Model Context Protocol (MCP) 是一個開放標準,用於將 AI 代理連接到外部工具和資料來源。透過 MCP,您的代理可以查詢資料庫、整合 Slack 和 GitHub 等 API,以及連接到其他服務,而無需編寫自訂工具實作。
MCP 伺服器可以作為本地程序運行、透過 HTTP 連接,或直接在您的 SDK 應用程式中執行。
此範例使用 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 的資訊,並返回結果。
您可以在呼叫 query() 時在程式碼中配置 MCP 伺服器,或在 SDK 自動載入的 .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 檔案。SDK 會自動載入此檔案:
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/me/projects"]
}
}
}MCP 工具需要明確的權限才能讓 Claude 使用。如果沒有權限,Claude 會看到工具可用但無法呼叫它們。
MCP 工具遵循 mcp__<server-name>__<tool-name> 的命名模式。例如,名為 "github" 的 GitHub 伺服器中的 list_issues 工具會變成 mcp__github__list_issues。
使用 allowedTools 指定 Claude 可以使用哪些 MCP 工具:
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
]
}萬用字元(*)讓您可以允許伺服器的所有工具,而無需逐一列出。
除了列出允許的工具外,您還可以變更權限模式以授予更廣泛的存取權限:
permissionMode: "acceptEdits":自動批准工具使用(對於破壞性操作仍會提示)permissionMode: "bypassPermissions":跳過所有安全提示,包括檔案刪除或執行 shell 命令等破壞性操作。請謹慎使用,尤其是在生產環境中。此模式會傳播到 Task 工具產生的子代理。options: {
mcpServers: { /* your servers */ },
permissionMode: "acceptEdits" // No need for allowedTools
}請參閱權限以了解更多關於權限模式的詳細資訊。
要查看 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透過 stdin/stdout 通訊的本地程序。用於在同一台機器上運行的 MCP 伺服器:
對於雲端託管的 MCP 伺服器和遠端 API,請使用 HTTP 或 SSE:
對於 HTTP(非串流),請改用 "type": "http"。
直接在您的應用程式碼中定義自訂工具,而不是運行單獨的伺服器程序。請參閱自訂工具指南以了解實作詳情。
當您配置了許多 MCP 工具時,工具定義可能會佔用上下文視窗的很大一部分。MCP 工具搜尋透過按需動態載入工具而不是預先載入所有工具來解決此問題。
工具搜尋預設以自動模式運行。當您的 MCP 工具描述會佔用超過上下文視窗 10% 時,它會啟動。觸發時:
defer_loading: true,而不是預先載入到上下文中工具搜尋需要支援 tool_reference 區塊的模型:Sonnet 4 及更新版本,或 Opus 4 及更新版本。Haiku 模型不支援工具搜尋。
使用 ENABLE_TOOL_SEARCH 環境變數控制工具搜尋行為:
| 值 | 行為 |
|---|---|
auto | 當 MCP 工具超過上下文的 10% 時啟動(預設) |
auto:5 | 在 5% 閾值時啟動(自訂百分比) |
true | 始終啟用 |
false | 停用,所有 MCP 工具預先載入 |
在 env 選項中設定值:
const options = {
mcpServers: { /* your MCP servers */ },
env: {
ENABLE_TOOL_SEARCH: "auto:5" // Enable at 5% threshold
}
};大多數 MCP 伺服器需要身份驗證才能存取外部服務。透過伺服器配置中的環境變數傳遞憑證。
使用 env 欄位將 API 金鑰、權杖和其他憑證傳遞給 MCP 伺服器:
請參閱列出儲存庫的 issues 以獲取包含除錯日誌的完整工作範例。
對於 HTTP 和 SSE 伺服器,直接在伺服器配置中傳遞身份驗證標頭:
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 伺服器以列出最近的 issues。此範例包含除錯日誌以驗證 MCP 連線和工具呼叫。
在執行之前,請建立一個具有 repo 範圍的 GitHub 個人存取權杖,並將其設定為環境變數:
export GITHUB_TOKEN=ghp_xxxxxxxxxxxxxxxxxxxximport { 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.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 在每次查詢開始時會發出一個子類型為 init 的 system 訊息。此訊息包含每個 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`);
}
}
}常見原因:
env 欄位是否與伺服器預期的相符。npx 命令,請驗證套件是否存在以及 Node.js 是否在您的 PATH 中。如果 Claude 看到工具但不使用它們,請檢查您是否已透過 allowedTools 或變更權限模式授予權限:
options: {
mcpServers: { /* your servers */ },
allowedTools: ["mcp__servername__*"] // Required for Claude to use the tools
}MCP SDK 的伺服器連線預設逾時為 60 秒。如果您的伺服器啟動時間更長,連線將會失敗。對於需要更多啟動時間的伺服器,請考慮:
allowedTools 和 disallowedTools 控制您的代理可以使用哪些 MCP 工具Was this page helpful?