English ← MyDocs

文档索引

在此获取完整文档索引: https://code.claude.com/docs/llms.txt 使用此文件发现所有可用页面,然后再进一步探索。

使用 MCP 连接外部工具

配置 MCP 服务器以使用外部工具扩展您的智能体。涵盖传输类型、大型工具集的工具搜索、认证和错误处理。

模型上下文协议(MCP)是将 AI 智能体连接到外部工具和数据源的开放标准。使用 MCP,您的智能体可以查询数据库、与 Slack 和 GitHub 等 API 集成,以及连接到其他服务,而无需编写自定义工具实现。

MCP 服务器可以作为本地进程运行、通过 HTTP 连接,或直接在您的 SDK 应用程序中执行。

Note

本页介绍 Agent SDK 的 MCP 配置。要将 MCP 服务器添加到 Claude Code CLI 以便在每个项目中加载,请参阅 MCP 安装范围

快速入门

此示例使用 HTTP 传输连接到 Claude Code 文档 MCP 服务器,并使用 allowedTools 配合通配符允许服务器的所有工具。

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);
  }
}
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage


async def main():
    options = ClaudeAgentOptions(
        mcp_servers={
            "claude-code-docs": {
                "type": "http",
                "url": "https://code.claude.com/docs/mcp",
            }
        },
        allowed_tools=["mcp__claude-code-docs__*"],
    )

    async for message in query(
        prompt="Use the docs MCP server to explain what hooks are in Claude Code",
        options=options,
    ):
        if isinstance(message, ResultMessage) and message.subtype == "success":
            print(message.result)


asyncio.run(main())

智能体连接到文档服务器,搜索有关钩子的信息,并返回结果。

添加 MCP 服务器

您可以在调用 query() 时在代码中配置 MCP 服务器,或在通过 settingSources 加载的 .mcp.json 文件中配置。

在代码中

mcpServers 选项中直接传递 MCP 服务器:

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);
  }
}
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage


async def main():
    options = ClaudeAgentOptions(
        mcp_servers={
            "filesystem": {
                "command": "npx",
                "args": [
                    "-y",
                    "@modelcontextprotocol/server-filesystem",
                    "/Users/me/projects",
                ],
            }
        },
        allowed_tools=["mcp__filesystem__*"],
    )

    async for message in query(prompt="List files in my project", options=options):
        if isinstance(message, ResultMessage) and message.subtype == "success":
            print(message.result)


asyncio.run(main())

从配置文件

在项目根目录创建 .mcp.json 文件。当 project 设置源启用时(默认 query() 选项会启用),该文件会被拾取。如果您显式设置了 settingSources,请包含 "project" 以加载此文件:

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

允许 MCP 工具

MCP 工具需要明确的权限才能让 Claude 使用它们。没有权限,Claude 将看到工具可用但无法调用它们。

工具命名约定

MCP 工具遵循命名模式 mcp__<server-name>__<tool-name>。例如,名为 "github" 的 GitHub 服务器的 list_issues 工具变为 mcp__github__list_issues

使用 allowedTools 自动批准

使用 allowedTools 自动批准特定 MCP 工具,以便 Claude 无需权限提示即可使用它们:

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
    ]
  }
};

通配符(*)允许您允许服务器的所有工具,而无需逐个列出。

Note

对于 MCP 访问,优先使用 allowedTools 而不是权限模式。 permissionMode: "acceptEdits" 不会自动批准 MCP 工具(仅文件编辑和文件系统 Bash 命令)。permissionMode: "bypassPermissions" 确实自动批准 MCP 工具,但也禁用所有其他安全提示,这比必要的范围更广。allowedTools 中的通配符仅授予您想要的 MCP 服务器,不多不少。有关完整比较,请参阅权限模式

发现可用工具

要查看 MCP 服务器提供哪些工具,请检查服务器的文档或连接到服务器并检查 system 初始化消息:

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

传输类型

MCP 服务器使用不同的传输协议与您的智能体通信。检查服务器的文档以查看其支持的传输方式:

  • 如果文档给您一个要运行的命令(如 npx @modelcontextprotocol/server-github),使用 stdio
  • 如果文档给您一个 URL,使用 HTTP 或 SSE
  • 如果您在代码中构建自己的工具,使用 SDK MCP 服务器

stdio 服务器

通过 stdin/stdout 通信的本地进程。对您在同一台机器上运行的 MCP 服务器使用此方式:

const _ = {
  options: {
    mcpServers: {
      github: {
        command: "npx",
        args: ["-y", "@modelcontextprotocol/server-github"],
        env: {
          GITHUB_TOKEN: process.env.GITHUB_TOKEN
        }
      }
    },
    allowedTools: ["mcp__github__list_issues", "mcp__github__search_issues"]
  }
};
options = ClaudeAgentOptions(
    mcp_servers={
        "github": {
            "command": "npx",
            "args": ["-y", "@modelcontextprotocol/server-github"],
            "env": {"GITHUB_TOKEN": os.environ["GITHUB_TOKEN"]},
        }
    },
    allowed_tools=["mcp__github__list_issues", "mcp__github__search_issues"],
)
{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "${GITHUB_TOKEN}"
      }
    }
  }
}

