Connect Claude Code to tools via MCP

Tags

official-docs claude-code-cli

Content

Documentation Index

Fetch the complete documentation index at: https://code.claude.com/docs/llms.txt Use this file to discover all available pages before exploring further.

Connect Claude Code to tools via MCP

Learn how to connect Claude Code to your tools with the Model Context Protocol.

export const MCPServersTable = ({platform = "all"}) => { const ifYouAreAnAiAgentReadingThisYouShouldInsteadFetch = 'https://api.anthropic.com/mcp-registry/docs'; const [servers, setServers] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchServers = async () => { try { setLoading(true); const allServers = []; let cursor = null; do { const url = new URL('https://api.anthropic.com/mcp-registry/v0/servers'); url.searchParams.set('version', 'latest'); url.searchParams.set('visibility', 'commercial'); url.searchParams.set('limit', '100'); if (cursor) { url.searchParams.set('cursor', cursor); } const response = await fetch(url); if (!response.ok) { throw new Error(Failed to fetch MCP registry: ${response.status}); } const data = await response.json(); allServers.push(...data.servers); cursor = data.metadata?.nextCursor || null; } while (cursor); const transformedServers = allServers.map(item => { const server = item.server; const meta = item._meta?.['com.anthropic.api/mcp-registry'] || ({}); const worksWith = meta.worksWith || []; const availability = { claudeCode: worksWith.includes('claude-code'), mcpConnector: worksWith.includes('claude-api'), claudeDesktop: worksWith.includes('claude-desktop') }; const remotes = server.remotes || []; const httpRemote = remotes.find(r => r.type === 'streamable-http'); const sseRemote = remotes.find(r => r.type === 'sse'); const preferredRemote = httpRemote || sseRemote; const remoteUrl = preferredRemote?.url || meta.url; const remoteType = preferredRemote?.type; const isTemplatedUrl = remoteUrl?.includes('{'); let setupUrl; if (isTemplatedUrl && meta.requiredFields) { const urlField = meta.requiredFields.find(f => f.field === 'url'); setupUrl = urlField?.sourceUrl || meta.documentation; } const urls = {}; if (!isTemplatedUrl) { if (remoteType === 'streamable-http') { urls.http = remoteUrl; } else if (remoteType === 'sse') { urls.sse = remoteUrl; } } let envVars = []; if (server.packages && server.packages.length > 0) { const npmPackage = server.packages.find(p => p.registryType === 'npm'); if (npmPackage) { urls.stdio = npx -y ${npmPackage.identifier}; if (npmPackage.environmentVariables) { envVars = npmPackage.environmentVariables; } } } return { name: meta.displayName || server.title || server.name, description: meta.oneLiner || server.description, documentation: meta.documentation, urls: urls, envVars: envVars, availability: availability, customCommands: meta.claudeCodeCopyText ? { claudeCode: meta.claudeCodeCopyText } : undefined, setupUrl: setupUrl }; }); setServers(transformedServers); setError(null); } catch (err) { setError(err.message); console.error('Error fetching MCP registry:', err); } finally { setLoading(false); } }; fetchServers(); }, []); const generateClaudeCodeCommand = server => { if (server.customCommands && server.customCommands.claudeCode) { return server.customCommands.claudeCode.replace('--transport streamable-http', '--transport http'); } const serverSlug = server.name.toLowerCase().replace(/[^a-z0-9]/g, '-'); if (server.urls.http) { return claude mcp add ${serverSlug} --transport http ${server.urls.http}; } if (server.urls.sse) { return claude mcp add ${serverSlug} --transport sse ${server.urls.sse}; } if (server.urls.stdio) { const envFlags = server.envVars && server.envVars.length > 0 ? server.envVars.map(v => --env ${v.name}=YOUR_${v.name}).join(' ') : ''; const baseCommand = claude mcp add ${serverSlug} --transport stdio; return envFlags ? ${baseCommand} ${envFlags} -- ${server.urls.stdio} : ${baseCommand} -- ${server.urls.stdio}; } return null; }; if (loading) { return

Loading MCP servers...
; } if (error) { return
Error loading MCP servers: {error}
; } const filteredServers = servers.filter(server => { if (platform === "claudeCode") { return server.availability.claudeCode; } else if (platform === "mcpConnector") { return server.availability.mcpConnector; } else if (platform === "claudeDesktop") { return server.availability.claudeDesktop; } else if (platform === "all") { return true; } else { throw new Error(Unknown platform: ${platform}); } }); return <>

  <div className="cards-container">
    {filteredServers.map(server => {
const claudeCodeCommand = generateClaudeCodeCommand(server);
const mcpUrl = server.urls.http || server.urls.sse;
const commandToShow = platform === "claudeCode" ? claudeCodeCommand : mcpUrl;
return <div key={server.name} className="server-card">
          <div>
            {server.documentation ? <a href={server.documentation}>
                <strong>{server.name}</strong>
              </a> : <strong>{server.name}</strong>}
          </div>

          <p style={{
  margin: '0.5rem 0',
  fontSize: '0.9rem'
}}>
            {server.description}
          </p>

          {server.setupUrl && <p style={{
  margin: '0.25rem 0',
  fontSize: '0.8rem',
  fontStyle: 'italic',
  opacity: 0.7
}}>
              Requires user-specific URL.{' '}
              <a href={server.setupUrl} style={{
  textDecoration: 'underline'
}}>
                Get your URL here
              </a>.
            </p>}

          {commandToShow && !server.setupUrl && <>
            <p style={{
  display: 'block',
  fontSize: '0.75rem',
  fontWeight: 500,
  minWidth: 'fit-content',
  marginTop: '0.5rem',
  marginBottom: 0
}}>
              {platform === "claudeCode" ? "Command" : "URL"}
            </p>
            <div className="command-row">
              <code>
                {commandToShow}
              </code>
            </div>
          </>}
        </div>;

})} </>; };

