概述

Model Context Protocol (MCP) 伺服器透過自訂工具和功能擴展 Claude Code。MCP 可以作為外部程序運行、透過 HTTP/SSE 連接,或直接在您的 SDK 應用程式中執行。

配置

基本配置

在專案根目錄的 .mcp.json 中配置 MCP 伺服器:
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["@modelcontextprotocol/server-filesystem"],
      "env": {
        "ALLOWED_PATHS": "/Users/me/projects"
      }
    }
  }
}

在 SDK 中使用 MCP 伺服器

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

for await (const message of query({
  prompt: "列出我專案中的檔案",
  options: {
    mcpConfig: ".mcp.json",
    allowedTools: ["mcp__filesystem__list_files"]
  }
})) {
  if (message.type === "result" && message.subtype === "success") {
    console.log(message.result);
  }
}

傳輸類型

stdio 伺服器

透過 stdin/stdout 通訊的外部程序:
// .mcp.json 配置
{
  "mcpServers": {
    "my-tool": {
      "command": "node",
      "args": ["./my-mcp-server.js"],
      "env": {
        "DEBUG": "${DEBUG:-false}"
      }
    }
  }
}

HTTP/SSE 伺服器

具有網路通訊的遠端伺服器:
// SSE 伺服器配置
{
  "mcpServers": {
    "remote-api": {
      "type": "sse",
      "url": "https://api.example.com/mcp/sse",
      "headers": {
        "Authorization": "Bearer ${API_TOKEN}"
      }
    }
  }
}

// HTTP 伺服器配置
{
  "mcpServers": {
    "http-service": {
      "type": "http",
      "url": "https://api.example.com/mcp",
      "headers": {
        "X-API-Key": "${API_KEY}"
      }
    }
  }
}

SDK MCP 伺服器

在您的應用程式內運行的程序內伺服器。有關建立自訂工具的詳細資訊,請參閱自訂工具指南

資源管理

MCP 伺服器可以公開 Claude 可以列出和讀取的資源:
import { query } from "@anthropic-ai/claude-code";

// 列出可用資源
for await (const message of query({
  prompt: "資料庫伺服器有哪些可用資源?",
  options: {
    mcpConfig: ".mcp.json",
    allowedTools: ["mcp__list_resources", "mcp__read_resource"]
  }
})) {
  if (message.type === "result") console.log(message.result);
}

身份驗證

環境變數

// 帶有環境變數的 .mcp.json
{
  "mcpServers": {
    "secure-api": {
      "type": "sse",
      "url": "https://api.example.com/mcp",
      "headers": {
        "Authorization": "Bearer ${API_TOKEN}",
        "X-API-Key": "${API_KEY:-default-key}"
      }
    }
  }
}

// 設定環境變數
process.env.API_TOKEN = "your-token";
process.env.API_KEY = "your-key";

OAuth2 身份驗證

目前不支援客戶端內的 OAuth2 MCP 身份驗證。

錯誤處理

優雅地處理 MCP 連接失敗:
import { query } from "@anthropic-ai/claude-code";

for await (const message of query({
  prompt: "處理資料",
  options: {
    mcpServers: {
      "data-processor": dataServer
    }
  }
})) {
  if (message.type === "system" && message.subtype === "init") {
    // 檢查 MCP 伺服器狀態
    const failedServers = message.mcp_servers.filter(
      s => s.status !== "connected"
    );
    
    if (failedServers.length > 0) {
      console.warn("連接失敗:", failedServers);
    }
  }
  
  if (message.type === "result" && message.subtype === "error_during_execution") {
    console.error("執行失敗");
  }
}

相關資源