HTTP/SSE 服务器

对云托管的 MCP 服务器和远程 API 使用 HTTP 或 SSE:

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__*"]
  }
};
options = ClaudeAgentOptions(
    mcp_servers={
        "remote-api": {
            "type": "sse",
            "url": "https://api.example.com/mcp/sse",
            "headers": {"Authorization": f"Bearer {os.environ['API_TOKEN']}"},
        }
    },
    allowed_tools=["mcp__remote-api__*"],
)
{
  "mcpServers": {
    "remote-api": {
      "type": "sse",
      "url": "https://api.example.com/mcp/sse",
      "headers": {
        "Authorization": "Bearer ${API_TOKEN}"
      }
    }
  }
}

对于可流式 HTTP 传输,请改用 "type": "http"。在 .mcp.json 和其他 JSON 配置文件中,"streamable-http" 作为 "http" 的别名被接受。编程 mcpServers 选项仅接受 "http"

SDK MCP 服务器

直接在应用程序代码中定义自定义工具,而不是运行单独的服务器进程。有关实现详情,请参阅自定义工具指南

MCP 工具搜索

当您配置了许多 MCP 工具时,工具定义可能会消耗上下文窗口的很大一部分。工具搜索通过从上下文中保留工具定义并仅加载 Claude 在每一轮中需要的工具来解决这个问题。

工具搜索默认启用。有关配置选项和详情,请参阅工具搜索

有关更多详情,包括最佳实践以及将工具搜索与自定义 SDK 工具一起使用,请参阅工具搜索指南

认证

大多数 MCP 服务器需要认证才能访问外部服务。通过服务器配置中的环境变量传递凭据。

通过环境变量传递凭据

使用 env 字段将 API 密钥、令牌和其他凭据传递给 MCP 服务器:

const _ = {
  options: {
    mcpServers: {
      github: {
        command: "npx",
        args: ["-y", "@modelcontextprotocol/server-github"],
        env: {
          GITHUB_TOKEN: process.env.GITHUB_TOKEN
        }
      }
    },
    allowedTools: ["mcp__github__list_issues"]
  }
};
options = ClaudeAgentOptions(
    mcp_servers={
        "github": {
            "command": "npx",
            "args": ["-y", "@modelcontextprotocol/server-github"],
            "env": {"GITHUB_TOKEN": os.environ["GITHUB_TOKEN"]},
        }
    },
    allowed_tools=["mcp__github__list_issues"],
)
{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "${GITHUB_TOKEN}"
      }
    }
  }
}

{{CONTENT}}amp;#123;GITHUB_TOKEN&#125; 语法在运行时展开环境变量。

有关带有调试日志的完整工作示例,请参阅列出仓库中的问题

远程服务器的 HTTP 头

对于 HTTP 和 SSE 服务器,在服务器配置中直接传递认证头:

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

{{CONTENT}}amp;#123;API_TOKEN&#125; 语法在运行时展开环境变量。

OAuth2 认证

MCP 规范支持 OAuth 2.1 进行授权。SDK 不会自动处理 OAuth 流程,但您可以在应用程序中完成 OAuth 流程后通过头传递访问令牌:

// After completing OAuth flow in your app
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__*"]
};
# After completing OAuth flow in your app
access_token = await get_access_token_from_oauth_flow()

options = ClaudeAgentOptions(
    mcp_servers={
        "oauth-api": {
            "type": "http",
            "url": "https://api.example.com/mcp",
            "headers": {"Authorization": f"Bearer {access_token}"},
        }
    },
    allowed_tools=["mcp__oauth-api__*"],
)

示例

列出仓库中的问题

此示例连接到 GitHub MCP 服务器以列出最近的问题。该示例包含调试日志以验证 MCP 连接和工具调用。

运行前,创建一个具有 repo 范围的 GitHub 个人访问令牌并将其设置为环境变量:

export GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxx
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: {
        command: "npx",
        args: ["-y", "@modelcontextprotocol/server-github"],
        env: {
          GITHUB_TOKEN: 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);
  }
}
import asyncio
import os
from claude_agent_sdk import (
    query,
    ClaudeAgentOptions,
    ResultMessage,
    SystemMessage,
    AssistantMessage,
)


