SpyBara
Go Premium

agent-sdk/mcp.md 2026-07-17 22:57 UTC to 2026-07-18 16:02 UTC

20 added, 8 removed.

2026
Sat 18 16:02 Fri 17 22:57 Thu 16 22:59 Wed 15 22:00 Tue 14 23:01 Mon 13 23:57 Sat 11 19:03 Fri 10 17:00 Thu 9 23:58 Wed 8 16:02 Tue 7 16:02 Mon 6 23:57 Sat 4 03:01 Fri 3 23:00 Thu 2 23:59 Wed 1 21:01

Connect to external tools with MCP

Configure MCP servers to extend your agent with external tools. Covers transport types, tool search for large tool sets, authentication, and error handling.

The Model Context Protocol (MCP) is an open standard for connecting AI agents to external tools and data sources. With MCP, your agent can query databases, integrate with APIs like Slack and GitHub, and connect to other services without writing custom tool implementations.

MCP servers can run as local processes, connect over HTTP, or execute directly within your SDK application.

Quickstart

This example connects to the Claude Code documentation MCP server using HTTP transport and uses allowedTools with a wildcard to permit all tools from the server.

import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
prompt: "Use the docs MCP server to explain what hooks are in Claude Code",
options: {
mcpServers: {
"claude-code-docs": {
type: "http",
url: "https://code.claude.com/docs/mcp"
}
},
allowedTools: ["mcp__claude-code-docs__*"]
}
})) {
if (message.type === "result" && message.subtype === "success") {
console.log(message.result);
}
}

The agent connects to the documentation server, searches for information about hooks, and returns the results.

Add an MCP server

You can configure MCP servers in code when calling query(), or in a .mcp.json file loaded via settingSources.

In code

Pass MCP servers directly in the mcpServers option:

import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
prompt: "List files in my project",
options: {
mcpServers: {
filesystem: {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]
}
},
allowedTools: ["mcp__filesystem__*"]
}
})) {
if (message.type === "result" && message.subtype === "success") {
console.log(message.result);
}
}

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:

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]
    }
  }
}

Connection timing

Servers you pass in options.mcpServers start connecting as soon as the query starts. Connection is non-blocking by default: the first turn begins without waiting, and each server's tools become available once its connection completes. {/* min-version: 2.1.142 */}Before Claude Code v2.1.142, startup blocked on the connection batch for up to 5 seconds.

To restore a bounded startup wait for every server, set the MCP_CONNECTION_NONBLOCKING environment variable to 0. The wait is capped at 5 seconds by MCP_CONNECT_TIMEOUT_MS, and servers still pending at that deadline keep connecting in the background.

To make one server's tools available before the first turn, set alwaysLoad: true on its config. Startup then waits for that server to connect, capped at the same 5-second startup deadline, while other servers keep connecting in the background. The alwaysLoad field requires Claude Code v2.1.121 or later. See Exempt a server from deferral for the alwaysLoad field's effect on tool search.

The system message with subtype init reports each server's status at the moment it's emitted. A server that's still connecting has status pending. Check for status failed or needs-auth when you want to detect servers that won't be usable, rather than treating every status other than connected as a failure; see Error handling for the full status check.

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 pattern mcp__<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

Use allowedTools to auto-approve specific MCP tools so Claude can use them without a permission prompt:

const _ = {
options: {
mcpServers: {
// your servers
},
allowedTools: [
"mcp__github__*", // All tools from the github server
"mcp__db__query", // Only the query tool from db server
"mcp__slack__send_message" // Only send_message from slack server
]
}
};

Wildcards (*) let you allow all tools from a server without listing each one individually.

Discover available tools

To see what tools an MCP server provides, check the server's documentation or inspect the tools array in the system init message. MCP tool names start with mcp__.

MCP servers connect in the background by default, so the init message arrives before they finish: the tools array lists only built-in tools and mcp_servers shows a pending status for each server. Set the MCP_CONNECTION_NONBLOCKING environment variable to 0 to wait up to 5 seconds for servers to connect before the init message is sent; servers that connect in time list their mcp__ tools there, and slower ones keep connecting in the background:

export MCP_CONNECTION_NONBLOCKING=0

With that variable set, this filter prints the MCP tool names:

import { query } from "@anthropic-ai/claude-agent-sdk";

const options = {
mcpServers: {
// your servers
},
};

for await (const message of query({ prompt: "...", options })) {
if (message.type === "system" && message.subtype === "init") {
const mcpTools = message.tools.filter((name) => name.startsWith("mcp__"));
console.log("Available MCP tools:", mcpTools);
}
}

You can also ask Claude to list the tools available from a server.

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:

const _ = {
options: {
mcpServers: {
filesystem: {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]
}
},
allowedTools: ["mcp__filesystem__read_file", "mcp__filesystem__list_directory"]
}
};

HTTP/SSE servers

Use HTTP or SSE for cloud-hosted MCP servers and remote APIs:

const _ = {
options: {
mcpServers: {
"remote-api": {
type: "sse",
url: "https://api.example.com/mcp/sse",
headers: {
Authorization: `Bearer ${process.env.API_TOKEN}`
}
}
},
allowedTools: ["mcp__remote-api__*"]
}
};

For the streamable HTTP transport, use "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.

{/* min-version: 2.1.210 */}An SDK MCP server registered by an initialize control request begins connecting as soon as Claude Code processes the request.

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 the env field to pass API keys, tokens, and other credentials to the MCP server:

const _ = {
options: {
mcpServers: {
"api-server": {
command: "npx",
args: ["-y", "@your-org/api-mcp-server"],
env: {
API_KEY: process.env.API_KEY
}
}
},
allowedTools: ["mcp__api-server__*"]
}
};

HTTP headers for remote servers

For HTTP and SSE servers, pass authentication headers directly in the server configuration:

const _ = {
options: {
mcpServers: {
"secure-api": {
type: "http",
url: "https://api.example.com/mcp",
headers: {
Authorization: `Bearer ${process.env.API_TOKEN}`
}
}
},
allowedTools: ["mcp__secure-api__*"]
}
};

For a complete working example of a remote server authenticated with headers, see List issues from a repository.

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 status needs-auth. Because servers connect in the background by default, the mcp_servers array of the system init message may still show pending for that server. To confirm whether a server needs credentials, poll mcpServerStatus() in the TypeScript SDK or get_mcp_status() in Python, or set MCP_CONNECTION_NONBLOCKING=0 to wait for connections before the init message.

To supply credentials, complete the OAuth flow in your own application and pass the resulting access token in the server's headers:

// After completing OAuth flow in your app.
// Implement getAccessTokenFromOAuthFlow for your OAuth provider.
const accessToken = await getAccessTokenFromOAuthFlow();

const options = {
mcpServers: {
"oauth-api": {
type: "http",
url: "https://api.example.com/mcp",
headers: {
Authorization: `Bearer ${accessToken}`
}
}
},
allowedTools: ["mcp__oauth-api__*"]
};

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:

export GITHUB_TOKEN=YOUR_GITHUB_PAT
import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
prompt: "List the 3 most recent issues in anthropics/claude-code",
options: {
mcpServers: {
github: {
type: "http",
url: "https://api.githubcopilot.com/mcp/",
headers: {
Authorization: `Bearer ${process.env.GITHUB_TOKEN}`
}
}
},
allowedTools: ["mcp__github__list_issues"]
}
})) {
// Verify MCP server connected successfully
if (message.type === "system" && message.subtype === "init") {
console.log("MCP servers:", message.mcp_servers);
}

// Log when Claude calls an MCP tool
if (message.type === "assistant") {
for (const block of message.message.content) {
if (block.type === "tool_use" && block.name.startsWith("mcp__")) {
console.log("MCP tool called:", block.name);
}
}
}

// Print the final result
if (message.type === "result" && message.subtype === "success") {
console.log(message.result);
}
}

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's execute_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:

[[sources]]
id = "production"
dsn = "${DATABASE_URL}"

[[tools]]
name = "execute_sql"
source = "production"
readonly = true

The script then points DBHub at the config file instead of passing a connection string directly. Before running, set the DATABASE_URL environment variable to your connection string. Replace the placeholder values with your own database details:

export DATABASE_URL=postgresql://user:password@localhost:5432/mydb
import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
// Natural language query - Claude writes the SQL
prompt: "How many users signed up last week? Break it down by day.",
options: {
mcpServers: {
postgres: {
command: "npx",
// dbhub.toml sets readonly = true, so execute_sql rejects writes
args: ["-y", "@bytebase/dbhub", "--config", "dbhub.toml"]
}
},
allowedTools: ["mcp__postgres__execute_sql"]
}
})) {
if (message.type === "result" && message.subtype === "success") {
console.log(message.result);
}
}

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.

The SDK emits a system 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". Because connection is non-blocking by default, healthy servers often still report "pending" when the init message is emitted. Check for "failed" or "needs-auth" to detect servers that won't be usable, and don't treat "pending" as a failure:

import { query } from "@anthropic-ai/claude-agent-sdk";

try {
for await (const message of query({
prompt: "Process data",
options: {
mcpServers: {
// Replace dataServer with your server configuration
"data-processor": dataServer
}
}
})) {
if (message.type === "system" && message.subtype === "init") {
const unavailableServers = message.mcp_servers.filter(
(s) => s.status === "failed" || s.status === "needs-auth"
);

if (unavailableServers.length > 0) {
console.warn("Unavailable MCP servers:", unavailableServers);
}
}

if (message.type === "result" && message.subtype === "error_during_execution") {
console.error("Execution failed");
}
}
} catch (error) {
// A single-shot query() throws after yielding an error result.
// If the failure was an error result, the error subtype branch above
// has already run; connection or process failures yield no result
// message.
console.log(`Session ended with an error: ${error}`);
}

Troubleshooting

Server shows "failed" status

Check the init message to see which servers failed to connect:

if (message.type === "system" && message.subtype === "init") {
for (const server of message.mcp_servers) {
if (server.status === "failed") {
console.error(`Server ${server.name} failed to connect`);
}
}
}

A "pending" status means the server is still connecting, not that it failed. 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 env field matches what the server expects.
  • Server not installed: For npx commands, 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 with allowedTools:

const _ = {
options: {
mcpServers: {
// your servers
},
allowedTools: ["mcp__servername__*"] // Auto-approve calls from this server
}
};

Connection timeouts

MCP server connections time out after 30 seconds by default. If your server takes longer to start, the connection fails. Raise the 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 the MAX_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.

  • 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 allowedTools and disallowedTools
  • MCP output limits and warnings: How the SDK handles tool results that exceed MAX_MCP_OUTPUT_TOKENS, including the persist-to-disk fallback and the anthropic/maxResultSizeChars per-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