---
title: MCP
description: Use @codespar/mcp to connect CodeSpar tools to Claude Desktop, Cursor, and other MCP-compatible clients.
---

import { Callout } from "fumadocs-ui/components/callout";
import { Tab, Tabs } from "fumadocs-ui/components/tabs";
import { Steps, Step } from "fumadocs-ui/components/steps";

# MCP Adapter

<VersionBadge pkg="@codespar/mcp" />

The `@codespar/mcp` adapter exposes CodeSpar tools as an MCP (Model Context Protocol) server, allowing you to use them in **Claude Desktop**, **Cursor**, **Windsurf**, and any other MCP-compatible client. No code required -- configure the MCP server, restart your client, and the meta-tools appear in the tool palette.

This is the fastest way to try CodeSpar. If you already use Claude Desktop or Cursor, you can be up and running in under 2 minutes.

## Installation

<Tabs items={["npm", "pnpm", "yarn"]}>
<Tab value="npm">
```bash
npm install -g @codespar/mcp
```
</Tab>
<Tab value="pnpm">
```bash
pnpm add -g @codespar/mcp
```
</Tab>
<Tab value="yarn">
```bash
yarn global add @codespar/mcp
```
</Tab>
</Tabs>

<Callout type="info">
You do not need to install globally. The MCP configuration below uses `npx`, which will download and run `@codespar/mcp` automatically. Global installation is only needed if you want to avoid the `npx` startup delay.
</Callout>

## First run and `codespar_get_started`

You do not need a valid API key just to boot the server. If `CODESPAR_API_KEY` is missing or invalid, the server starts in a guided **setup mode** instead of crashing: it stays connected to the client and exposes a single tool, `codespar_get_started`, that walks the agent through minting a key and validating the connection.

In setup mode the agent can:

1. Call `codespar_get_started` to learn why the full tool palette is not loaded (no key, or a key that failed validation).
2. Follow the returned steps to mint a key at [Dashboard -> API Keys](https://codespar.dev/dashboard/api-keys).
3. Re-validate: once a working `csk_` key is in place and the server restarts, the full meta-tool palette replaces the setup tool.

This means a fresh `npx @codespar/mcp serve` in Claude Desktop, Cursor, or any other client always produces a usable server; the agent itself can guide the user through the remaining setup instead of surfacing a startup crash.

## Hosted remote MCP

You can skip the local process entirely. CodeSpar hosts a remote MCP endpoint that any remote-capable client can connect to with one URL:

```
https://connect.codespar.dev/mcp
```

- **Transport:** Streamable HTTP.
- **Auth:** either a bearer key (`Authorization: Bearer csk_live_...` or `csk_test_...`) or **OAuth 2.1**, with protected-resource discovery served at `/.well-known/oauth-protected-resource` on the same host (RFC 9728), so OAuth-capable clients can discover the authorization server automatically.
- **Surface:** the same 14 meta-tools and the same governance (policy engine, credential vault, audit chain) as the stdio server; only the transport differs.

For Claude Code, setup is one line:

```bash
claude mcp add --transport http codespar https://connect.codespar.dev/mcp --header "Authorization: Bearer <key>"
```

Clients that speak OAuth 2.1 can omit the header and complete the browser flow on first connect.

## API Reference

### `getMcpConfig(options): McpConfig`

Returns a generic MCP server configuration object that can be used with any MCP-compatible client. This is the base function -- the client-specific helpers below call it internally.

```typescript
import { getMcpConfig } from "@codespar/mcp";

const config = getMcpConfig({
  apiKey: process.env.CODESPAR_API_KEY,
  servers: ["stripe", "mercadopago", "correios"],
});

console.log(JSON.stringify(config, null, 2));
```

```json title="Output"
{
  "command": "npx",
  "args": ["@codespar/mcp", "serve", "--servers", "stripe,mercadopago,correios"],
  "env": {
    "CODESPAR_API_KEY": "csk_live_..."
  }
}
```

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `apiKey` | `string` | Yes | Your CodeSpar API key (`csk_live_` or `csk_test_`) |
| `servers` | `string[]` | No | MCP servers to connect. Omit to connect all available servers. |

### `getClaudeDesktopConfig(options): ClaudeDesktopConfig`

Returns a configuration snippet ready to paste into Claude Desktop's `claude_desktop_config.json`. The output is the complete `mcpServers` block.

```typescript
import { getClaudeDesktopConfig } from "@codespar/mcp";

const config = getClaudeDesktopConfig({
  apiKey: "csk_live_your_key_here",
  servers: ["stripe", "asaas", "correios", "twilio"],
});

console.log(JSON.stringify(config, null, 2));
```

```json title="Output"
{
  "mcpServers": {
    "codespar": {
      "command": "npx",
      "args": ["@codespar/mcp", "serve", "--servers", "stripe,asaas,correios,twilio"],
      "env": {
        "CODESPAR_API_KEY": "csk_live_your_key_here"
      }
    }
  }
}
```

### `getCursorConfig(options): CursorConfig`

Returns a configuration snippet for Cursor's MCP settings file (`.cursor/mcp.json`).

```typescript
import { getCursorConfig } from "@codespar/mcp";

const config = getCursorConfig({
  apiKey: "csk_live_your_key_here",
  servers: ["stripe", "twilio"],
});

console.log(JSON.stringify(config, null, 2));
```

```json title="Output"
{
  "mcpServers": {
    "codespar": {
      "command": "npx",
      "args": ["@codespar/mcp", "serve", "--servers", "stripe,twilio"],
      "env": {
        "CODESPAR_API_KEY": "csk_live_your_key_here"
      }
    }
  }
}
```

## Setup guides

<Tabs items={["Claude Desktop", "Cursor", "Windsurf", "Custom MCP Client"]}>

<Tab value="Claude Desktop">
### Claude Desktop

<Steps>
<Step>
Open Claude Desktop and go to **Settings** (gear icon).
</Step>
<Step>
Navigate to **Developer** and click **Edit Config**. This opens the `claude_desktop_config.json` file.
</Step>
<Step>
Add the CodeSpar MCP server configuration. If you already have other MCP servers configured, add the `codespar` entry to the existing `mcpServers` object:

```json title="claude_desktop_config.json"
{
  "mcpServers": {
    "codespar": {
      "command": "npx",
      "args": ["@codespar/mcp", "serve"],
      "env": {
        "CODESPAR_API_KEY": "csk_live_your_key_here"
      }
    }
  }
}
```

To limit which servers are accessible, add the `--servers` flag:

```json title="claude_desktop_config.json (with specific servers)"
{
  "mcpServers": {
    "codespar": {
      "command": "npx",
      "args": ["@codespar/mcp", "serve", "--servers", "stripe,mercadopago,correios"],
      "env": {
        "CODESPAR_API_KEY": "csk_live_your_key_here"
      }
    }
  }
}
```
</Step>
<Step>
Save the file and **restart Claude Desktop**.
</Step>
<Step>
Look for the hammer icon in the chat input. Click it to see the list of available CodeSpar tools. You should see the 14-tool meta-tool palette: `codespar_discover`, `codespar_charge`, `codespar_pay`, `codespar_checkout`, `codespar_shop`, `codespar_wallet`, `codespar_invoice`, `codespar_ship`, `codespar_notify`, `codespar_crypto_pay`, `codespar_kyc`, `codespar_ledger`, `codespar_issue`, and `codespar_manage_connections`.
</Step>
</Steps>

<Callout type="info">
Claude Desktop discovers all meta-tools automatically. You can now ask Claude to process payments, create invoices, ship packages, run KYC, and send notifications -- all from the chat interface.
</Callout>
**Example prompts to try:**

- "Discover what payment tools are available"
- "Create a R$49.90 Pix charge for the Pro Plan using Asaas"
- "Generate a Pix QR code for R$250"
- "Check shipping rates from Sao Paulo to Rio de Janeiro for a 2kg package"
- "Send an order confirmation via WhatsApp to +5511999887766"
</Tab>

<Tab value="Cursor">
### Cursor

<Steps>
<Step>
Create a `.cursor` directory in your project root (if it does not exist) and add an `mcp.json` file:

```json title=".cursor/mcp.json"
{
  "mcpServers": {
    "codespar": {
      "command": "npx",
      "args": ["@codespar/mcp", "serve"],
      "env": {
        "CODESPAR_API_KEY": "csk_live_your_key_here"
      }
    }
  }
}
```
</Step>
<Step>
Restart Cursor or reload the window (`Cmd+Shift+P` then "Developer: Reload Window").
</Step>
<Step>
Open the Cursor agent panel (`Cmd+L` or the chat sidebar). CodeSpar tools are now available in agent mode. You can ask the agent to perform commerce operations directly.
</Step>
</Steps>

<Callout type="info">
The `.cursor/mcp.json` file is project-scoped. Add it to `.gitignore` if it contains your API key, or use environment variables in your shell profile and reference them in the config.
</Callout>
**To use global Cursor MCP settings instead:**

1. Open Cursor settings (`Cmd+,`)
2. Search for "MCP" in the settings search bar
3. Add the same configuration in the global MCP settings field
</Tab>

<Tab value="Windsurf">
### Windsurf

<Steps>
<Step>
Open Windsurf settings and navigate to the MCP configuration section.
</Step>
<Step>
Add the CodeSpar MCP server:

```json title="Windsurf MCP config"
{
  "mcpServers": {
    "codespar": {
      "command": "npx",
      "args": ["@codespar/mcp", "serve"],
      "env": {
        "CODESPAR_API_KEY": "csk_live_your_key_here"
      }
    }
  }
}
```
</Step>
<Step>
Restart Windsurf. CodeSpar tools will appear in the agent's available tools list.
</Step>
</Steps>
</Tab>

<Tab value="Custom MCP Client">
### Custom MCP Client

If you are building your own MCP client or integrating with a less common one, use the generic `getMcpConfig` function:

```typescript title="custom-client.ts"
import { getMcpConfig } from "@codespar/mcp";

const config = getMcpConfig({
  apiKey: process.env.CODESPAR_API_KEY,
  servers: ["stripe", "mercadopago", "correios", "twilio"],
});

// Pass this config to your MCP client implementation
// The MCP server will spawn as a child process using the command and args
```

The MCP server exposes tools following the [Model Context Protocol specification](https://modelcontextprotocol.io/). Each tool includes:

| Field | Type | Description |
|-------|------|-------------|
| `name` | `string` | Tool identifier (e.g., `codespar_charge`) |
| `description` | `string` | Human-readable description of what the tool does |
| `inputSchema` | `JSONSchema` | JSON Schema defining the tool's parameters |

**Example tool listing from the MCP server:**

```json
{
  "tools": [
    {
      "name": "codespar_discover",
      "description": "Semantic + lexical tool search across the catalog (biased toward connected providers)",
      "inputSchema": {
        "type": "object",
        "properties": {
          "query": { "type": "string" },
          "limit": { "type": "number" }
        },
        "required": ["query"]
      }
    },
    {
      "name": "codespar_charge",
      "description": "Create an inbound charge (buyer pays merchant) — Pix / boleto / card",
      "inputSchema": {
        "type": "object",
        "properties": {
          "provider": { "type": "string" },
          "amount": { "type": "number" },
          "currency": { "type": "string" },
          "description": { "type": "string" },
          "payment_methods": {
            "type": "array",
            "items": { "type": "string" }
          }
        },
        "required": ["provider", "amount", "currency"]
      }
    }
  ]
}
```
</Tab>

</Tabs>

## Specifying servers

By default, the MCP adapter connects to all available servers. You can limit which servers are accessible using the `--servers` flag. This is useful for scoping the tool set to a specific domain:

```json title="Payments only"
{
  "mcpServers": {
    "codespar-payments": {
      "command": "npx",
      "args": ["@codespar/mcp", "serve", "--servers", "stripe,mercadopago,asaas"],
      "env": {
        "CODESPAR_API_KEY": "csk_live_your_key_here"
      }
    }
  }
}
```

You can also run multiple CodeSpar MCP servers with different scopes:

```json title="Multiple scoped servers"
{
  "mcpServers": {
    "codespar-payments": {
      "command": "npx",
      "args": ["@codespar/mcp", "serve", "--servers", "stripe,mercadopago"],
      "env": {
        "CODESPAR_API_KEY": "csk_live_your_key_here"
      }
    },
    "codespar-logistics": {
      "command": "npx",
      "args": ["@codespar/mcp", "serve", "--servers", "correios,jadlog,melhorenvio"],
      "env": {
        "CODESPAR_API_KEY": "csk_live_your_key_here"
      }
    }
  }
}
```

<Callout type="info">
Scoping servers improves tool selection accuracy. When the model has fewer tools to choose from, it makes better decisions about which one to call.
</Callout>
## Using sandbox keys

For testing, use a `csk_test_` API key. The MCP server will route all tool calls to sandbox servers that return realistic mock data:

```json title="Sandbox configuration"
{
  "mcpServers": {
    "codespar-sandbox": {
      "command": "npx",
      "args": ["@codespar/mcp", "serve"],
      "env": {
        "CODESPAR_API_KEY": "csk_test_your_key_here"
      }
    }
  }
}
```

<Callout type="info">
Sandbox and production share the same tool interface. Switching from test to live is a single environment variable change.
</Callout>
## Troubleshooting

### Tools do not appear after restart

1. **Verify the config file location.** Claude Desktop looks for `claude_desktop_config.json` in:
   - macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
   - Windows: `%APPDATA%\Claude\claude_desktop_config.json`
   - Linux: `~/.config/Claude/claude_desktop_config.json`

2. **Validate JSON syntax.** A missing comma or bracket will silently fail. Use `cat claude_desktop_config.json | python3 -m json.tool` to validate.

3. **Check that `npx` is available.** Open a terminal and run `npx --version`. If it is not installed, install Node.js 18+.

4. **Check the API key.** Ensure it starts with `csk_live_` or `csk_test_`. Keys are case-sensitive.

### MCP server crashes on startup

Check the MCP server logs:

- **Claude Desktop:** Open the developer console (`Cmd+Option+I` on macOS) and look for MCP-related errors.
- **Cursor:** Check the Output panel (`Cmd+Shift+U`) and select "MCP" from the dropdown.

Common causes:

| Symptom | Cause | Fix |
|---------|-------|-----|
| `ENOENT: npx not found` | Node.js not in PATH | Add Node.js to your shell PATH or use the full path to `npx` in the config |
| `INVALID_API_KEY` | Wrong or missing API key | Verify the key in your dashboard at [Dashboard → API Keys](https://codespar.dev/dashboard/api-keys) |
| `EACCES: permission denied` | npm cache permissions | Run `sudo chown -R $(whoami) ~/.npm` on macOS/Linux |
| `TIMEOUT` | Network issues | Check your internet connection and verify `api.codespar.dev` is reachable |

### Tool calls return errors

If the MCP server is running but tool calls fail:

1. **Check server availability.** Not every server is available in every region. Use `codespar_discover` to see which servers are active for your account.
2. **Verify parameters.** Tool call errors often come from missing required parameters. Check the tool's `inputSchema` for required fields.
3. **Check rate limits.** Sandbox keys have lower rate limits than production keys.

### Slow startup

The first run with `npx` downloads the `@codespar/mcp` package, which takes a few seconds. Subsequent runs use the cached version. To eliminate this delay, install globally:

```bash
npm install -g @codespar/mcp
```

Then update the config to use the global binary:

```json
{
  "mcpServers": {
    "codespar": {
      "command": "codespar-mcp",
      "args": ["serve"],
      "env": {
        "CODESPAR_API_KEY": "csk_live_your_key_here"
      }
    }
  }
}
```

## Next steps

<NextStepsGrid items={[
  { label: "DOCS", title: "Introduction", description: "Architecture overview and the Complete Loop.", href: "/docs" },
  { label: "CONCEPT", title: "Sessions", description: "How sessions and servers work under the hood.", href: "/docs/concepts/sessions" },
  { label: "CONCEPT", title: "Tools & Meta-Tools", description: "The meta-tool layer explained in detail.", href: "/docs/concepts/tools" },
  { label: "PROVIDER", title: "Claude Adapter", description: "Programmatic integration with the Anthropic SDK.", href: "/docs/providers/claude" },
  { label: "PROVIDER", title: "OpenAI Adapter", description: "Programmatic integration with the OpenAI SDK.", href: "/docs/providers/openai" },
  { label: "QUICKSTART", title: "Quickstart", description: "End-to-end setup for programmatic usage.", href: "/docs/quickstart" },
]} />