Claude Code can connect to hundreds of external tools and data sources through the Model Context Protocol (MCP), an open source standard for AI-tool integrations. MCP servers give Claude Code access to your tools, databases, and APIs.

Connect a server when you find yourself copying data into chat from another tool, like an issue tracker or a monitoring dashboard. Once connected, Claude can read and act on that system directly instead of working from what you paste.

What you can do with MCP

With MCP servers connected, you can ask Claude Code to:

Here are some commonly used MCP servers you can connect to Claude Code:

Use third party MCP servers at your own risk - Anthropic has not verified the correctness or security of all these servers. Make sure you trust MCP servers you are installing. Be especially careful when using MCP servers that could fetch untrusted content, as these can expose you to prompt injection risk.

Need a specific integration? Find hundreds more MCP servers on GitHub, or build your own using the MCP SDK.

Installing MCP servers

MCP servers can be configured in three different ways depending on your needs:

Option 1: Add a remote HTTP server

HTTP servers are the recommended option for connecting to remote MCP servers. This is the most widely supported transport for cloud-based services.

```bash theme={null}

Basic syntax

claude mcp add --transport http

Real example: Connect to Notion

claude mcp add --transport http notion https://mcp.notion.com/mcp

Example with Bearer token

claude mcp add --transport http secure-api https://api.example.com/mcp \ --header "Authorization: Bearer your-token"


### Option 2: Add a remote SSE server

<Warning>
  The SSE (Server-Sent Events) transport is deprecated. Use HTTP servers instead, where available.
</Warning>

```bash theme={null}
# Basic syntax
claude mcp add --transport sse <name> <url>

# Real example: Connect to Asana
claude mcp add --transport sse asana https://mcp.asana.com/sse

# Example with authentication header
claude mcp add --transport sse private-api https://api.company.com/sse \
  --header "X-API-Key: your-key-here"

Option 3: Add a local stdio server

Stdio servers run as local processes on your machine. They're ideal for tools that need direct system access or custom scripts.

```bash theme={null}

Basic syntax

claude mcp add [options] -- [args...]

Real example: Add Airtable server

claude mcp add --transport stdio --env AIRTABLE_API_KEY=YOUR_KEY airtable \ -- npx -y airtable-mcp-server


<Note>
  **Important: Option ordering**

  All options (`--transport`, `--env`, `--scope`, `--header`) must come **before** the server name. The `--` (double dash) then separates the server name from the command and arguments that get passed to the MCP server.

  For example:

  * `claude mcp add --transport stdio myserver -- npx server` → runs `npx server`
  * `claude mcp add --transport stdio --env KEY=value myserver -- python server.py --port 8080` → runs `python server.py --port 8080` with `KEY=value` in environment

  This prevents conflicts between Claude's flags and the server's flags.
</Note>

### Managing your servers

Once configured, you can manage your MCP servers with these commands:

```bash theme={null}
# List all configured servers
claude mcp list

# Get details for a specific server
claude mcp get github

# Remove a server
claude mcp remove github

# (within Claude Code) Check server status
/mcp

Dynamic tool updates

Claude Code supports MCP list_changed notifications, allowing MCP servers to dynamically update their available tools, prompts, and resources without requiring you to disconnect and reconnect. When an MCP server sends a list_changed notification, Claude Code automatically refreshes the available capabilities from that server.

Automatic reconnection

If an HTTP or SSE server disconnects mid-session, Claude Code automatically reconnects with exponential backoff: up to five attempts, starting at a one-second delay and doubling each time. The server appears as pending in /mcp while reconnection is in progress. After five failed attempts the server is marked as failed and you can retry manually from /mcp. Stdio servers are local processes and are not reconnected automatically.

Push messages with channels

An MCP server can also push messages directly into your session so Claude can react to external events like CI results, monitoring alerts, or chat messages. To enable this, your server declares the claude/channel capability and you opt it in with the --channels flag at startup. See Channels to use an officially supported channel, or Channels reference to build your own.

Tips:

Windows Users: On native Windows (not WSL), local MCP servers that use npx require the cmd /c wrapper to ensure proper execution.

