Claude Code 中文文档

create: 2026-07-08
update: 2026-07-31
author: thinkycx
category: translation
tags: claude-code, agent-sdk, translation
description: Claude Agent SDK 的 MCP 集成指南,介绍如何通过 MCP 协议连接外部工具和数据源,涵盖传输类型、连接时序、工具搜索、认证和错误处理。
title: 【译】Agent SDK - MCP 集成

【译】SDK MCP 集成

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

Model Context Protocol (MCP) 是连接 AI Agent 与外部工具和数据源的开放标准。 通过 MCP,你的 Agent 可以查询数据库、与 Slack 和 GitHub 等 API 集成,以及连接其他服务,而无需编写自定义工具实现。

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

本页涵盖 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())

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 文件。project 设置源启用时该文件会被读取(默认 query() 选项中已启用)。如果你显式设置了 settingSources,需包含 "project" 才能加载此文件:

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

连接时序

options.mcpServers 中的服务器在 query 启动时即开始连接。 连接默认是非阻塞的:第一轮对话无需等待即可开始,每个服务器的工具在其连接完成后变为可用。在 Claude Code v2.1.142 之前,启动时会阻塞等待连接批次最多 5 秒。

要恢复有界启动等待(等待所有服务器),可将 MCP_CONNECTION_NONBLOCKING 环境变量设为 0。等待上限由 MCP_CONNECT_TIMEOUT_MS 控制(默认 5 秒),超时仍未完成的服务器会在后台继续连接。

要使某个服务器的工具在第一轮对话前就可用,在其配置上设置 alwaysLoad: true。此时启动会等待该服务器连接完成(受相同的 5 秒启动截止时间限制),而其他服务器继续在后台连接。alwaysLoad 字段需要 Claude Code v2.1.121 或更高版本。关于 alwaysLoad 对工具搜索的影响,见免除服务器延迟加载

subtype 为 initsystem 消息会报告每个服务器发出时的状态。仍在连接的服务器状态为 pending。当你需要检测不可用的服务器时,检查 failedneeds-auth 状态,不要把 pending 以外的所有状态都视为失败;完整的状态检查见错误处理

允许 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: {
    // 你的服务器
  },
  allowedTools: [
    "mcp__github__*",            // github 服务器的所有工具
    "mcp__db__query",            // 仅 db 服务器的 query 工具
    "mcp__slack__send_message"   // 仅 slack 的 send_message
  ]
};
options = ClaudeAgentOptions(
    mcp_servers={
        # your servers
    },
    allowed_tools=[
        "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
    ],
)

通配符(*)让你可以允许服务器的所有工具,无需逐一列出。

对于 MCP 访问,优先使用 allowedTools 而非权限模式。 permissionMode: "acceptEdits" 不会自动批准 MCP 工具(仅文件编辑和文件系统 Bash 命令)。permissionMode: "bypassPermissions" 会自动批准 MCP 工具,但也会禁用大多数其他安全提示,这比所需范围更广;关于哪些提示仍然保留,见权限评估方式allowedTools 中的通配符精确授予你想要的 MCP 服务器,不会多也不会少。完整对比见权限模式

发现可用工具

要查看 MCP 服务器提供了哪些工具, 查看服务器文档或检查 system init 消息中的 tools 数组。MCP 工具名以 mcp__ 开头。

MCP 服务器默认在后台连接,因此 init 消息在连接完成前就会到达:tools 数组仅列出内置工具,mcp_servers 对每个服务器显示 pending 状态。将 MCP_CONNECTION_NONBLOCKING 环境变量设为 0 可在发送 init 消息前等待服务器连接(最多 5 秒);及时连接的服务器会在此列出其 mcp__ 工具,较慢的继续在后台连接:

export MCP_CONNECTION_NONBLOCKING=0

设置该变量后,以下过滤器可打印 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 服务器

stdio 服务器

通过 stdin/stdout 通信的本地进程。 用于在同一台机器上运行的 MCP 服务器:

在代码中:

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"],
)

.mcp.json 配置文件:

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

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 服务器

直接在应用代码中定义自定义工具, 而不是运行单独的服务器进程。实现细节见自定义工具指南

通过 initialize 控制请求注册的 SDK MCP 服务器,在 Claude Code 处理该请求时即开始连接。

MCP 工具搜索

