本页目录28
- MCP 工具需要在 `allowedTools` 中显式授权(格式为 `mcp__<server-name>__<tool-name>`),否则 Claude 只能看到工具但无法调用
- 三种主要传输类型:stdio(本地进程)、HTTP/SSE(远程服务)、SDK MCP server(进程内自定义工具)
- 服务器连接是否阻塞首轮对话取决于类型:stdio/无缓存工具列表的 HTTP-SSE 会等待连接(默认超时由 `MCP_TIMEOUT` 控制,30秒);已缓存工具列表的远程服务器和 SDK 服务器不阻塞首轮
- `system` 类型、`init` 子类型消息报告每个服务器状态:`pending`、`connected`、`failed`、`needs-auth`、`disabled`,`pending` 不等于失败
- SDK 本身不处理 OAuth2 交互流程,需要在自己的应用中完成 OAuth 后把 access token 通过 `headers` 传入
- 工具输出超过 25000 tokens(由 `MAX_MCP_OUTPUT_TOKENS` 控制)会被写入文件,工具结果替换为包含文件路径的错误信息
本文是对 Claude Agent SDK 官方文档「Connect to external tools with MCP」页面的中文整理,完整与最新内容以原文为准:https://code.claude.com/docs/en/agent-sdk/mcp
Model Context Protocol (MCP) 是一个开放标准,用于把 AI agent 连接到外部工具和数据源。通过 MCP,你的 agent 可以查询数据库、集成 Slack、GitHub 等 API,而无需自己编写工具实现。
MCP 服务器可以作为本地进程运行、通过 HTTP 连接,或直接在 SDK 应用内部执行。
本页面讲的是 Agent SDK 中的 MCP 配置。若要把 MCP 服务器加到 Claude Code CLI、让它在每个项目中都加载,请参见官方文档中「MCP installation scopes」一节。
快速开始
下面的例子通过 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())
agent 连接到文档服务器,搜索与 hooks 相关的信息,并返回结果。
添加 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 文件。默认 query() 选项启用了 project 这个 setting source,该文件就会被加载;如果你显式设置了 settingSources,需要包含 "project" 才会加载此文件:
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]
}
}
}
连接时机
Claude Code 会在启动时注册通过 options.mcpServers 传入的服务器,并在首轮等待(如果有的话)结束后发出 init 消息。通过 .mcp.json 等 settings 文件加载的服务器不会获得完整的等待时间,在 init 时通常显示为 pending。每个 options.mcpServers 服务器何时连接、是否会延迟首轮对话,取决于其类型:
| 服务器类型 | 是否延迟首轮对话? | 首轮等待超时 |
|---|---|---|
| stdio 服务器,或没有缓存工具列表的 HTTP/SSE 服务器 | 是,直到连接成功为止 | MCP_TIMEOUT,默认 30 秒;到达该期限连接即失败 |
| 拥有缓存工具列表的远程服务器(Claude Code 从上次连接中保存下来) | 否;缓存的工具从第一轮起就可用 | 无;在首次被调用工具时才连接,该延迟连接有自己的超时 |
| 进程内 SDK server | 否;永远不会延迟首轮对话 | 无 |
要在 init 消息发出之前、更早的独立阶段就阻塞启动本身:
- 将
MCP_CONNECTION_NONBLOCKING设为0,即可阻塞在整批连接上。Claude Code 默认把这个等待上限设为 5 秒,可通过环境变量MCP_CONNECT_TIMEOUT_MS(单位毫秒)调整该上限。到期限仍未连接的服务器会在后台继续尝试连接。 - 在服务器配置上设置
alwaysLoad: true,使其工具在首轮对话中以完整 schema 可用,从而豁免工具搜索的延迟加载。Claude Code 会在启动时等待该服务器的工具(同样受上面的期限限制),其余服务器则在后台继续连接;按上表规则,若该服务器拥有缓存的工具列表,则无需连接即可直接提供工具。
system 消息、子类型为 init 时,会报告发出这条消息那一刻各服务器的状态;具体状态取值见下方「错误处理」一节。
允许使用 MCP 工具
MCP 工具在被 Claude 使用前需要显式授权。没有授权,Claude 能看到工具存在,但无法调用。
工具命名规则
MCP 工具遵循命名格式 mcp__<server-name>__<tool-name>。例如,一个名为 "github" 的服务器,其 list_issues 工具会变成 mcp__github__list_issues。
用 allowedTools 自动批准
使用 allowedTools 自动批准指定的 MCP 工具,这样 Claude 无需权限弹窗即可使用它们:
const _ = {
options: {
mcpServers: {
// 你的服务器
},
allowedTools: [
"mcp__github__*", // github 服务器的全部工具
"mcp__db__query", // 仅 db 服务器的 query 工具
"mcp__slack__send_message" // 仅 slack 的 send_message
]
}
};
options = ClaudeAgentOptions(
mcp_servers={
# 你的服务器
},
allowed_tools=[
"mcp__github__*", # github 服务器的全部工具
"mcp__db__query", # 仅 db 服务器的 query 工具
"mcp__slack__send_message", # 仅 slack 的 send_message
],
)
通配符(*)可以在不逐个列出的情况下批准某服务器的所有工具。
建议优先用
allowedTools而不是权限模式来控制 MCP 访问。permissionMode: "acceptEdits"不会自动批准 MCP 工具(只自动批准文件编辑和文件系统相关的 Bash 命令)。permissionMode: "bypassPermissions"会自动批准 MCP 工具,但同时也会关闭大部分其他安全提示,范围比实际需要的更大。allowedTools中的通配符只精确授权你指定的 MCP 服务器,不多不少。
发现可用工具
要查看某个 MCP 服务器提供哪些工具,可查阅该服务器文档,或检查 system init 消息中的 tools 数组。MCP 工具名都以 mcp__ 开头。
Claude Code 会在针对 options.mcpServers 服务器的首轮连接等待结束后发出 init 消息,因此 tools 数组会列出到那时已连接服务器的 mcp__ 工具,以及拥有缓存工具列表的服务器的工具(这些服务器在首次使用时才真正连接)。尚未连接的其他服务器的工具则不会出现;具体状态请看「错误处理」一节。
下面的过滤逻辑可以打印出 MCP 工具名:
import { query } from "@anthropic-ai/claude-agent-sdk";
const options = {
mcpServers: {
// 你的服务器
},
};
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);
}
}
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage
async def main():
options = ClaudeAgentOptions(
mcp_servers={
# 你的服务器
},
)
async for message in query(prompt="...", options=options):
if isinstance(message, SystemMessage) and message.subtype == "init":
mcp_tools = [t for t in message.data.get("tools", []) if t.startswith("mcp__")]
print("Available MCP tools:", mcp_tools)
asyncio.run(main())
也可以直接让 Claude 列出某服务器可用的工具。
传输类型
MCP 服务器与 agent 之间可以使用不同传输协议通信。请查阅服务器文档确认它支持哪种传输:
- 如果文档给出的是一条运行命令(例如
npx @modelcontextprotocol/server-filesystem),使用 stdio - 如果文档给出的是一个 URL,使用 HTTP 或 SSE
- 如果你在代码中构建自己的工具,使用 SDK MCP server
stdio 服务器
通过 stdin/stdout 通信的本地进程,用于你在同一台机器上运行的 MCP 服务器。.mcp.json 中的字段与「从配置文件读取」一节相同。在代码中,传入命令及其参数:
const _ = {
options: {
mcpServers: {
filesystem: {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]
}
},
allowedTools: ["mcp__filesystem__read_file", "mcp__filesystem__list_directory"]
}
};
options = ClaudeAgentOptions(
mcp_servers={
"filesystem": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-filesystem",
"/Users/me/projects",
],
}
},
allowed_tools=["mcp__filesystem__read_file", "mcp__filesystem__list_directory"],
)
HTTP/SSE 服务器
用于云端托管的 MCP 服务器和远程 API:
在代码中:
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__*"],
)
在 .mcp.json 中:
{
"mcpServers": {
"remote-api": {
"type": "sse",
"url": "https://api.example.com/mcp/sse",
"headers": {
"Authorization": "Bearer ${API_TOKEN}"
}
}
}
}
若要使用 streamable HTTP 传输,用 "type": "http" 代替。在 .mcp.json 等 JSON 配置文件中,"streamable-http" 是 "http" 的别名。但代码里的 mcpServers 选项只接受 "http"。
SDK MCP 服务器
直接在应用代码中定义自定义工具,而不用另起一个服务器进程。具体实现细节参见官方「custom tools guide」。
通过 initialize control request 注册的 SDK MCP 服务器,会在 Claude Code 处理该请求时立即开始连接。
MCP 工具搜索
当配置了大量 MCP 工具时,工具定义会占用上下文窗口的相当一部分。工具搜索(tool search)通过把工具定义暂不放入上下文、只在每一轮按需加载所需工具来解决这个问题。
工具搜索默认开启。具体配置选项、最佳实践,以及如何将工具搜索用于自定义 SDK 工具,请参见官方「Tool search」文档。
身份验证
大多数 MCP 服务器需要认证才能访问外部服务。在服务器配置中通过环境变量传递凭证。
通过环境变量传递凭证
使用 env 字段把 API key、token 等凭证传给 MCP 服务器:
在代码中:
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__*"]
}
};
options = ClaudeAgentOptions(
mcp_servers={
"api-server": {
"command": "npx",
"args": ["-y", "@your-org/api-mcp-server"],
"env": {"API_KEY": os.environ["API_KEY"]},
}
},
allowed_tools=["mcp__api-server__*"],
)
在 .mcp.json 中:
{
"mcpServers": {
"api-server": {
"command": "npx",
"args": ["-y", "@your-org/api-mcp-server"],
"env": {
"API_KEY": "${API_KEY}"
}
}
}
}
${API_KEY} 这种写法会在运行时展开为对应的环境变量值。
远程服务器的 HTTP headers
对于 HTTP 和 SSE 服务器,可以直接在服务器配置中传入认证 header:
在代码中:
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__*"],
)
在 .mcp.json 中:
{
"mcpServers": {
"secure-api": {
"type": "http",
"url": "https://api.example.com/mcp",
"headers": {
"Authorization": "Bearer ${API_TOKEN}"
}
}
}
}
${API_TOKEN} 会在运行时展开为对应的环境变量值。
完整的、带 header 认证的远程服务器示例见下方「从仓库列出 issue」。
OAuth2 认证
MCP 规范支持 OAuth 2.1 授权方式。SDK 本身不会打开浏览器、也不会运行交互式 OAuth 流程。当配置的服务器返回授权挑战、且没有已保存的 token 时,agent 运行会在没有该服务器工具的情况下继续,该服务器状态报告为 needs-auth。发出 system init message 时,mcp_servers 数组对该服务器可能仍显示 pending。要确认某服务器是否需要凭证,可在 TypeScript SDK 中轮询 mcpServerStatus(),或在 Python 中使用 get_mcp_status()。
要提供凭证,需要在你自己的应用中完成 OAuth 流程,然后把得到的 access token 传入服务器的 headers:
// 在你的应用中完成 OAuth 流程之后。
// 需要为你的 OAuth provider 实现 getAccessTokenFromOAuthFlow。
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__*"]
};
# 在你的应用中完成 OAuth 流程之后。
# 需要为你的 OAuth provider 实现 get_access_token_from_oauth_flow。
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__*"],
)
示例
从仓库列出 issue
这个例子连接远程 GitHub MCP server 来列出最近的 issue,并带调试日志来验证 MCP 连接与工具调用。
运行前,先创建一个 GitHub personal access token,赋予对目标仓库的读权限,并设为环境变量:
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"]
}
})) {
// 验证 MCP 服务器是否连接成功
if (message.type === "system" && message.subtype === "init") {
console.log("MCP servers:", message.mcp_servers);
}
// 记录 Claude 何时调用了 MCP 工具
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);
}
}
}
// 打印最终结果
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": {
"type": "http",
"url": "https://api.githubcopilot.com/mcp/",
"headers": {"Authorization": f"Bearer {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,
):
# 验证 MCP 服务器是否连接成功
if isinstance(message, SystemMessage) and message.subtype == "init":
print("MCP servers:", message.data.get("mcp_servers"))
# 记录 Claude 何时调用了 MCP 工具
if isinstance(message, AssistantMessage):
for block in message.content:
if hasattr(block, "name") and block.name.startswith("mcp__"):
print("MCP tool called:", block.name)
# 打印最终结果
if isinstance(message, ResultMessage) and message.subtype == "success":
print(message.result)
asyncio.run(main())
查询数据库
这个例子用 DBHub 查询 Postgres 数据库。agent 会自动发现数据库 schema、写出 SQL 查询,并返回结果。
DBHub 的 execute_sql 工具会执行 agent 生成的任何 SQL,包括写操作,除非你加以限制。在 DBHub 配置文件 中设置 readonly = true,可以让 DBHub 拒绝 INSERT、UPDATE、DELETE 及 DDL 语句,这样即使 agent 生成了写操作,该示例也不会修改你的数据。DBHub 在加载配置时会从进程环境中解析 ${DATABASE_URL},因此连接字符串不会写入文件本身。在脚本旁创建这个 dbhub.toml:
[[sources]]
id = "production"
dsn = "${DATABASE_URL}"
[[tools]]
name = "execute_sql"
source = "production"
readonly = true
脚本随后指向该配置文件,而不是直接传连接字符串。运行前把 DATABASE_URL 环境变量设为你的连接字符串(用你自己的数据库信息替换占位值):
export DATABASE_URL=postgresql://user:password@localhost:5432/mydb
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
// 自然语言查询 —— SQL 由 Claude 编写
prompt: "How many users signed up last week? Break it down by day.",
options: {
mcpServers: {
postgres: {
command: "npx",
// dbhub.toml 设置了 readonly = true,所以 execute_sql 会拒绝写操作
args: ["-y", "@bytebase/dbhub", "--config", "dbhub.toml"]
}
},
allowedTools: ["mcp__postgres__execute_sql"]
}
})) {
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={
"postgres": {
"command": "npx",
# dbhub.toml 设置了 readonly = true,所以 execute_sql 会拒绝写操作
"args": [
"-y",
"@bytebase/dbhub",
"--config",
"dbhub.toml",
],
}
},
allowed_tools=["mcp__postgres__execute_sql"],
)
# 自然语言查询 —— SQL 由 Claude 编写
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 服务器可能因各种原因连接失败:服务器进程可能没有安装、凭证可能无效、远程服务器也可能不可达。
Claude Code 在每次查询开始时会发出一个 system 类型、子类型为 init 的消息,其中包含每个 MCP 服务器的连接状态。status 字段可取值为 "pending"、"connected"、"failed"、"needs-auth" 或 "disabled"。Claude Code 会在针对 options.mcpServers 服务器的首轮连接等待结束后发出 init 消息,因此在这段等待内完成连接的服务器会显示 "connected"。"pending" 状态表示该服务器还没连上,这在下面两种情况下很常见:一是从 settings 文件加载、没有获得完整等待时间的服务器;二是工具列表是从缓存中提供、实际连接是在首次使用时才建立的服务器;到达期限仍未完成连接的服务器,报告出来的状态可能是 "pending" 也可能是 "failed",取决于具体时机。不要把 "pending" 当作失败。要检测不可用的服务器,应检查是否为 "failed" 或 "needs-auth":
import { query } from "@anthropic-ai/claude-agent-sdk";
try {
for await (const message of query({
prompt: "Process data",
options: {
mcpServers: {
// 用你的服务器配置替换 dataServer
"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) {
// 单次 query() 会在产出一条错误结果消息之后抛出异常。如果失败是一条错误结果,
// 上面的 error subtype 分支已经处理过了;若是启动失败或连不上 Claude Code 进程,
// 则不会产出任何 result 消息。连接失败的 MCP 服务器不会抛出异常:
// 用上面的状态检查即可,注意 init 时仍为 "pending" 的服务器需要之后再查一次状态。
console.log(`Session ended with an error: ${error}`);
}
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage, ResultMessage
async def main():
# 用你的服务器配置替换 data_server
options = ClaudeAgentOptions(mcp_servers={"data-processor": data_server})
try:
async for message in query(prompt="Process data", options=options):
if isinstance(message, SystemMessage) and message.subtype == "init":
unavailable_servers = [
s
for s in message.data.get("mcp_servers", [])
if s.get("status") in ("failed", "needs-auth")
]
if unavailable_servers:
print(f"Unavailable MCP servers: {unavailable_servers}")
if (
isinstance(message, ResultMessage)
and message.subtype == "error_during_execution"
):
print("Execution failed")
except Exception as error:
# 单次 query() 会在产出一条错误结果消息之后抛出异常。如果失败是一条错误结果,
# 上面的 error subtype 分支已经处理过了;若是启动失败或连不上 Claude Code 进程,
# 则不会产出任何 result 消息。连接失败的 MCP 服务器不会抛出异常:
# 用上面的状态检查即可,注意 init 时仍为 "pending" 的服务器需要之后再查一次状态。
print(f"Session ended with an error: {error}")
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`);
}
}
}
if isinstance(message, SystemMessage) and message.subtype == "init":
for server in message.data.get("mcp_servers", []):
if server.get("status") == "failed":
print(f"Server {server['name']} failed to connect")
"pending" 状态不代表服务器失败;它在 init 时对应上面提到的两种情况。要在会话中稍后获取更新的状态,可以调用 query 的 mcpServerStatus() 方法(TypeScript SDK),或 Python 中的 ClaudeSDKClient.get_mcp_status()。
常见原因:
- 缺少环境变量:确认所需的 token 和凭证已设置。对 stdio 服务器,检查
env字段是否与服务器预期一致。 - 服务器未安装:对
npx命令,确认包存在且 Node.js 在你的 PATH 中。 - 连接字符串无效:对数据库服务器,确认连接字符串格式正确且数据库可访问。
- 网络问题:对远程 HTTP/SSE 服务器,检查 URL 是否可达,以及防火墙是否放行该连接。
工具没有被调用
如果 Claude 能看到工具但不使用它们,检查是否已通过 allowedTools 授权:
const _ = {
options: {
mcpServers: {
// 你的服务器
},
allowedTools: ["mcp__servername__*"] // 自动批准该服务器的调用
}
};
options = ClaudeAgentOptions(
mcp_servers={
# 你的服务器
},
allowed_tools=["mcp__servername__*"], # 自动批准该服务器的调用
)
连接超时
MCP 服务器连接默认在 30 秒后超时。这个限制只作用于连接建立阶段;若要更改一次正在运行的工具调用允许花费的时长,请设置 MCP_TOOL_TIMEOUT。如果你的服务器启动耗时更长,连接就会失败。可以用环境变量 MCP_TIMEOUT(单位毫秒)提高连接超时限制。对于需要更长启动时间的服务器,还可以考虑:
- 如果有更轻量的服务器,优先使用
- 在启动 agent 之前预热该服务器
- 检查服务器日志,定位初始化缓慢的原因
工具输出超过最大允许 token 数
SDK 采用与 Claude Code 相同的 MCP 输出限制。当某次工具调用结果超过 25,000 tokens 时,完整输出会被保存到文件,工具结果会被替换为一条包含文件路径的错误信息,agent 可以据此分段读回输出。可通过环境变量 MAX_MCP_OUTPUT_TOKENS 提高该限制。完整行为(包括写入磁盘的兜底方式,以及服务器如何通过 anthropic/maxResultSizeChars 这个逐工具 annotation 声明更高的单工具限制)详见官方文档「MCP output limits and warnings」一节。
相关资源
- Custom tools guide:构建你自己的、随 SDK 应用进程内运行的 MCP server
- Permissions:通过
allowedTools与disallowedTools控制 agent 可使用哪些 MCP 工具 - MCP output limits and warnings:SDK 如何处理超过
MAX_MCP_OUTPUT_TOKENS的工具结果,包括写入磁盘的兜底方式和anthropic/maxResultSizeChars这个逐工具 annotation - TypeScript SDK reference:包含 MCP 配置选项的完整 API 参考
- Python SDK reference:包含 MCP 配置选项的完整 API 参考
- MCP server directory(https://github.com/modelcontextprotocol/servers):浏览可用于数据库、API 等场景的 MCP 服务器