bash theme={null} # This creates command="cmd" which Windows can execute claude mcp add --transport stdio my-server -- cmd /c npx -y @some/package

Without the cmd /c wrapper, you'll encounter "Connection closed" errors because Windows cannot directly execute npx. (See the note above for an explanation of the -- parameter.)

Plugin-provided MCP servers

Plugins can bundle MCP servers, automatically providing tools and integrations when the plugin is enabled. Plugin MCP servers work identically to user-configured servers.

How plugin MCP servers work:

Example plugin MCP configuration:

In .mcp.json at plugin root:

```json theme={null} { "mcpServers": { "database-tools": { "command": "${CLAUDE_PLUGIN_ROOT}/servers/db-server", "args": ["--config", "${CLAUDE_PLUGIN_ROOT}/config.json"], "env": { "DB_URL": "${DB_URL}" } } } }


Or inline in `plugin.json`:

```json theme={null}
{
  "name": "my-plugin",
  "mcpServers": {
    "plugin-api": {
      "command": "${CLAUDE_PLUGIN_ROOT}/servers/api-server",
      "args": ["--port", "8080"]
    }
  }
}

Plugin MCP features:

Viewing plugin MCP servers:

```bash theme={null}

Within Claude Code, see all MCP servers including plugin ones

/mcp


Plugin servers appear in the list with indicators showing they come from plugins.

**Benefits of plugin MCP servers**:

* **Bundled distribution**: Tools and servers packaged together
* **Automatic setup**: No manual MCP configuration needed
* **Team consistency**: Everyone gets the same tools when plugin is installed

See the [plugin components reference](https://code.claude.com/en/plugins-reference#mcp-servers) for details on bundling MCP servers with plugins.

## MCP installation scopes

MCP servers can be configured at three scopes. The scope you choose controls which projects the server loads in and whether the configuration is shared with your team.

| Scope                     | Loads in             | Shared with team         | Stored in                   |
| ------------------------- | -------------------- | ------------------------ | --------------------------- |
| [Local](#local-scope)     | Current project only | No                       | `~/.claude.json`            |
| [Project](#project-scope) | Current project only | Yes, via version control | `.mcp.json` in project root |
| [User](#user-scope)       | All your projects    | No                       | `~/.claude.json`            |

### Local scope

Local scope is the default. A local-scoped server loads only in the project where you added it and stays private to you. Claude Code stores it in `~/.claude.json` under that project's path, so the same server won't appear in your other projects. Use local scope for personal development servers, experimental configurations, or servers with credentials you don't want in version control.

<Note>
  The term "local scope" for MCP servers differs from general local settings. MCP local-scoped servers are stored in `~/.claude.json` (your home directory), while general local settings use `.claude/settings.local.json` (in the project directory). See [Settings](https://code.claude.com/en/settings#settings-files) for details on settings file locations.
</Note>

```bash theme={null}
# Add a local-scoped server (default)
claude mcp add --transport http stripe https://mcp.stripe.com

# Explicitly specify local scope
claude mcp add --transport http stripe --scope local https://mcp.stripe.com

The command writes the server into the entry for your current project inside ~/.claude.json. The example below shows the result when you run it from /path/to/your/project:

```json theme={null} { "projects": { "/path/to/your/project": { "mcpServers": { "stripe": { "type": "http", "url": "https://mcp.stripe.com" } } } } }


### Project scope

Project-scoped servers enable team collaboration by storing configurations in a `.mcp.json` file at your project's root directory. This file is designed to be checked into version control, ensuring all team members have access to the same MCP tools and services. When you add a project-scoped server, Claude Code automatically creates or updates this file with the appropriate configuration structure.

```bash theme={null}
# Add a project-scoped server
claude mcp add --transport http paypal --scope project https://mcp.paypal.com/mcp

The resulting .mcp.json file follows a standardized format:

```json theme={null} { "mcpServers": { "shared-server": { "command": "/path/to/server", "args": [], "env": {} } } }


For security reasons, Claude Code prompts for approval before using project-scoped servers from `.mcp.json` files. If you need to reset these approval choices, use the `claude mcp reset-project-choices` command.

### User scope

User-scoped servers are stored in `~/.claude.json` and provide cross-project accessibility, making them available across all projects on your machine while remaining private to your user account. This scope works well for personal utility servers, development tools, or services you frequently use across different projects.

```bash theme={null}
# Add a user server
claude mcp add --transport http hubspot --scope user https://mcp.hubspot.com/anthropic

Scope hierarchy and precedence

When the same server is defined in more than one place, Claude Code connects to it once, using the definition from the highest-precedence source:

  1. Local scope
  2. Project scope
  3. User scope
  4. Plugin-provided servers
  5. claude.ai connectors

The three scopes match duplicates by name. Plugins and connectors match by endpoint, so one that points at the same URL or command as a server above is treated as a duplicate.

Environment variable expansion in .mcp.json

Claude Code supports environment variable expansion in .mcp.json files, allowing teams to share configurations while maintaining flexibility for machine-specific paths and sensitive values like API keys.

