跳转到主要内容
Model Context Protocol (MCP) 是一个开放标准,用于将 AI 代理连接到外部工具和数据源。使用 MCP,您的代理可以查询数据库、与 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);
  }
}
代理连接到文档服务器,搜索有关 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);
  }
}

从配置文件

在项目根目录创建一个 .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
    ]
  }
};
通配符 (*) 让您允许来自服务器的所有工具,而无需逐个列出每一个。
对于 MCP 访问,优先使用 allowedTools 而不是权限模式。 permissionMode: "acceptEdits" 不会自动批准 MCP 工具(仅文件编辑和文件系统 Bash 命令)。permissionMode: "bypassPermissions" 确实会自动批准 MCP 工具,但也会禁用所有其他安全提示,这比必要的范围更广。allowedTools 中的通配符仅授予您想要的 MCP 服务器,没有其他。请参阅 权限模式 以获得完整比较。

发现可用工具

要查看 MCP 服务器提供的工具,请检查服务器的文档或连接到服务器并检查 system init 消息:
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"]
  }
};

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__*"]
  }
};
对于可流式传输的 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"]
  }
};
有关带有调试日志的完整工作示例,请参阅 从存储库列出问题

远程服务器的 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__*"]
  }
};

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__*"]
};

示例

从存储库列出问题

此示例连接到 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);
  }
}

查询数据库

此示例使用 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);
  }
}

错误处理

MCP 服务器可能因各种原因连接失败:服务器进程可能未安装、凭据可能无效,或远程服务器可能无法访问。 SDK 在每个查询开始时发出一个 system 消息,子类型为 init。此消息包括每个 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");
  }
}

故障排除

服务器显示”失败”状态

检查 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__*"] // 自动批准来自此服务器的调用
  }
};

连接超时

MCP SDK 对服务器连接的默认超时为 60 秒。如果您的服务器需要更长时间才能启动,连接将失败。对于需要更多启动时间的服务器,请考虑:
  • 使用更轻量级的服务器(如果可用)
  • 在启动代理之前预热服务器
  • 检查服务器日志以了解缓慢初始化的原因

相关资源

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