> ## Documentation Index
> Fetch the complete documentation index at: https://code.dcycle.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> Learn how to authenticate with Dcycle across API, CLI, and MCP integrations

# Authentication

Dcycle supports multiple authentication methods depending on how you're integrating:

<CardGroup cols={3}>
  <Card title="API Keys" icon="key" href="#api-key-authentication">
    For REST API and programmatic integrations
  </Card>

  <Card title="CLI Login" icon="terminal" href="#cli-authentication">
    For command-line tool access
  </Card>

  <Card title="MCP Setup" icon="robot" href="#mcp-authentication">
    For AI assistant integrations
  </Card>
</CardGroup>

***

## API Key Authentication

API Keys are the primary method for authenticating with the Dcycle REST API.

### When to Use API Keys

* Server-to-server integrations
* Automated scripts and CI/CD pipelines
* Backend applications
* Any programmatic access

### Get an API Key

<Steps>
  <Step title="Log in to Dcycle">
    Go to [app.dcycle.io](https://app.dcycle.io)
  </Step>

  <Step title="Navigate to API Keys">
    **Organization Settings → API Keys**
  </Step>

  <Step title="Generate a new key">
    Click **"Generate API Key"**

    <Warning>
      The API Key is only shown **once**. Save it immediately.
    </Warning>
  </Step>
</Steps>

### User Attribution & Accountability

<Warning>
  **Important**: When you create an API key, you are authorizing it to perform actions **on your behalf**. All data uploaded using that key will be attributed to you (the API key creator) for audit and compliance purposes.
</Warning>

This means:

* ✅ All records created via your API key are linked to your user account
* ✅ Audit logs will show you as the creator of the data
* ✅ This ensures proper data governance and traceability
* ✅ You are responsible for the data uploaded using your API keys

<Tip>
  **Best Practice**: Create separate API keys for different environments (dev, staging, prod) and name them descriptively (e.g., "Production ETL Pipeline", "Testing Environment") to easily track their usage.
</Tip>

### Using your API Key

Include your API Key in requests using the appropriate format for your API version:

<Tabs>
  <Tab title="New API (Recommended)">
    <CodeGroup>
      ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
      # New API endpoints (e.g., /v1/logistics/requests)
      curl -X POST "https://api.dcycle.io/v1/logistics/requests" \
        -H "x-api-key: your-api-key-here" \
        -H "x-organization-id: your-org-id" \
        -H "Content-Type: application/json" \
        -d '{ "origin": "Barcelona", "destination": "Madrid" }'
      ```

      ```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
      import requests

      # Simpler - only 2 headers needed!
      headers = {
          "x-api-key": api_key,
          "x-organization-id": org_id,
      }

      response = requests.post(
          "https://api.dcycle.io/v1/logistics/requests",
          headers=headers,
          json={"origin": "Barcelona", "destination": "Madrid"}
      )
      ```

      ```javascript JavaScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
      // Simpler - only 2 headers needed!
      const headers = {
        'x-api-key': apiKey,
        'x-organization-id': orgId,
      };

      fetch('https://api.dcycle.io/v1/logistics/requests', {
        method: 'POST',
        headers,
        body: JSON.stringify({ origin: 'Barcelona', destination: 'Madrid' })
      })
        .then(res => res.json())
        .then(data => console.log(data));
      ```
    </CodeGroup>
  </Tab>

  <Tab title="Legacy API">
    <CodeGroup>
      ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
      # Legacy API endpoints (e.g., /api/facilities)
      curl -X GET "https://api.dcycle.io/api/facilities" \
        -H "Authorization: Bearer your-api-key-here" \
        -H "x-organization-id: your-org-id" \
        -H "x-user-id: your-user-id"
      ```

      ```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
      import requests

      # Legacy format - 3 headers required
      headers = {
          "Authorization": f"Bearer {api_key}",
          "x-organization-id": org_id,
          "x-user-id": user_id
      }

      response = requests.get(
          "https://api.dcycle.io/api/facilities",
          headers=headers
      )
      ```

      ```javascript JavaScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
      // Legacy format - 3 headers required
      const headers = {
        'Authorization': `Bearer ${apiKey}`,
        'x-organization-id': orgId,
        'x-user-id': userId
      };

      fetch('https://api.dcycle.io/api/facilities', { headers })
        .then(res => res.json())
        .then(data => console.log(data));
      ```
    </CodeGroup>
  </Tab>
</Tabs>

### Required Headers

<Tabs>
  <Tab title="New API (Recommended)">
    **Simpler authentication** - Only 2 required headers:

    | Header              | Description                 | Required          |
    | ------------------- | --------------------------- | ----------------- |
    | `x-api-key`         | Your API Key                | ✅ Yes             |
    | `x-organization-id` | Your organization UUID      | ✅ Yes             |
    | `Content-Type`      | Content type (for POST/PUT) | Only for POST/PUT |

    <Info>
      **No `x-user-id` needed!** Operations are automatically attributed to the user who created the API key.
    </Info>
  </Tab>

  <Tab title="Legacy API">
    **Legacy format** - 3 required headers:

    | Header              | Description                    | Required          |
    | ------------------- | ------------------------------ | ----------------- |
    | `Authorization`     | Bearer token with your API Key | ✅ Yes             |
    | `x-organization-id` | Your organization UUID         | ✅ Yes             |
    | `x-user-id`         | Your user UUID                 | ✅ Yes             |
    | `Content-Type`      | Content type (for POST/PUT)    | Only for POST/PUT |
  </Tab>
</Tabs>

***

## CLI Authentication

<Note>
  **Early Access** - The Dcycle CLI is currently available for enterprise customers.
  [Contact us](/docs/support) to learn more about access.
</Note>

The CLI (`dcy` command) supports two authentication methods: interactive login and environment variables.

### Interactive Login

The simplest way to authenticate:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
dcy auth login
```

This opens your browser to the Dcycle sign-in page. You complete the full authentication flow in the browser (email, password, MFA, SSO) and the CLI receives the session automatically.

Use `--no-browser` to authenticate directly in the terminal instead:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
dcy auth login --no-browser
```

Your session persists until you explicitly log out.

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Check current authentication status
dcy auth status

# Log out
dcy auth logout
```

### Environment Variables

For automated scripts and CI/CD pipelines, use environment variables:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
export DCYCLE_API_KEY=your_api_key
export DCYCLE_ORG_ID=your_org_id

# Commands use environment automatically
dcy vehicle list
dcy facility list
```

<Tip>
  Environment variables take precedence over interactive login. This is useful for running scripts with different credentials than your personal account.
</Tip>

### Configuration File

The CLI stores configuration in `~/.config/dcycle/v2/config.yaml`:

```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
# ~/.config/dcycle/v2/config.yaml
host: https://api.dcycle.io
organization_id: your-org-id
```

You can manage configuration via commands:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Set active organization
dcy org set YOUR_ORG_ID

# Change API environment
dcy config host set prod
```

[Learn more about CLI authentication →](/cli/authentication)

***

## MCP Authentication

<Info>
  **Coming Soon** - The Dcycle MCP Server is in private beta.
  [Contact us](/docs/support) for early access.
</Info>

The MCP (Model Context Protocol) Server uses your API key for authentication with AI assistants like Claude.

### Claude Desktop Configuration

Add to your Claude Desktop config (`~/Library/Application Support/Claude/claude_desktop_config.json`):

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "mcpServers": {
    "dcycle": {
      "command": "uvx",
      "args": ["dcycle-mcp"],
      "env": {
        "DCYCLE_API_KEY": "your_api_key"
      }
    }
  }
}
```

### Claude Code Configuration

For Claude Code, add to `~/.claude/settings.json`:

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "mcpServers": {
    "dcycle": {
      "command": "uvx",
      "args": ["dcycle-mcp"],
      "env": {
        "DCYCLE_API_KEY": "your_api_key"
      }
    }
  }
}
```

[Learn more about MCP setup →](/mcp/quickstart)

***

## JWT Tokens (Web Applications)

JWT tokens are ideal for web and mobile applications acting on behalf of users.

### Get a JWT Token

<Steps>
  <Step title="Login with email and password">
    ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
    curl -X POST "https://api.dcycle.io/auth/login" \
      -H "Content-Type: application/json" \
      -d '{
        "email": "your-email@example.com",
        "password": "your-password"
      }'
    ```
  </Step>

  <Step title="Extract the token from response">
    ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
    {
      "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
      "token_type": "Bearer",
      "expires_in": 3600
    }
    ```
  </Step>

  <Step title="Use the token in your requests">
    Include the token in the `Authorization` header:

    ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
    curl -X GET "https://api.dcycle.io/v1/facilities" \
      -H "Authorization: Bearer eyJhbGciOiJSUzI1NiIs..." \
      -H "x-organization-id: your-org-id" \
      -H "x-user-id: your-user-id"
    ```
  </Step>