Supported syntax:

Expansion locations: Environment variables can be expanded in:

Example with variable expansion:

```json theme={null} { "mcpServers": { "api-server": { "type": "http", "url": "${API_BASE_URL:-https://api.example.com}/mcp", "headers": { "Authorization": "Bearer ${API_KEY}" } } } }


If a required environment variable is not set and has no default value, Claude Code will fail to parse the config.

## Practical examples

{/* ### Example: Automate browser testing with Playwright

```bash
claude mcp add --transport stdio playwright -- npx -y @playwright/mcp@latest

Then write and run browser tests:

Test if the login flow works with test@example.com
Take a screenshot of the checkout page on mobile
Verify that the search feature returns results
``` */}

### Example: Monitor errors with Sentry

```bash theme={null}
claude mcp add --transport http sentry https://mcp.sentry.dev/mcp

Authenticate with your Sentry account:

```text theme={null} /mcp


Then debug production issues:

```text theme={null}
What are the most common errors in the last 24 hours?

```text theme={null} Show me the stack trace for error ID abc123


```text theme={null}
Which deployment introduced these new errors?

Example: Connect to GitHub for code reviews

```bash theme={null} claude mcp add --transport http github https://api.githubcopilot.com/mcp/


Authenticate if needed by selecting "Authenticate" for GitHub:

```text theme={null}
/mcp

Then work with GitHub:

```text theme={null} Review PR #456 and suggest improvements


```text theme={null}
Create a new issue for the bug we just found

```text theme={null} Show me all open PRs assigned to me


### Example: Query your PostgreSQL database

```bash theme={null}
claude mcp add --transport stdio db -- npx -y @bytebase/dbhub \
  --dsn "postgresql://readonly:pass@prod.db.com:5432/analytics"

Then query your database naturally:

```text theme={null} What's our total revenue this month?


```text theme={null}
Show me the schema for the orders table

```text theme={null} Find customers who haven't made a purchase in 90 days


## Authenticate with remote MCP servers

Many cloud-based MCP servers require authentication. Claude Code supports OAuth 2.0 for secure connections.

<Steps>
  <Step title="Add the server that requires authentication">
    For example:

    ```bash theme={null}
    claude mcp add --transport http sentry https://mcp.sentry.dev/mcp
    ```
  </Step>

  <Step title="Use the /mcp command within Claude Code">
    In Claude code, use the command:

    ```text theme={null}
    /mcp
    ```

    Then follow the steps in your browser to login.
  </Step>
</Steps>

<Tip>
  Tips:

  * Authentication tokens are stored securely and refreshed automatically
  * Use "Clear authentication" in the `/mcp` menu to revoke access
  * If your browser doesn't open automatically, copy the provided URL and open it manually
  * If the browser redirect fails with a connection error after authenticating, paste the full callback URL from your browser's address bar into the URL prompt that appears in Claude Code
  * OAuth authentication works with HTTP servers
</Tip>

### Use a fixed OAuth callback port

Some MCP servers require a specific redirect URI registered in advance. By default, Claude Code picks a random available port for the OAuth callback. Use `--callback-port` to fix the port so it matches a pre-registered redirect URI of the form `http://localhost:PORT/callback`.

You can use `--callback-port` on its own (with dynamic client registration) or together with `--client-id` (with pre-configured credentials).

```bash theme={null}
# Fixed callback port with dynamic client registration
claude mcp add --transport http \
  --callback-port 8080 \
  my-server https://mcp.example.com/mcp

Use pre-configured OAuth credentials

Some MCP servers don't support automatic OAuth setup via Dynamic Client Registration. If you see an error like "Incompatible auth server: does not support dynamic client registration," the server requires pre-configured credentials. Claude Code also supports servers that use a Client ID Metadata Document (CIMD) instead of Dynamic Client Registration, and discovers these automatically. If automatic discovery fails, register an OAuth app through the server's developer portal first, then provide the credentials when adding the server.

Create an app through the server's developer portal and note your client ID and client secret.

Many servers also require a redirect URI. If so, choose a port and register a redirect URI in the format `http://localhost:PORT/callback`. Use that same port with `--callback-port` in the next step.

Choose one of the following methods. The port used for --callback-port can be any available port. It just needs to match the redirect URI you registered in the previous step.

<Tabs>
  <Tab title="claude mcp add">
    Use `--client-id` to pass your app's client ID. The `--client-secret` flag prompts for the secret with masked input:

    ```bash theme={null}
    claude mcp add --transport http \
      --client-id your-client-id --client-secret --callback-port 8080 \
      my-server https://mcp.example.com/mcp
    ```
  </Tab>

  <Tab title="claude mcp add-json">
    Include the `oauth` object in the JSON config and pass `--client-secret` as a separate flag:

    ```bash theme={null}
    claude mcp add-json my-server \
      '{"type":"http","url":"https://mcp.example.com/mcp","oauth":{"clientId":"your-client-id","callbackPort":8080}}' \
      --client-secret
    ```
  </Tab>

  <Tab title="claude mcp add-json (callback port only)">
    Use `--callback-port` without a client ID to fix the port while using dynamic client registration:

    ```bash theme={null}
    claude mcp add-json my-server \
      '{"type":"http","url":"https://mcp.example.com/mcp","oauth":{"callbackPort":8080}}'
    ```
  </Tab>

  <Tab title="CI / env var">
    Set the secret via environment variable to skip the interactive prompt:

    ```bash theme={null}
    MCP_CLIENT_SECRET=your-secret claude mcp add --transport http \
      --client-id your-client-id --client-secret --callback-port 8080 \
      my-server https://mcp.example.com/mcp
    ```
  </Tab>