当配置了大量 MCP 工具时,工具定义可能占据上下文窗口的很大部分。 工具搜索通过从上下文中隐藏工具定义来解决此问题,仅加载 Claude 每个回合需要的工具。

工具搜索默认启用。配置选项、最佳实践以及与自定义 SDK 工具配合使用工具搜索,见工具搜索指南

认证

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

通过环境变量传递凭证

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

在代码中:

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} 语法在运行时展开环境变量。

完整的带认证 headers 的远程服务器示例见从仓库列出 Issues

远程服务器的 HTTP Headers

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

在代码中:

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} 语法在运行时展开环境变量。

OAuth2 认证

MCP 规范支持 OAuth 2.1 用于授权。 SDK 不会打开浏览器或运行交互式 OAuth 流程。当配置的服务器返回授权质询且没有存储的令牌时,Agent 运行会继续(不使用该服务器的工具),服务器报告 needs-auth 状态。由于服务器默认在后台连接,system init 消息mcp_servers 数组可能仍然为该服务器显示 pending。要确认服务器是否需要凭证,可在 TypeScript SDK 中轮询 mcpServerStatus(),或在 Python 中调用 get_mcp_status(),或设置 MCP_CONNECTION_NONBLOCKING=0 以在 init 消息前等待连接。

要提供凭证,在你自己的应用中完成 OAuth 流程,然后通过服务器的 headers 传递得到的 access token:

// 在应用中完成 OAuth 流程后
// 为你的 OAuth 提供者实现 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 提供者实现 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__*"],
)

示例

从仓库列出 Issues

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

运行前,创建具有仓库读取权限的 GitHub 个人访问令牌 并设置为环境变量:

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 拒绝 INSERTUPDATEDELETE 和 DDL 语句,确保示例即使 Agent 生成写入操作也不会修改你的数据。DBHub 在加载配置时从进程环境解析 ${DATABASE_URL},因此连接字符串不会出现在文件中。在脚本旁创建此 dbhub.toml

# dbhub.toml
[[sources]]
id = "production"
dsn = "${DATABASE_URL}"

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

脚本将 DBHub 指向该配置文件,而不是直接传递连接字符串。运行前设置 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({
  // 自然语言查询 - Claude 编写 SQL
  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"],
    )

    # 自然语言查询 - Claude 编写 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 在每次查询开始时发出一个 subtype 为 initsystem 消息。此消息包含每个 MCP 服务器的连接状态。status 字段可以是 "pending""connected""failed""needs-auth""disabled"。由于连接默认是非阻塞的,健康的服务器在 init 消息发出时通常仍报告 "pending"。检查 "failed""needs-auth" 来检测不可用的服务器,不要将 "pending" 视为失败:

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

try {
  for await (const message of query({
    prompt: "Process data",
    options: {
      mcpServers: {
        // 替换为你的服务器配置
        "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 进程不会生成结果消息。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():
    # 替换为你的服务器配置
    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 进程不会生成结果消息。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" 状态表示服务器仍在连接,并非失败。要在会话中获取更新后的状态,在 TypeScript SDK 中调用 query 的 mcpServerStatus() 方法,或在 Python 中调用 ClaudeSDKClient.get_mcp_status()

常见原因:

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

工具未被调用

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

const options = {
  mcpServers: {
    // 你的服务器
  },
  allowedTools: ["mcp__servername__*"] // 自动批准来自此服务器的调用
};
options = ClaudeAgentOptions(
    mcp_servers={
        # your servers
    },
    allowed_tools=["mcp__servername__*"],  # Auto-approve calls from this server
)

连接超时

MCP 服务器连接默认 30 秒后超时。 如果你的服务器启动需要更长时间,连接会失败。使用 MCP_TIMEOUT 环境变量提高限制(单位毫秒)。对于需要更多启动时间的服务器,也可考虑:

  • 使用更轻量的服务器(如果可用)
  • 在启动 Agent 之前预热服务器
  • 检查服务器日志以找出启动缓慢的原因

工具输出超过最大允许 token 数

SDK 对 MCP 输出应用与 Claude Code 相同的限制。 当工具结果超过 25,000 token 时,完整输出会保存到文件,工具结果会被替换为一条包含文件路径的错误消息,以便 Agent 分段读取输出。可通过 MAX_MCP_OUTPUT_TOKENS 环境变量提高限制。完整行为(包括服务器如何声明更高的每工具限制)见 MCP 输出限制与警告

相关资源