CheatSheet
日本語 icon日本語English iconEnglish
チートシートとはカンニングペーパーのことです。それが転じて、本来覚えることをまとめておいたものです。
要点をすぐに参照できるようにまとめてみました。

MCP (Model Context Protocol)

エンジニアのためのWebチートシート

MCP(Model Context Protocol)は、AIアプリケーションと外部システムを接続するためのオープンスタンダードプロトコルです。 アーキテクチャ、プリミティブ(Tools/Resources/Prompts)、TypeScript/Python SDK、クライアント設定、JSON-RPC通信などをチートシートにまとめました。

アーキテクチャ

コンポーネント構成

コンポーネント役割
MCP HostAIアプリケーション(Claude Desktop、VS Code等)。クライアントを内包し、ユーザーとAIのインターフェースを提供します。
MCP Clientホスト内のコンポーネント。MCPサーバーとの1:1接続を管理し、プロトコルメッセージを仲介します。
MCP Server外部システムへのアクセスを提供。Tools、Resources、Promptsを公開し、クライアントからのリクエストに応答します。

レイヤー構成

  • MCPは2層構成です。

    ┌─────────────────────────────┐
    │        MCP Host             │
    │  (Claude Desktop, VS Code)  │
    │                             │
    │  ┌──────────┐ ┌──────────┐  │
    │  │ Client 1 │ │ Client 2 │  │
    │  └────┬─────┘ └────┬─────┘  │
    └───────┼────────────┼────────┘
            │            │
       ┌────┴────┐  ┌────┴────┐
       │ Server  │  │ Server  │
       │ (Local) │  │(Remote) │
       └─────────┘  └─────────┘
    
    Data Layer:
      - Lifecycle (init, capability negotiation)
      - Server: Tools, Resources, Prompts
      - Client: Sampling, Elicitation
    
    Transport Layer:
      - Stdio (local)
      - Streamable HTTP (remote)

プロトコルプリミティブ

サーバー側プリミティブ

プリミティブ説明用途
ToolsLLMが呼び出す実行可能な関数。JSON Schemaで入力を定義。API呼び出し、DB操作、ファイル操作、計算
Resources読み取り専用データ。URIパターンでRESTful風アクセス。ファイル内容、DBレコード、APIレスポンス、スキーマ
Prompts再利用可能なテンプレート。ユーザーが明示的に選択。システムプロンプト、Few-shot例、推奨フォーマット

クライアント側プリミティブ

プリミティブ説明用途
SamplingサーバーからLLM補完をリクエスト。AI生成コンテンツの取得、要約、分析
Elicitationユーザーに追加情報を対話的にリクエスト。パラメータ確認、承認フロー、入力収集

トランスポート

トランスポート比較

トランスポート特徴説明
Stdioローカル実行、子プロセス、最高パフォーマンスstdin/stdoutでJSON-RPCメッセージを交換。ローカルサーバーに最適。
Streamable HTTPリモート対応、認証サポート、複数クライアントHTTP POSTでリクエスト、SSEでストリーミング応答。リモートサーバーに推奨。
SSEレガシー(非推奨)旧式の2エンドポイント方式。新規実装ではStreamable HTTPを使用してください。

サーバー実装(TypeScript)

FastMCP(推奨)

  • FastMCPフレームワークを使ったTypeScript実装です。

    import { FastMCP } from "fastmcp";
    import { z } from "zod";
    
    const server = new FastMCP({
      name: "My MCP Server",
      version: "1.0.0",
    });
    // Tool definition
    server.addTool({
      name: "calculate",
      description: "Perform a calculation",
      parameters: z.object({ expression: z.string() }),
      execute: async (args) => String(eval(args.expression)),
    });
    // Resource definition
    server.addResource({
      uri: "config://app",
      name: "App Configuration",
      mimeType: "application/json",
      async load() {
        return { text: JSON.stringify({ debug: true }) };
      },
    });
    // Prompt definition
    server.addPrompt({
      name: "code-review",
      description: "Code review prompt",
      arguments: [{ name: "code", required: true }],
      load: async (args) =>
        `Review the following code:\n${args.code}`,
    });
    
    server.start({ transportType: "stdio" });

公式SDK(低レベル)

  • @modelcontextprotocol/sdk を使った低レベル実装です。

    import { McpServer } from
      "@modelcontextprotocol/sdk/server/mcp.js";
    import { StdioServerTransport } from
      "@modelcontextprotocol/sdk/server/stdio.js";
    
    const server = new McpServer({
      name: "My Server", version: "1.0.0",
    });
    // Tool
    server.tool("get-weather", "Get weather",
      { city: { type: "string" } },
      async ({ city }) => ({
        content: [{ type: "text",
          text: `Weather in ${city}: Sunny` }],
      })
    );
    // Resource
    server.resource("docs", "docs://readme",
      async (uri) => ({
        contents: [{ uri: uri.href,
          text: "# Docs", mimeType: "text/markdown" }],
      })
    );
    
    const transport = new StdioServerTransport();
    await server.connect(transport);

サーバー実装(Python)