</Tabs>

Run /mcp in Claude Code and follow the browser login flow.

Tips:

Override OAuth metadata discovery

Point Claude Code at a specific OAuth authorization server metadata URL to bypass the default discovery chain. Set authServerMetadataUrl when the MCP server's standard endpoints error, or when you want to route discovery through an internal proxy. By default, Claude Code first checks RFC 9728 Protected Resource Metadata at /.well-known/oauth-protected-resource, then falls back to RFC 8414 authorization server metadata at /.well-known/oauth-authorization-server.

Set authServerMetadataUrl in the oauth object of your server's config in .mcp.json:

```json theme={null} { "mcpServers": { "my-server": { "type": "http", "url": "https://mcp.example.com/mcp", "oauth": { "authServerMetadataUrl": "https://auth.example.com/.well-known/openid-configuration" } } } }


The URL must use `https://`. `authServerMetadataUrl` requires Claude Code v2.1.64 or later. The metadata URL's `scopes_supported` overrides the scopes the upstream server advertises.

### Restrict OAuth scopes

Set `oauth.scopes` to pin the scopes Claude Code requests during the authorization flow. This is the supported way to restrict an MCP server to a security-team-approved subset when the upstream authorization server advertises more scopes than you want to grant. The value is a single space-separated string, matching the `scope` parameter format in RFC 6749 §3.3.

```json theme={null}
{
  "mcpServers": {
    "slack": {
      "type": "http",
      "url": "https://mcp.slack.com/mcp",
      "oauth": {
        "scopes": "channels:read chat:write search:read"
      }
    }
  }
}

oauth.scopes takes precedence over both authServerMetadataUrl and the scopes the server discovers at /.well-known. Leave it unset to let the MCP server determine the requested scope set.

If the authorization server advertises offline_access in scopes_supported, Claude Code appends it to the pinned scopes so the access token can be refreshed without a new browser sign-in.

If the server later returns a 403 insufficient_scope for a tool call, Claude Code re-authenticates with the same pinned scopes. Widen oauth.scopes when a tool you need requires a scope outside the pin.

Use dynamic headers for custom authentication

If your MCP server uses an authentication scheme other than OAuth (such as Kerberos, short-lived tokens, or an internal SSO), use headersHelper to generate request headers at connection time. Claude Code runs the command and merges its output into the connection headers.

```json theme={null} { "mcpServers": { "internal-api": { "type": "http", "url": "https://mcp.internal.example.com", "headersHelper": "/opt/bin/get-mcp-auth-headers.sh" } } }


The command can also be inline:

```json theme={null}
{
  "mcpServers": {
    "internal-api": {
      "type": "http",
      "url": "https://mcp.internal.example.com",
      "headersHelper": "echo '{\"Authorization\": \"Bearer '\"$(get-token)\"'\"}'"
    }
  }
}

Requirements:

The helper runs fresh on each connection (at session start and on reconnect). There is no caching, so your script is responsible for any token reuse.

Claude Code sets these environment variables when executing the helper:

Variable Value
CLAUDE_CODE_MCP_SERVER_NAME the name of the MCP server
CLAUDE_CODE_MCP_SERVER_URL the URL of the MCP server

Use these to write a single helper script that serves multiple MCP servers.

headersHelper executes arbitrary shell commands. When defined at project or local scope, it only runs after you accept the workspace trust dialog.

Add MCP servers from JSON configuration

If you have a JSON configuration for an MCP server, you can add it directly:

```bash theme={null} # Basic syntax claude mcp add-json ''

# Example: Adding an HTTP server with JSON configuration
claude mcp add-json weather-api '{"type":"http","url":"https://api.weather.com/mcp","headers":{"Authorization":"Bearer token"}}'

# Example: Adding a stdio server with JSON configuration
claude mcp add-json local-weather '{"type":"stdio","command":"/path/to/weather-cli","args":["--api-key","abc123"],"env":{"CACHE_DIR":"/tmp"}}'

