概要

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: "List files in my project",
  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: "What resources are available from the database server?",
  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: "Process data",
  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("Failed to connect:", failedServers);
    }
  }
  
  if (message.type === "result" && message.subtype === "error_during_execution") {
    console.error("Execution failed");
  }
}

関連リソース