</Steps>

### Token Expiration

JWT tokens expire after **1 hour**. When a token expires, you'll get a `401 Unauthorized` error. You'll need to log in again to get a new token.

<Tip>
  **Tip**: Implement automatic refresh in your application to renew tokens before they expire.
</Tip>

***

## Security Best Practices

<AccordionGroup>
  <Accordion title="Never expose your API Key">
    * ❌ **DON'T** save API Keys in source code
    * ❌ **DON'T** commit them to Git/GitHub
    * ❌ **DON'T** share them via email or Slack
    * ✅ **DO** use environment variables
    * ✅ **DO** use secret managers (AWS Secrets Manager, etc.)
  </Accordion>

  <Accordion title="Always use HTTPS">
    All API requests **must** use HTTPS. HTTP requests will be rejected.
  </Accordion>

  <Accordion title="Rotate your API Keys regularly">
    * Generate new API Keys every 3-6 months
    * Delete old API Keys immediately after migration
    * Use different API Keys for different environments (dev, staging, prod)
  </Accordion>

  <Accordion title="Environment-specific credentials">
    Use separate credentials for each environment:

    ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
    # Development
    export DCYCLE_API_KEY=$DEV_API_KEY

    # Production
    export DCYCLE_API_KEY=$PROD_API_KEY
    ```

    For CI/CD, store secrets in your pipeline's secret management (GitHub Secrets, GitLab CI Variables, etc.).
  </Accordion>
</AccordionGroup>

## API Key Management

### List your API Keys

You can view all your active API Keys at:
**[app.dcycle.io/settings/api](https://app.dcycle.io/settings/api)**

### Revoke an API Key

If an API Key has been compromised or you no longer need it:

1. Go to **Organization Settings → API Keys**
2. Find the API Key in the list
3. Click **"Revoke"**

<Warning>
  Once revoked, the API Key will stop working **immediately**. This action cannot be undone.
</Warning>

## Troubleshooting

### Error 401: Unauthorized

**Possible causes:**

* Invalid or revoked API Key
* Expired JWT token
* Incorrect `Authorization` header format
* Organization doesn't have API enabled

**Solution:**

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Verify you're using the correct format
Authorization: Bearer your-api-key-or-jwt-token
```

### Error 403: Forbidden

**Possible causes:**

* User doesn't belong to the specified organization
* Missing `x-organization-id` header
* Organization doesn't have permissions for that resource

**Solution:**
Verify that the `x-organization-id` corresponds to your organization.

## Next Steps

<CardGroup cols={3}>
  <Card title="API Quickstart" icon="code" href="/docs/quickstart#api-quickstart">
    Make your first API call
  </Card>

  <Card title="CLI Overview" icon="terminal" href="/cli/overview">
    Get started with the CLI
  </Card>

  <Card title="MCP Setup" icon="robot" href="/mcp/quickstart">
    Configure AI assistant integration
  </Card>
</CardGroup>