# Example: Adding an HTTP server with pre-configured OAuth credentials
claude mcp add-json my-server '{"type":"http","url":"https://mcp.example.com/mcp","oauth":{"clientId":"your-client-id","callbackPort":8080}}' --client-secret
```

bash theme={null} claude mcp get weather-api

Tips:

Import MCP servers from Claude Desktop

If you've already configured MCP servers in Claude Desktop, you can import them:

bash theme={null} # Basic syntax claude mcp add-from-claude-desktop

After running the command, you'll see an interactive dialog that allows you to select which servers you want to import.

bash theme={null} claude mcp list

Tips:

Use MCP servers from Claude.ai

If you've logged into Claude Code with a Claude.ai account, MCP servers you've added in Claude.ai are automatically available in Claude Code:

Add servers at claude.ai/settings/connectors. On Team and Enterprise plans, only admins can add servers.

Complete any required authentication steps in Claude.ai.

In Claude Code, use the command:

```text theme={null}
/mcp
```

Claude.ai servers appear in the list with indicators showing they come from Claude.ai.

To disable claude.ai MCP servers in Claude Code, set the ENABLE_CLAUDEAI_MCP_SERVERS environment variable to false:

```bash theme={null} ENABLE_CLAUDEAI_MCP_SERVERS=false claude


## Use Claude Code as an MCP server

You can use Claude Code itself as an MCP server that other applications can connect to:

```bash theme={null}
# Start Claude as a stdio MCP server
claude mcp serve

You can use this in Claude Desktop by adding this configuration to claude_desktop_config.json:

```json theme={null} { "mcpServers": { "claude-code": { "type": "stdio", "command": "claude", "args": ["mcp", "serve"], "env": {} } } }


<Warning>
  **Configuring the executable path**: The `command` field must reference the Claude Code executable. If the `claude` command is not in your system's PATH, you'll need to specify the full path to the executable.

  To find the full path:

  ```bash theme={null}
  which claude
  ```

  Then use the full path in your configuration:

  ```json theme={null}
  {
    "mcpServers": {
      "claude-code": {
        "type": "stdio",
        "command": "/full/path/to/claude",
        "args": ["mcp", "serve"],
        "env": {}
      }
    }
  }
  ```

  Without the correct executable path, you'll encounter errors like `spawn claude ENOENT`.
</Warning>

<Tip>
  Tips:

  * The server provides access to Claude's tools like View, Edit, LS, etc.
  * In Claude Desktop, try asking Claude to read files in a directory, make edits, and more.
  * Note that this MCP server is only exposing Claude Code's tools to your MCP client, so your own client is responsible for implementing user confirmation for individual tool calls.
</Tip>

## MCP output limits and warnings

When MCP tools produce large outputs, Claude Code helps manage the token usage to prevent overwhelming your conversation context:

* **Output warning threshold**: Claude Code displays a warning when any MCP tool output exceeds 10,000 tokens
* **Configurable limit**: you can adjust the maximum allowed MCP output tokens using the `MAX_MCP_OUTPUT_TOKENS` environment variable
* **Default limit**: the default maximum is 25,000 tokens
* **Scope**: the environment variable applies to tools that don't declare their own limit. Tools that set [`anthropic/maxResultSizeChars`](#raise-the-limit-for-a-specific-tool) use that value instead for text content, regardless of what `MAX_MCP_OUTPUT_TOKENS` is set to. Tools that return image data are still subject to `MAX_MCP_OUTPUT_TOKENS`

To increase the limit for tools that produce large outputs:

```bash theme={null}
export MAX_MCP_OUTPUT_TOKENS=50000
claude

This is particularly useful when working with MCP servers that:

Raise the limit for a specific tool

If you're building an MCP server, you can allow individual tools to return results larger than the default persist-to-disk threshold by setting _meta["anthropic/maxResultSizeChars"] in the tool's tools/list response entry. Claude Code raises that tool's threshold to the annotated value, up to a hard ceiling of 500,000 characters.

This is useful for tools that return inherently large but necessary outputs, such as database schemas or full file trees. Without the annotation, results that exceed the default threshold are persisted to disk and replaced with a file reference in the conversation.

```json theme={null} { "name": "get_schema", "description": "Returns the full database schema", "_meta": { "anthropic/maxResultSizeChars": 200000 } }


The annotation applies independently of `MAX_MCP_OUTPUT_TOKENS` for text content, so users don't need to raise the environment variable for tools that declare it. Tools that return image data are still subject to the token limit.

<Warning>
  If you frequently encounter output warnings with specific MCP servers you don't control, consider increasing the `MAX_MCP_OUTPUT_TOKENS` limit. You can also ask the server author to add the `anthropic/maxResultSizeChars` annotation or to paginate their responses. The annotation has no effect on tools that return image content; for those, raising `MAX_MCP_OUTPUT_TOKENS` is the only option.
</Warning>

## Respond to MCP elicitation requests

MCP servers can request structured input from you mid-task using elicitation. When a server needs information it can't get on its own, Claude Code displays an interactive dialog and passes your response back to the server. No configuration is required on your side: elicitation dialogs appear automatically when a server requests them.

Servers can request input in two ways:

* **Form mode**: Claude Code shows a dialog with form fields defined by the server (for example, a username and password prompt). Fill in the fields and submit.
* **URL mode**: Claude Code opens a browser URL for authentication or approval. Complete the flow in the browser, then confirm in the CLI.