FastMCP(推奨)

  • デコレーターベースのPython実装です。

    from fastmcp import FastMCP
    
    mcp = FastMCP("My MCP Server")
    
    @mcp.tool()
    def calculate(expression: str) -> str:
        """Evaluate a math expression"""
        return str(eval(expression))
    
    @mcp.tool()
    def search_database(
        query: str,
        limit: int = 10
    ) -> list[dict]:
        """Search the database"""
        # DB query logic here
        return [{"id": 1, "name": "Result"}]
    
    @mcp.resource("config://app")
    def get_config() -> str:
        """Get application configuration"""
        return '{"debug": true, "version": "1.0"}'
    
    @mcp.prompt()
    def code_review(code: str) -> str:
        """Generate a code review prompt"""
        return f"Review this code:\n{code}"
    
    if __name__ == "__main__":
        mcp.run()  # Default: stdio transport

公式SDK(低レベル)

  • mcp パッケージを使った低レベル実装です。

    from mcp.server import Server
    from mcp.server.stdio import stdio_server
    import mcp.types as types
    
    server = Server("my-server")
    @server.list_tools()
    async def list_tools():
        return [types.Tool(
            name="get-weather",
            description="Get weather",
            inputSchema={"type": "object",
              "properties": {"city": {"type": "string"}},
              "required": ["city"]},
        )]
    @server.call_tool()
    async def call_tool(name: str, arguments: dict):
        if name == "get-weather":
            return [types.TextContent(
                type="text",
                text=f"Weather: Sunny in {arguments['city']}"
            )]
    async def main():
        async with stdio_server() as (r, w):
            await server.run(r, w,
                server.create_initialization_options())
    
    import asyncio
    asyncio.run(main())

クライアント設定

設定ファイルのパス

  • MCPクライアントの設定ファイルの場所です。

    # macOS (Claude Desktop)
    ~/Library/Application Support/Claude/claude_desktop_config.json
    
    # Windows (Claude Desktop)
    %APPDATA%\Claude\claude_desktop_config.json
    
    # Claude Code
    .claude/settings.json  # or ~/.claude/settings.json

Stdio サーバー設定

  • ローカルで実行するサーバーの設定例です。

    {
      "mcpServers": {
        "filesystem": {
          "command": "npx",
          "args": [
            "-y",
            "@modelcontextprotocol/server-filesystem",
            "/Users/me/projects"
          ]
        },
        "github": {
          "command": "npx",
          "args": ["-y", "@modelcontextprotocol/server-github"],
          "env": {
            "GITHUB_TOKEN": "${GITHUB_TOKEN}"
          }
        },
        "python-server": {
          "command": "python",
          "args": ["-m", "my_mcp_server"],
          "env": {
            "API_KEY": "${API_KEY}"
          }
        }
      }
    }

HTTP リモートサーバー設定

  • リモートで実行するサーバーの設定例です。

    {
      "mcpServers": {
        "remote-api": {
          "type": "http",
          "url": "https://api.example.com/mcp",
          "headers": {
            "Authorization": "Bearer ${API_KEY}"
          }
        }
      }
    }

ライフサイクル & JSON-RPC

初期化シーケンス

  • 1. Client → Server: Initialize Request

    {
      "jsonrpc": "2.0", "id": 1,
      "method": "initialize",
      "params": {
        "protocolVersion": "2025-03-26",
        "capabilities": { "sampling": {} },
        "clientInfo": { "name": "Claude Desktop", "version": "1.0.0" }
      }
    }
  • 2. Server → Client: Initialize Response

    {
      "jsonrpc": "2.0", "id": 1,
      "result": {
        "protocolVersion": "2025-03-26",
        "capabilities": { "tools": { "listChanged": true } },
        "serverInfo": { "name": "My Server", "version": "1.0.0" }
      }
    }
  • 3. Client → Server: Initialized Notification

    { "jsonrpc": "2.0", "method": "notifications/initialized" }

JSON-RPC メッセージ形式

  • Request

    {
      "jsonrpc": "2.0", "id": "req-1",
      "method": "tools/call",
      "params": { "name": "calculate",
        "arguments": { "expression": "2 + 2" } }
    }
  • Success Response

    {
      "jsonrpc": "2.0", "id": "req-1",
      "result": {
        "content": [{ "type": "text", "text": "4" }]
      }
    }
  • Error Response / Notification

    // Error
    { "jsonrpc": "2.0", "id": "req-1",
      "error": { "code": -32600, "message": "Invalid Request" } }
    
    // Notification (no id, no response)
    { "jsonrpc": "2.0",
      "method": "notifications/tools/list_changed" }

セキュリティ & デバッグ

セキュリティベストプラクティス

プラクティス
APIキー・トークンは環境変数に格納する(JSONに平文記載しない)
信頼できるソースからのみサーバーを使用する
ファイルシステムアクセスはディレクトリ制限を設定する
ツール実行時はユーザー承認を要求する
機密設定には sensitive: true を使用する
ログにパスワード・トークン・機密データを絶対に含めない

デバッグツール

プラクティス
MCP Inspector(http://localhost:5173)でサーバーを対話的にテスト
デバッグログはstderrに出力(stdoutはJSON-RPCメッセージ用)
リクエストID、エラー型、パフォーマンス指標を構造化ログで記録

エラーコード

コード意味
-32700Parse Error
-32600不正なリクエスト
-32601メソッドが見つからない
-32602不正なパラメータ
-32000サーバーエラー
-32001リクエストタイムアウト