This page covers MCP configuration for the Agent SDK. To add MCP servers to the Claude Code CLI so they load in every project, see MCP installation scopes.
Quickstart
This example connects to the Claude Code documentation MCP server using HTTP transport and usesallowedTools with a wildcard to permit all tools from the server.
Add an MCP server
You can configure MCP servers in code when callingquery(), or in a .mcp.json file loaded via settingSources.
In code
Pass MCP servers directly in themcpServers option:
From a config file
Create a.mcp.json file at your project root. The file is picked up when the project setting source is enabled, which it is for default query() options. If you set settingSources explicitly, include "project" for this file to load:
Connection timing
Claude Code registers the servers you pass inoptions.mcpServers at startup and emits the init message once the first-turn wait, if any, resolves. Servers loaded from settings files such as .mcp.json don’t get the full wait and commonly show pending at init. When each options.mcpServers server connects, and whether it delays the first turn, depends on its type:
To block startup itself at a separate, earlier phase than the first-turn wait, before the init message is sent:
- Set
MCP_CONNECTION_NONBLOCKINGto0to block on the whole connection batch. Claude Code caps that wait at 5 seconds by default. Adjust the cap with theMCP_CONNECT_TIMEOUT_MSenvironment variable, in milliseconds. Servers still pending at that deadline keep connecting in the background. - Set
alwaysLoad: trueon a server’s config to make its tools available at their full schemas on the first turn, exempt from tool search deferral. Claude Code waits at startup for that server’s tools, capped at the same deadline, while other servers keep connecting in the background; a remote server with a cached tool list supplies them without connecting, per the table above.
system message with subtype init reports each server’s status at the moment it’s emitted; see Error handling for reading those statuses.
Allow MCP tools
MCP tools require explicit permission before Claude can use them. Without permission, Claude will see that tools are available but won’t be able to call them.Tool naming convention
MCP tools follow the naming patternmcp__<server-name>__<tool-name>. For example, a GitHub server named "github" with a list_issues tool becomes mcp__github__list_issues.
Auto-approve with allowedTools
UseallowedTools to auto-approve specific MCP tools so Claude can use them without a permission prompt:
*) let you allow all tools from a server without listing each one individually.
Prefer
allowedTools over permission modes for MCP access. permissionMode: "acceptEdits" does not auto-approve MCP tools (only file edits and filesystem Bash commands). permissionMode: "bypassPermissions" does auto-approve MCP tools but also disables most other safety prompts, which is broader than necessary; see How permissions are evaluated for the prompts that remain. A wildcard in allowedTools grants exactly the MCP server you want and nothing more. See Permission modes for a full comparison.Discover available tools
To see what tools an MCP server provides, check the server’s documentation or inspect thetools array in the system init message. MCP tool names start with mcp__.
Claude Code emits the init message after the first-turn connection wait for servers passed in options.mcpServers, so the tools array lists the mcp__ tools of each server that has connected by then, plus those of servers with a cached tool list, which connect on first use. Tools of any other server that hasn’t connected are absent; see Error handling for reading each server’s status.
This filter prints the MCP tool names:
Transport types
MCP servers communicate with your agent using different transport protocols. Check the server’s documentation to see which transport it supports:- If the docs give you a command to run (like
npx @modelcontextprotocol/server-filesystem), use stdio - If the docs give you a URL, use HTTP or SSE
- If you’re building your own tools in code, use an SDK MCP server
stdio servers
Local processes that communicate via stdin/stdout. Use this for MCP servers you run on the same machine. For the.mcp.json form, use the same fields shown at From a config file. In code, pass the command and its arguments:
HTTP/SSE servers
Use HTTP or SSE for cloud-hosted MCP servers and remote APIs:- In code
- .mcp.json
"type": "http" instead. In .mcp.json and other JSON config files, "streamable-http" is accepted as an alias for "http". The programmatic mcpServers option accepts only "http".
SDK MCP servers
Define custom tools directly in your application code instead of running a separate server process. See the custom tools guide for implementation details. An SDK MCP server registered by aninitialize control request begins connecting as soon as Claude Code processes the request.
MCP tool search
When you have many MCP tools configured, tool definitions can consume a significant portion of your context window. Tool search solves this by withholding tool definitions from context and loading only the ones Claude needs for each turn. Tool search is enabled by default. See Tool search for configuration options, best practices, and using tool search with custom SDK tools.Authentication
Most MCP servers require authentication to access external services. Pass credentials through environment variables in the server configuration.Pass credentials via environment variables
Use theenv field to pass API keys, tokens, and other credentials to the MCP server:
- In code
- .mcp.json
HTTP headers for remote servers
For HTTP and SSE servers, pass authentication headers directly in the server configuration:- In code
- .mcp.json
OAuth2 authentication
The MCP specification supports OAuth 2.1 for authorization. The SDK doesn’t open a browser or run an interactive OAuth flow. When a configured server returns an authorization challenge and no stored token is available, the agent run continues without that server’s tools, and the server reports statusneeds-auth. The mcp_servers array of the system init message may still show pending for that server when it’s emitted. To confirm whether a server needs credentials, poll mcpServerStatus() in the TypeScript SDK or get_mcp_status() in Python.
To supply credentials, complete the OAuth flow in your own application and pass the resulting access token in the server’s headers:
Examples
List issues from a repository
This example connects to the remote GitHub MCP server to list recent issues. The example includes debug logging to verify the MCP connection and tool calls. Before running, create a GitHub personal access token with read access to the repositories you want to query and set it as an environment variable:Query a database
This example uses DBHub to query a Postgres database. The agent automatically discovers the database schema, writes the SQL query, and returns the results. DBHub’sexecute_sql tool runs whatever SQL the agent emits, including writes, unless you restrict it. Setting readonly = true in the DBHub configuration file makes DBHub reject INSERT, UPDATE, DELETE, and DDL statements, so the example cannot modify your data even if the agent emits a write. DBHub resolves ${DATABASE_URL} from the process environment when it loads the config, so the connection string stays out of the file. Create this dbhub.toml next to your script:
dbhub.toml
DATABASE_URL environment variable to your connection string. Replace the placeholder values with your own database details:
Error handling
MCP servers can fail to connect for various reasons: the server process might not be installed, credentials might be invalid, or a remote server might be unreachable. Claude Code emits asystem message with subtype init at the start of each query. This message includes the connection status for each MCP server. The status field can be "pending", "connected", "failed", "needs-auth", or "disabled". Claude Code emits the init message after the first-turn connection wait for servers passed in options.mcpServers, so such a server that connected within the wait shows "connected". A "pending" status means the server hasn’t connected yet, which is common for settings-file servers that don’t get the full wait, or that its tool list was served from the cache with a connection made on first use; the reported status for a deadline-expired server can be "pending" or "failed" depending on timing. Don’t treat "pending" as a failure. Check for "failed" or "needs-auth" to detect servers that won’t be usable:
Troubleshooting
Server shows “failed” status
Check theinit message to see which servers failed to connect:
"pending" status doesn’t mean the server failed; see Error handling for the two cases it covers at init. To get updated statuses later in the session, call the query’s mcpServerStatus() method in the TypeScript SDK, or ClaudeSDKClient.get_mcp_status() in Python.
Common causes:
- Missing environment variables: Ensure required tokens and credentials are set. For stdio servers, check the
envfield matches what the server expects. - Server not installed: For
npxcommands, verify the package exists and Node.js is in your PATH. - Invalid connection string: For database servers, verify the connection string format and that the database is accessible.
- Network issues: For remote HTTP/SSE servers, check the URL is reachable and any firewalls allow the connection.
Tools not being called
If Claude sees tools but doesn’t use them, check that you’ve granted permission withallowedTools:
Connection timeouts
MCP server connections time out after 30 seconds by default. Claude Code applies that limit to the connection attempt only; to change how long a running tool call may take, setMCP_TOOL_TIMEOUT. If your server takes longer to start, the connection fails. Raise the connection limit with the MCP_TIMEOUT environment variable, in milliseconds. For servers that need more startup time, also consider:
- Using a lighter-weight server if available
- Pre-warming the server before starting your agent
- Checking server logs for slow initialization causes
Tool output exceeds maximum allowed tokens
The SDK applies the same MCP output limit as Claude Code. When a tool result is larger than 25,000 tokens, the full output is saved to a file and the tool result is replaced with an error message that names the file path, so the agent can read the output back in portions. Raise the limit with theMAX_MCP_OUTPUT_TOKENS environment variable. See MCP output limits and warnings for the full behavior, including how a server can declare a higher per-tool limit.
Related resources
- Custom tools guide: Build your own MCP server that runs in-process with your SDK application
- Permissions: Control which MCP tools your agent can use with
allowedToolsanddisallowedTools - MCP output limits and warnings: How the SDK handles tool results that exceed
MAX_MCP_OUTPUT_TOKENS, including the persist-to-disk fallback and theanthropic/maxResultSizeCharsper-tool annotation - TypeScript SDK reference: Full API reference including MCP configuration options
- Python SDK reference: Full API reference including MCP configuration options
- MCP server directory: Browse available MCP servers for databases, APIs, and more