To auto-respond to elicitation requests without showing a dialog, use the [`Elicitation` hook](https://code.claude.com/en/hooks#elicitation).

If you're building an MCP server that uses elicitation, see the [MCP elicitation specification](https://modelcontextprotocol.io/docs/learn/client-concepts#elicitation) for protocol details and schema examples.

## Use MCP resources

MCP servers can expose resources that you can reference using @ mentions, similar to how you reference files.

### Reference MCP resources

<Steps>
  <Step title="List available resources">
    Type `@` in your prompt to see available resources from all connected MCP servers. Resources appear alongside files in the autocomplete menu.
  </Step>

  <Step title="Reference a specific resource">
    Use the format `@server:protocol://resource/path` to reference a resource:

    ```text theme={null}
    Can you analyze @github:issue://123 and suggest a fix?
    ```

    ```text theme={null}
    Please review the API documentation at @docs:file://api/authentication
    ```
  </Step>

  <Step title="Multiple resource references">
    You can reference multiple resources in a single prompt:

    ```text theme={null}
    Compare @postgres:schema://users with @docs:file://database/user-model
    ```
  </Step>
</Steps>

<Tip>
  Tips:

  * Resources are automatically fetched and included as attachments when referenced
  * Resource paths are fuzzy-searchable in the @ mention autocomplete
  * Claude Code automatically provides tools to list and read MCP resources when servers support them
  * Resources can contain any type of content that the MCP server provides (text, JSON, structured data, etc.)
</Tip>

## Scale with MCP Tool Search

Tool search keeps MCP context usage low by deferring tool definitions until Claude needs them. Only tool names load at session start, so adding more MCP servers has minimal impact on your context window.

### How it works

Tool search is enabled by default. MCP tools are deferred rather than loaded into context upfront, and Claude uses a search tool to discover relevant ones when a task needs them. Only the tools Claude actually uses enter context. From your perspective, MCP tools work exactly as before.

If you prefer threshold-based loading, set `ENABLE_TOOL_SEARCH=auto` to load schemas upfront when they fit within 10% of the context window and defer only the overflow. See [Configure tool search](#configure-tool-search) for all options.

### For MCP server authors

If you're building an MCP server, the server instructions field becomes more useful with Tool Search enabled. Server instructions help Claude understand when to search for your tools, similar to how [skills](https://code.claude.com/en/skills) work.

Add clear, descriptive server instructions that explain:

* What category of tasks your tools handle
* When Claude should search for your tools
* Key capabilities your server provides

Claude Code truncates tool descriptions and server instructions at 2KB each. Keep them concise to avoid truncation, and put critical details near the start.

### Configure tool search

Tool search is enabled by default: MCP tools are deferred and discovered on demand. When `ANTHROPIC_BASE_URL` points to a non-first-party host, tool search is disabled by default because most proxies do not forward `tool_reference` blocks. Set `ENABLE_TOOL_SEARCH` explicitly if your proxy does. This feature requires models that support `tool_reference` blocks: Sonnet 4 and later, or Opus 4 and later. Haiku models do not support tool search.

Control tool search behavior with the `ENABLE_TOOL_SEARCH` environment variable:

| Value      | Behavior                                                                                                                       |
| :--------- | :----------------------------------------------------------------------------------------------------------------------------- |
| (unset)    | All MCP tools deferred and loaded on demand. Falls back to loading upfront when `ANTHROPIC_BASE_URL` is a non-first-party host |
| `true`     | All MCP tools deferred, including for non-first-party `ANTHROPIC_BASE_URL`                                                     |
| `auto`     | Threshold mode: tools load upfront if they fit within 10% of the context window, deferred otherwise                            |
| `auto:<N>` | Threshold mode with a custom percentage, where `<N>` is 0-100 (e.g., `auto:5` for 5%)                                          |
| `false`    | All MCP tools loaded upfront, no deferral                                                                                      |

```bash theme={null}
# Use a custom 5% threshold
ENABLE_TOOL_SEARCH=auto:5 claude

# Disable tool search entirely
ENABLE_TOOL_SEARCH=false claude

Or set the value in your settings.json env field.

You can also disable the ToolSearch tool specifically:

```json theme={null} { "permissions": { "deny": ["ToolSearch"] } }


## Use MCP prompts as commands

MCP servers can expose prompts that become available as commands in Claude Code.

### Execute MCP prompts

<Steps>
  <Step title="Discover available prompts">
    Type `/` to see all available commands, including those from MCP servers. MCP prompts appear with the format `/mcp__servername__promptname`.
  </Step>

  <Step title="Execute a prompt without arguments">
    ```text theme={null}
    /mcp__github__list_prs
    ```
  </Step>

  <Step title="Execute a prompt with arguments">
    Many prompts accept arguments. Pass them space-separated after the command:

    ```text theme={null}
    /mcp__github__pr_review 456
    ```

    ```text theme={null}
    /mcp__jira__create_issue "Bug in login flow" high
    ```
  </Step>
</Steps>

<Tip>
  Tips:

  * MCP prompts are dynamically discovered from connected servers
  * Arguments are parsed based on the prompt's defined parameters
  * Prompt results are injected directly into the conversation
  * Server and prompt names are normalized (spaces become underscores)
</Tip>

## Managed MCP configuration

For organizations that need centralized control over MCP servers, Claude Code supports two configuration options:

1. **Exclusive control with `managed-mcp.json`**: Deploy a fixed set of MCP servers that users cannot modify or extend
2. **Policy-based control with allowlists/denylists**: Allow users to add their own servers, but restrict which ones are permitted

These options allow IT administrators to:

* **Control which MCP servers employees can access**: Deploy a standardized set of approved MCP servers across the organization
* **Prevent unauthorized MCP servers**: Restrict users from adding unapproved MCP servers
* **Disable MCP entirely**: Remove MCP functionality completely if needed

### Option 1: Exclusive control with managed-mcp.json

When you deploy a `managed-mcp.json` file, it takes **exclusive control** over all MCP servers. Users cannot add, modify, or use any MCP servers other than those defined in this file. This is the simplest approach for organizations that want complete control.

System administrators deploy the configuration file to a system-wide directory:

* macOS: `/Library/Application Support/ClaudeCode/managed-mcp.json`
* Linux and WSL: `/etc/claude-code/managed-mcp.json`
* Windows: `C:\Program Files\ClaudeCode\managed-mcp.json`

<Note>
  These are system-wide paths (not user home directories like `~/Library/...`) that require administrator privileges. They are designed to be deployed by IT administrators.
</Note>

The `managed-mcp.json` file uses the same format as a standard `.mcp.json` file:

```json theme={null}
{
  "mcpServers": {
    "github": {
      "type": "http",
      "url": "https://api.githubcopilot.com/mcp/"
    },
    "sentry": {
      "type": "http",
      "url": "https://mcp.sentry.dev/mcp"
    },
    "company-internal": {
      "type": "stdio",
      "command": "/usr/local/bin/company-mcp-server",
      "args": ["--config", "/etc/company/mcp-config.json"],
      "env": {
        "COMPANY_API_URL": "https://internal.company.com"
      }
    }
  }
}

Option 2: Policy-based control with allowlists and denylists

Instead of taking exclusive control, administrators can allow users to configure their own MCP servers while enforcing restrictions on which servers are permitted. This approach uses allowedMcpServers and deniedMcpServers in the managed settings file.

Choosing between options: Use Option 1 (managed-mcp.json) when you want to deploy a fixed set of servers with no user customization. Use Option 2 (allowlists/denylists) when you want to allow users to add their own servers within policy constraints.

Restriction options

Each entry in the allowlist or denylist can restrict servers in three ways:

  1. By server name (serverName): Matches the configured name of the server
  2. By command (serverCommand): Matches the exact command and arguments used to start stdio servers
  3. By URL pattern (serverUrl): Matches remote server URLs with wildcard support

Important: Each entry must have exactly one of serverName, serverCommand, or serverUrl.

Example configuration

```json theme={null} { "allowedMcpServers": [ // Allow by server name { "serverName": "github" }, { "serverName": "sentry" },

// Allow by exact command (for stdio servers)
{ "serverCommand": ["npx", "-y", "@modelcontextprotocol/server-filesystem"] },
{ "serverCommand": ["python", "/usr/local/bin/approved-server.py"] },

// Allow by URL pattern (for remote servers)
{ "serverUrl": "https://mcp.company.com/*" },
{ "serverUrl": "https://*.internal.corp/*" }

], "deniedMcpServers": [ // Block by server name { "serverName": "dangerous-server" },

// Block by exact command (for stdio servers)
{ "serverCommand": ["npx", "-y", "unapproved-package"] },

// Block by URL pattern (for remote servers)
{ "serverUrl": "https://*.untrusted.com/*" }

] } ```

How command-based restrictions work

Exact matching:

Stdio server behavior:

Non-stdio server behavior:

How URL-based restrictions work

URL patterns support wildcards using * to match any sequence of characters. This is useful for allowing entire domains or subdomains.

Wildcard examples:

Remote server behavior:

json theme={null} { "allowedMcpServers": [ { "serverUrl": "https://mcp.company.com/*" }, { "serverUrl": "https://*.internal.corp/*" } ] }

Result:

json theme={null} { "allowedMcpServers": [ { "serverCommand": ["npx", "-y", "approved-package"] } ] }

Result:

json theme={null} { "allowedMcpServers": [ { "serverName": "github" }, { "serverCommand": ["npx", "-y", "approved-package"] } ] }

Result:

json theme={null} { "allowedMcpServers": [ { "serverName": "github" }, { "serverName": "internal-tool" } ] }

Result:

Allowlist behavior (allowedMcpServers)

Denylist behavior (deniedMcpServers)

Important notes

When using managed-mcp.json: Users cannot add MCP servers through claude mcp add or configuration files. The allowedMcpServers and deniedMcpServers settings still apply to filter which managed servers are actually loaded.