async def main():
    options = ClaudeAgentOptions(
        mcp_servers={
            "github": {
                "command": "npx",
                "args": ["-y", "@modelcontextprotocol/server-github"],
                "env": {"GITHUB_TOKEN": os.environ["GITHUB_TOKEN"]},
            }
        },
        allowed_tools=["mcp__github__list_issues"],
    )

    async for message in query(
        prompt="List the 3 most recent issues in anthropics/claude-code",
        options=options,
    ):
        # Verify MCP server connected successfully
        if isinstance(message, SystemMessage) and message.subtype == "init":
            print("MCP servers:", message.data.get("mcp_servers"))

        # Log when Claude calls an MCP tool
        if isinstance(message, AssistantMessage):
            for block in message.content:
                if hasattr(block, "name") and block.name.startswith("mcp__"):
                    print("MCP tool called:", block.name)

        # Print the final result
        if isinstance(message, ResultMessage) and message.subtype == "success":
            print(message.result)


asyncio.run(main())

查询数据库

此示例使用 Postgres MCP 服务器查询数据库。连接字符串作为参数传递给服务器。智能体自动发现数据库模式,编写 SQL 查询并返回结果:

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

// Connection string from environment variable
const connectionString = process.env.DATABASE_URL;

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",
        // Pass connection string as argument to the server
        args: ["-y", "@modelcontextprotocol/server-postgres", connectionString]
      }
    },
    // Allow only read queries, not writes
    allowedTools: ["mcp__postgres__query"]
  }
})) {
  if (message.type === "result" && message.subtype === "success") {
    console.log(message.result);
  }
}
import asyncio
import os
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage


async def main():
    # Connection string from environment variable
    connection_string = os.environ["DATABASE_URL"]

    options = ClaudeAgentOptions(
        mcp_servers={
            "postgres": {
                "command": "npx",
                # Pass connection string as argument to the server
                "args": [
                    "-y",
                    "@modelcontextprotocol/server-postgres",
                    connection_string,
                ],
            }
        },
        # Allow only read queries, not writes
        allowed_tools=["mcp__postgres__query"],
    )

    # Natural language query - Claude writes the SQL
    async for message in query(
        prompt="How many users signed up last week? Break it down by day.",
        options=options,
    ):
        if isinstance(message, ResultMessage) and message.subtype == "success":
            print(message.result)


asyncio.run(main())

错误处理

MCP 服务器可能因各种原因连接失败:服务器进程可能未安装、凭据可能无效,或远程服务器可能无法访问。

SDK 在每次查询开始时发出一个子类型为 initsystem 消息。此消息包含每个 MCP 服务器的连接状态。在智能体开始工作之前检查 status 字段以检测连接失败:

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

for await (const message of query({
  prompt: "Process data",
  options: {
    mcpServers: {
      "data-processor": dataServer
    }
  }
})) {
  if (message.type === "system" && message.subtype === "init") {
    const failedServers = message.mcp_servers.filter((s) => s.status !== "connected");

    if (failedServers.length > 0) {
      console.warn("Failed to connect:", failedServers);
    }
  }

  if (message.type === "result" && message.subtype === "error_during_execution") {
    console.error("Execution failed");
  }
}
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage, ResultMessage


async def main():
    options = ClaudeAgentOptions(mcp_servers={"data-processor": data_server})

    async for message in query(prompt="Process data", options=options):
        if isinstance(message, SystemMessage) and message.subtype == "init":
            failed_servers = [
                s
                for s in message.data.get("mcp_servers", [])
                if s.get("status") != "connected"
            ]

            if failed_servers:
                print(f"Failed to connect: {failed_servers}")

        if (
            isinstance(message, ResultMessage)
            and message.subtype == "error_during_execution"
        ):
            print("Execution failed")


asyncio.run(main())

故障排除

服务器显示 "failed" 状态

检查 init 消息以查看哪些服务器连接失败:

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`);
    }
  }
}

常见原因:

  • 缺少环境变量:确保设置了所需的令牌和凭据。对于 stdio 服务器,检查 env 字段是否与服务器期望的匹配。
  • 服务器未安装:对于 npx 命令,验证包是否存在且 Node.js 在您的 PATH 中。
  • 连接字符串无效:对于数据库服务器,验证连接字符串格式以及数据库是否可访问。
  • 网络问题:对于远程 HTTP/SSE 服务器,检查 URL 是否可达以及防火墙是否允许连接。

工具未被调用

如果 Claude 看到工具但不使用它们,请检查您是否已使用 allowedTools 授予权限:

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

连接超时

MCP SDK 对服务器连接的默认超时为 60 秒。如果您的服务器启动时间更长,连接将失败。对于需要更多启动时间的服务器,请考虑:

  • 如果可用,使用更轻量级的服务器
  • 在启动智能体之前预热服务器
  • 检查服务器日志以了解缓慢初始化的原因

相关资源

  • 自定义工具指南:构建在 SDK 应用程序中以进程内方式运行的自定义 MCP 服务器
  • 权限:使用 allowedToolsdisallowedTools 控制您的智能体可以使用哪些 MCP 工具
  • TypeScript SDK 参考:完整的 API 参考,包括 MCP 配置选项
  • Python SDK 参考:完整的 API 参考,包括 MCP 配置选项
  • MCP 服务器目录:浏览可用的 MCP 服务器,包括数据库、API 等