MCP协议
MCP 协议:连接外部服务
·约 8 分钟阅读
Model Context Protocol(MCP)是 Anthropic 推出的开放标准,让 AI 模型能够连接任何外部服务。可以把它理解为 AI 世界的 USB 接口——一个标准协议连接所有工具。
你将学到什么
- MCP 的架构设计和核心概念
- 开发一个 MCP Server
- 在 Claude Code / Claude Desktop 中使用 MCP
- MCP 的三大能力:Tools、Resources、Prompts
MCP 架构
MCP 采用 Client-Server 架构:
┌──────────────┐ stdio/SSE ┌──────────────┐
│ MCP Client │ ◄───────────────► │ MCP Server │
│ (Claude Code │ │ (你开发的) │
│ / Desktop) │ │ │
└──────────────┘ └──────────────┘
│
┌──────┴──────┐
│ 外部服务 │
│ (数据库/API) │
└─────────────┘
传输方式:
- stdio:进程间通信,适合本地使用(Claude Code 默认)
- SSE(Server-Sent Events):HTTP 长连接,适合远程服务
MCP 三大能力
| 能力 | 说明 | 示例 |
|---|---|---|
| Tools | 可执行的函数 | 查询数据库、发送邮件 |
| Resources | 可读取的数据源 | 文件列表、配置信息 |
| Prompts | 预定义的 prompt 模板 | 代码审查模板、翻译模板 |
开发一个 MCP Server
以一个"待办事项管理"MCP Server 为例:
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
const server = new McpServer({
name: "todo-server",
version: "1.0.0",
});
// 内存中的 todo 列表
const todos: { id: number; text: string; done: boolean }[] = [];
let nextId = 1;
// Tool: 添加待办
server.tool(
"add_todo",
"添加一个新的待办事项",
{ text: z.string().describe("待办事项内容") },
async ({ text }) => {
const todo = { id: nextId++, text, done: false };
todos.push(todo);
return { content: [{ type: "text", text: "已添加: " + text }] };
}
);
// Tool: 列出待办
server.tool(
"list_todos",
"列出所有待办事项",
{},
async () => {
if (todos.length === 0) {
return { content: [{ type: "text", text: "没有待办事项" }] };
}
const list = todos.map(t =>
(t.done ? "[x]" : "[ ]") + " #" + t.id + " " + t.text
).join("\n");
return { content: [{ type: "text", text: list }] };
}
);
// Tool: 完成待办
server.tool(
"complete_todo",
"标记一个待办事项为已完成",
{ id: z.number().describe("待办事项 ID") },
async ({ id }) => {
const todo = todos.find(t => t.id === id);
if (!todo) {
return { content: [{ type: "text", text: "未找到 ID: " + id }] };
}
todo.done = true;
return { content: [{ type: "text", text: "已完成: " + todo.text }] };
}
);
// Resource: 待办统计
server.resource(
"todo://stats",
"待办事项统计信息",
async () => {
const total = todos.length;
const done = todos.filter(t => t.done).length;
return {
contents: [{
uri: "todo://stats",
mimeType: "text/plain",
text: "总计: " + total + ", 已完成: " + done + ", 待完成: " + (total - done),
}]
};
}
);
// 启动
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
}
main();
在 Claude Code 中配置
在项目的 .mcp.json 或全局 ~/.claude/mcp.json 中添加:
{
"mcpServers": {
"todo": {
"command": "npx",
"args": ["tsx", "path/to/todo-server.ts"]
}
}
}
配置完成后,Claude Code 会自动发现并使用这些工具。
在 Claude Desktop 中配置
编辑 claude_desktop_config.json:
{
"mcpServers": {
"todo": {
"command": "node",
"args": ["path/to/todo-server.js"]
}
}
}
实战练习
Tip: 开发你的第一个 MCP Server。
- 使用
@modelcontextprotocol/sdk创建一个 MCP Server - 实现至少 2 个 Tool 和 1 个 Resource
- 在 Claude Code 中配置并测试
关键要点
Note: 本文核心总结
- MCP = AI 的标准化工具接口(USB for AI)
- Client-Server 架构,支持 stdio 和 SSE 传输
- 三大能力:Tools(执行操作)、Resources(读取数据)、Prompts(模板)
- 一个 MCP Server 可以被任何兼容的 Client 使用
延伸阅读
- MCP 官网:modelcontextprotocol.io
- 下一篇:Agent Skills——基于 MCP 的高级能力模块