spinny:~/writing $ less mcp-model-context-protocol-guide.md
12**Model Context Protocol(MCP)** 是由 Anthropic 创建的开放标准,定义了 AI 模型如何与外部工具、数据源和服务进行通信。可以把它想象成"AI 的 USB-C" - - 一个通用连接器,让任何 AI 代理都能通过标准化接口与任何工具进行通信。34自发布以来,MCP 的 **SDK 月下载量已超过 9700 万次**,并已被所有主要 AI 提供商采用:Anthropic、OpenAI、Google、Microsoft 和 Amazon。在本指南中,我们将探索使用 MCP 构建所需的一切知识。56## 为什么 MCP 存在78在 MCP 之前,每个 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 有三个基本原语: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 服务器110111让我们构建一个实用的 MCP 服务器,它与存储在 JSON 文件中的待办事项列表进行交互。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. **保持服务器专注**:每个领域一个服务器(GitHub 服务器、Slack 服务器等)。不要构建单体服务器。2812. **使用 Zod 验证输入**:始终使用正确的 schema 验证工具输入。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