spinny:~/writing $ less mcp-model-context-protocol-guide.md
12**Model Context Protocol(MCP)** は、Anthropic が作成したオープンスタンダードで、AI モデルが外部ツール、データソース、サービスとどのように通信するかを定義します。これを「AI の USB-C」と考えてください - 標準化されたインターフェースを通じて、任意の AI エージェントが任意のツールと通信できるユニバーサルコネクタです。34ローンチ以来、MCP は **月間9,700万回以上の SDK ダウンロード** を達成し、すべての主要 AI プロバイダーに採用されています:Anthropic、OpenAI、Google、Microsoft、Amazon。このガイドでは、MCP を使って構築するために知っておくべきすべてを探ります。56## MCP が存在する理由78MCP 以前は、すべての AI アプリケーションが使用したい各ツールに対してカスタム統合を構築する必要がありました。AI にファイルを読ませたい?カスタムコードを書く。データベースをクエリする?さらにカスタムコード。Slack に投稿する?また別の統合。910これにより **N×M 問題** が発生しました:N 個の AI アプリケーションがそれぞれ M 個のカスタム統合を必要とし、作業の重複と断片化したエコシステムにつながりました。1112```mermaid13graph TD14 subgraph "Before MCP (N×M)"15 A1[AI App 1] --> T1[GitHub Integration]16 A1 --> T2[Slack Integration]17 A1 --> T3[DB Integration]18 A2[AI App 2] --> T4[GitHub Integration]19 A2 --> T5[Slack Integration]20 A2 --> T6[DB Integration]21 end22```2324MCP はこれを、任意の AI クライアントが任意の MCP サーバーと通信するために使用できる**単一のプロトコル**で解決します:2526```mermaid27graph TD28 subgraph "With MCP (N+M)"29 A1[AI App 1] --> MCP[MCP Protocol]30 A2[AI App 2] --> MCP31 MCP --> S1[GitHub Server]32 MCP --> S2[Slack Server]33 MCP --> S3[DB Server]34 end35```3637## 基本概念3839MCP には3つの基本的なプリミティブがあります:4041### 1. ツール(Tools)42ツールは AI が呼び出せる関数です。「ファイルを作成する」「データベースをクエリする」「メッセージを送信する」などのアクションを表します。各ツールには名前、説明、パラメータの JSON Schema があります。4344```typescript45{46 name: "create_issue",47 description: "Create a new GitHub issue",48 inputSchema: {49 type: "object",50 properties: {51 title: { type: "string", description: "Issue title" },52 body: { type: "string", description: "Issue body" },53 repo: { type: "string", description: "Repository name" }54 },55 required: ["title", "repo"]56 }57}58```5960### 2. リソース(Resources)61リソースは AI が読み取れるデータです。ファイル、データベースレコード、API レスポンス、その他のデータソースを表します。リソースは URI で識別されます。6263```typescript64{65 uri: "file:///Users/dev/project/README.md",66 name: "Project README",67 mimeType: "text/markdown"68}69```7071### 3. プロンプト(Prompts)72プロンプトはインタラクションの構造化を助ける再利用可能なテンプレートです。動的パラメータを含めることができ、一般的なワークフローの標準化に役立ちます。7374```typescript75{76 name: "code_review",77 description: "Review code changes for quality and security",78 arguments: [79 { name: "diff", description: "The code diff to review", required: true }80 ]81}82```8384## アーキテクチャ8586MCP はクライアント-サーバーアーキテクチャに従います:8788```mermaid89graph LR90 subgraph "Host Application"91 Client[MCP Client]92 end9394 subgraph "MCP Server"95 Server[Server Process]96 Server --> Tools[Tools]97 Server --> Resources[Resources]98 Server --> Prompts[Prompts]99 end100101 Client -- "JSON-RPC 2.0\n(stdio or SSE)" --> Server102```103104- **ホスト**:AI アプリケーション(Claude Desktop、Cursor、カスタムアプリ)105- **クライアント**:MCP サーバーとの 1:1 接続を維持106- **サーバー**:ツール、リソース、プロンプトをクライアントに公開107- **トランスポート**:stdio(ローカル)または Server-Sent Events(リモート)上の JSON-RPC 2.0 で通信108109## MCP サーバーの構築110111JSON ファイルに保存されたタスクリストとやり取りする実用的な MCP サーバーを構築しましょう。112113### セットアップ114115```bash116mkdir mcp-todo-server && cd mcp-todo-server117npm init -y118npm install @modelcontextprotocol/sdk zod119```120121### サーバーの実装122123```typescript124// src/index.ts125import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";126import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";127import { z } from "zod";128import fs from "fs";129130const TODO_FILE = "./todos.json";131132function readTodos(): { id: number; text: string; done: boolean }[] {133 if (!fs.existsSync(TODO_FILE)) return [];134 return JSON.parse(fs.readFileSync(TODO_FILE, "utf-8"));135}136137function writeTodos(todos: { id: number; text: string; done: boolean }[]) {138 fs.writeFileSync(TODO_FILE, JSON.stringify(todos, null, 2));139}140141const server = new McpServer({142 name: "todo-server",143 version: "1.0.0",144});145146// Tool: Add a todo147server.tool(148 "add_todo",149 "Add a new todo item",150 { text: z.string().describe("The todo text") },151 async ({ text }) => {152 const todos = readTodos();153 const newTodo = { id: Date.now(), text, done: false };154 todos.push(newTodo);155 writeTodos(todos);156 return { content: [{ type: "text", text: `Added: "${text}"` }] };157 }158);159160// Tool: List todos161server.tool(162 "list_todos",163 "List all todo items",164 {},165 async () => {166 const todos = readTodos();167 const list = todos168 .map((t) => `${t.done ? "✅" : "⬜"} [${t.id}] ${t.text}`)169 .join("\n");170 return { content: [{ type: "text", text: list || "No todos yet." }] };171 }172);173174// Tool: Complete a todo175server.tool(176 "complete_todo",177 "Mark a todo as completed",178 { id: z.number().describe("The todo ID to complete") },179 async ({ id }) => {180 const todos = readTodos();181 const todo = todos.find((t) => t.id === id);182 if (!todo) return { content: [{ type: "text", text: "Todo not found." }] };183 todo.done = true;184 writeTodos(todos);185 return { content: [{ type: "text", text: `Completed: "${todo.text}"` }] };186 }187);188189// Resource: Current todos as a readable resource190server.resource(191 "todos://list",192 "Current todo list",193 async () => ({194 contents: [{195 uri: "todos://list",196 mimeType: "application/json",197 text: JSON.stringify(readTodos(), null, 2),198 }],199 })200);201202// Start the server203const transport = new StdioServerTransport();204await server.connect(transport);205```206207### 設定208209このサーバーを Claude Desktop で使用するには、設定に追加してください:210211```json212{213 "mcpServers": {214 "todo": {215 "command": "npx",216 "args": ["tsx", "/path/to/mcp-todo-server/src/index.ts"]217 }218 }219}220```221222## MCP クライアントの構築223224任意の MCP サーバーに接続するカスタムクライアントも構築できます:225226```typescript227import { Client } from "@modelcontextprotocol/sdk/client/index.js";228import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";229230const transport = new StdioClientTransport({231 command: "npx",232 args: ["tsx", "./src/index.ts"],233});234235const client = new Client({ name: "my-client", version: "1.0.0" });236await client.connect(transport);237238// List available tools239const { tools } = await client.listTools();240console.log("Available tools:", tools.map((t) => t.name));241242// Call a tool243const result = await client.callTool({244 name: "add_todo",245 arguments: { text: "Write MCP blog post" },246});247console.log(result);248```249250## 人気の MCP サーバー251252MCP エコシステムは急速に成長しています。最も人気のあるサーバーの一部を紹介します:253254| サーバー | 説明 | ユースケース |255|----------|------|-------------|256| **GitHub** | Issue、PR の作成、リポジトリの管理 | 開発ワークフロー |257| **Slack** | メッセージの送信、チャンネルの管理 | チームコミュニケーション |258| **PostgreSQL** | データベースのクエリと管理 | データアクセス |259| **Filesystem** | ファイルの読み取り、書き込み、検索 | ローカル開発 |260| **Puppeteer** | ブラウザの自動化とスクレイピング | Web テスト |261| **Sentry** | エラー監視とデバッグ | 本番サポート |262| **Supabase** | データベース、認証、ストレージ | バックエンド操作 |263264## MCP vs A2A(Agent-to-Agent)265266MCP が**エージェント-ツール**間の通信を処理するのに対し、Google の **A2A(Agent-to-Agent)** プロトコルは**エージェント-エージェント**間の通信を処理します。これらは相補的です:267268```mermaid269graph TD270 Agent1[Agent 1] -- "A2A Protocol" --> Agent2[Agent 2]271 Agent1 -- "MCP Protocol" --> Tool1[GitHub MCP Server]272 Agent2 -- "MCP Protocol" --> Tool2[Database MCP Server]273```274275- **MCP**:AI エージェントがツールを使用する方法(垂直統合)276- **A2A**:AI エージェント同士が協力する方法(水平統合)277278## ベストプラクティス2792801. **サーバーを焦点を絞る**:ドメインごとに1つのサーバー(GitHub サーバー、Slack サーバーなど)。モノリシックなサーバーを構築しないでください。2812. **Zod で入力を検証する**:常に適切なスキーマでツールの入力を検証してください。2823. **エラーを適切に処理する**:スタックトレースではなく、意味のあるエラーメッセージを返してください。2834. **読み取り専用データにはリソースを使用する**:AI がデータの読み取りのみが必要な場合は、ツールではなくリソースとして公開してください。2845. **適切な説明を追加する**:ツールとパラメータの良い説明は、AI が各ツールをいつ、どのように使用するかを理解するのに役立ちます。2856. **MCP Inspector でテストする**:`npx @modelcontextprotocol/inspector` を使用してサーバーを対話的にテストしてください。286287## はじめに288289```bash290# Create a new MCP server from template291npx @modelcontextprotocol/create-server my-server292293# Test with the MCP Inspector294npx @modelcontextprotocol/inspector npx tsx ./src/index.ts295```296297## まとめ298299MCP は 2026 年に AI ツール利用のデファクトスタンダードとなりました。カスタム AI エージェントの構築、Claude Code の拡張、既存プラットフォームへの統合の作成のいずれであっても、MCP を理解することは不可欠です。このプロトコルは午後の数時間で学べるほどシンプルですが、本番レベルの AI ワークフローを構築するのに十分な強力さを持っています。300301**次のステップ:**302- [MCP 仕様](https://spec.modelcontextprotocol.io/)を探索する303- [既存の MCP サーバー](https://github.com/modelcontextprotocol/servers)をブラウズしてインスピレーションを得る304- TypeScript または Python SDK で最初のサーバーを構築する305- Claude Desktop または MCP Inspector でテストする306
:MCP(Model Context Protocol):開発者のための完全ガイドlines 1-306 (END) — press q to close