> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cloud.coinbase.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Coinbase for Agents (CLI/MCP)

> Give your AI agent headless access to Coinbase. Trade crypto, manage portfolios, and check prices from the terminal or an MCP server.

The Coinbase CLI gives you headless access to [Coinbase Advanced Trade](https://www.coinbase.com/advanced-trade). Install once, authenticate with a CDP API key, and trade crypto with JSON output, order preview, and a built-in MCP server.

<CardGroup cols={2}>
  <Card title="Trade from the terminal" icon="terminal">
    Market and limit orders, portfolio management, and USDC/USD conversions from the command line.
  </Card>

  <Card title="AI-native" icon="microchip-ai">
    JSON output by default, an MCP server for agent tool-calling, and a bundled skill file for agent self-onboarding.
  </Card>

  <Card title="Preview before you execute" icon="eye">
    Every write operation supports `--dry-run` and order preview. See fees, slippage, and estimated fill price before committing.
  </Card>

  <Card title="Zero dependencies" icon="feather">
    A single ESM bundle on Node.js 22+. No runtime dependencies.
  </Card>
</CardGroup>

## Get started

The fastest way to get started is to point your AI agent at the setup instructions. Copy this into Claude Code, Cursor, Codex, or any coding agent:

```
Follow https://docs.cdp.coinbase.com/coinbase-cli/skill.md to install and configure the Coinbase CLI.
```

Your agent will install the CLI, walk you through API key creation, and verify the connection.

<Info>
  The [skill file](https://docs.cdp.coinbase.com/coinbase-cli/skill.md) is a machine-readable guide that teaches agents how to install, authenticate, and use the CLI. It covers every command and common workflows.
</Info>

### Manual install

If you prefer to set things up yourself:

#### 1. Install the CLI

```bash theme={null}
npm install -g @coinbase/coinbase-cli
coinbase --version
```

<Info>
  Node.js 22 or later is required.
</Info>

<Warning>
  **nvm/fnm users:** Each Node version has its own global packages. If you upgrade Node, reinstall the CLI in a new terminal:

  ```bash theme={null}
  npm install -g @coinbase/coinbase-cli
  ```
</Warning>

**Linux only**: install keyring support to keep secrets out of plaintext:

```bash theme={null}
which secret-tool || sudo apt install -y libsecret-tools
```

#### 2. Create a CDP API key

1. Go to [API Keys](https://portal.cdp.coinbase.com/projects/api-keys) in the CDP Portal (a project is auto-created on first sign-in)
2. Click **Create API Key** and give it a name (e.g., `my-trading-agent`)
3. Under **API restrictions**, enable **Trade** and **Transfer** (View is enabled by default)
4. Under **Advanced settings**, change the key type to **ECDSA**
5. Click **Create & Download** and save the JSON key file

<Warning>
  The key secret is only shown at creation time. The brokerage API requires ECDSA keys. Ed25519 keys return HTTP 401.
</Warning>

#### 3. Configure and verify

```bash theme={null}
coinbase env live --key-file <path-to-key.json>
coinbase env           # verify: shows "live" with your key ID
coinbase balance       # verify: returns JSON with account balances
```

#### 4. Check a price and place a trade

```bash theme={null}
# Get the current BTC price
coinbase products get BTC-USD --jq '.price'

# Preview a $10 market buy (shows fees + estimated fill price, does not execute)
coinbase orders preview product_id=BTC-USD side=BUY type=market quote_size=10

# Execute the trade with an idempotent order ID
coinbase orders create product_id=BTC-USD side=BUY type=market \
  quote_size=10 client_order_id=$(uuidgen)

# Check the order
coinbase orders get <order_id>
```

<Info>
  `client_order_id` makes the order idempotent. If your connection drops and you retry with the same ID, the API returns the existing order instead of creating a duplicate. Always include one.
</Info>

***

## Commands

### Market data

| Command                                                  | Description                                                          |
| -------------------------------------------------------- | -------------------------------------------------------------------- |
| `coinbase products get <product_id>`                     | Price, 24-hour volume/change, and size limits                        |
| `coinbase products list`                                 | All tradable products (900+ results, filter with `symbol` or `--jq`) |
| `coinbase products list symbol==USD`                     | Products with USD as the base or quote currency                      |
| `coinbase products ticker <product_id>`                  | Recent trades with best bid/ask                                      |
| `coinbase products book <product_id>`                    | Full order book (bids + asks)                                        |
| `coinbase products candles <product_id> granularity==1h` | OHLCV price history                                                  |
| `coinbase products best-bid-ask product_ids=BTC-USD`     | Current best bid and ask                                             |

### Orders

| Command                                                   | Description                                        |
| --------------------------------------------------------- | -------------------------------------------------- |
| `coinbase orders preview ...`                             | Dry-run: returns fill estimate, fees, and slippage |
| `coinbase orders create ...`                              | Execute an order                                   |
| `coinbase orders list`                                    | All orders with status, fill percentage, and fees  |
| `coinbase orders get <order_id>`                          | Single order detail                                |
| `coinbase orders fills`                                   | All trade fills with price, size, and commission   |
| `coinbase orders edit <order_id>`                         | Modify an existing order                           |
| `coinbase orders cancel order_ids:='["<id>"]'`            | Batch cancel orders                                |
| `coinbase orders close-position product_id=<id> size=<n>` | Close an open position                             |

**Market order**: executes immediately at the best available price.

```bash theme={null}
# Buy $100 of BTC (quote_size = USD amount to spend)
coinbase orders create product_id=BTC-USD side=BUY type=market quote_size=100

# Sell 0.5 ETH (base_size = amount of the asset to sell)
coinbase orders create product_id=ETH-USD side=SELL type=market base_size=0.5
```

**Limit order**: executes at the specified price or better.

```bash theme={null}
coinbase orders create product_id=BTC-USD side=BUY type=limit \
  base_size=0.001 limit_price=50000
```

<Info>
  Market buys use `quote_size` (the amount to spend in USD). Market sells use `base_size` (the amount of the asset to sell). When switching between buy and sell, explicitly clear the other field (e.g., add `quote_size=` to clear a stale value).
</Info>

### Portfolios and balances

| Command                                                           | Description                                                  |
| ----------------------------------------------------------------- | ------------------------------------------------------------ |
| `coinbase balance`                                                | All account balances (crypto + fiat)                         |
| `coinbase portfolios list`                                        | All portfolios with UUID, name, and type                     |
| `coinbase portfolios get <portfolio_id>`                          | Breakdown: balances, positions, allocation %, unrealized PnL |
| `coinbase portfolios create name=<name>`                          | Create a new portfolio                                       |
| `coinbase portfolios edit <portfolio_id> name=<n>`                | Rename a portfolio                                           |
| `coinbase portfolios delete <portfolio_id>`                       | Delete a portfolio (must be empty)                           |
| `coinbase transfer amount=<n> currency=<c> from=<uuid> to=<uuid>` | Move funds between portfolios                                |

### Conversions

| Command                                               | Description                         |
| ----------------------------------------------------- | ----------------------------------- |
| `coinbase convert quote from=<c> to=<c> amount=<n>`   | Get a conversion quote (rate + fee) |
| `coinbase convert execute <quote_id> from=<c> to=<c>` | Execute a quoted conversion         |
| `coinbase convert get <quote_id>`                     | Check conversion status             |

### Info and session

| Command         | Description                                    |
| --------------- | ---------------------------------------------- |
| `coinbase fees` | Fee tier (maker/taker rates) and 30-day volume |
| `coinbase env`  | View and manage credential environments        |
| `coinbase mcp`  | Start the MCP server (stdio)                   |

***

## Global flags

These flags work on any command:

| Flag          | What it does                                                                  | When to use                                                                      |
| ------------- | ----------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| `--template`  | Print the expected request body without sending                               | Before your first call to any command. Discover field names instead of guessing. |
| `--dry-run`   | Assemble the full request and print it without sending                        | Before any write operation to verify what will be sent                           |
| `--jq <expr>` | Filter the JSON response with a [jq](https://jqlang.github.io/jq/) expression | Extract specific fields: `--jq '.price'`, `--jq '.accounts[].currency'`          |
| `-e <env>`    | Override the active environment                                               | Switch between configured environments                                           |

## Field syntax

| Syntax       | Meaning                                    | Example                      |
| ------------ | ------------------------------------------ | ---------------------------- |
| `key=value`  | String body field                          | `product_id=BTC-USD`         |
| `key:=value` | Raw JSON (arrays, numbers, Boolean values) | `order_ids:='["abc","def"]'` |
| `key==value` | Query parameter                            | `product_type==SPOT`         |
| `@file.json` | Load body from a JSON file                 | `@order.json`                |

***

## MCP server

The CLI includes an [MCP](https://modelcontextprotocol.io) server that exposes every command as a typed tool. When your agent needs to check prices, preview orders, or manage portfolios, it calls the corresponding tool. The CLI handles auth, request formatting, and JSON parsing.

**Claude Code:**

```bash theme={null}
claude mcp add --scope user --transport stdio coinbase -- coinbase mcp
```

**Other MCP clients** (Cursor, Windsurf, etc.), add to your MCP config:

```json theme={null}
{
  "mcpServers": {
    "coinbase": {
      "command": "coinbase",
      "args": ["mcp"],
      "transport": "stdio"
    }
  }
}
```

**Without a global install**, use `npx`:

```json theme={null}
{
  "mcpServers": {
    "coinbase": {
      "command": "npx",
      "args": ["-y", "@coinbase/coinbase-cli", "mcp"],
      "transport": "stdio"
    }
  }
}
```

<Info>
  The MCP server runs on stdio (no network ports opened) and uses the same credentials configured with `coinbase env`.
</Info>

***

## Troubleshooting

| Error                              | Cause                                        | Fix                                                                                               |
| ---------------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| `HTTP 401`                         | Ed25519 key or expired credentials           | Create a new **ECDSA** key in the [CDP Portal](https://portal.cdp.coinbase.com/projects/api-keys) |
| `HTTP 403 Missing required scopes` | API key missing Trade or Transfer permission | Check key permissions in the Portal                                                               |
| `insufficient fund`                | Account balance too low                      | Run `coinbase balance` to check available funds                                                   |
| `coinbase: command not found`      | CLI not on PATH                              | Run `npm install -g @coinbase/coinbase-cli`; on Windows, add `%APPDATA%\npm` to PATH              |
| `MISSING_FIELDS`                   | Required fields not provided                 | Run `coinbase <command> --template` to see expected fields                                        |
| `INVALID_VALUE`                    | Unrecognized enum value                      | Check the error message for accepted values                                                       |
| `INVALID_FORMAT`                   | Wrong date/time format                       | Use RFC 3339 with timezone (e.g., `2024-01-01T00:00:00Z`)                                         |
