ByteFisher AI 编程实战(十九):MCP协议深入——打通AI与工具

上篇我们通过 Function Calling 让 Agent 调用工具。但如果每个工具都要单独适配,维护成本很高。MCP 应运而生——它像 AI 界的 USB 接口,让工具和模型可以即插即用。

一、MCP 是什么

MCP(Model Context Protocol)是由 Anthropic 提出的开放协议,标准化 AI 模型与外部工具的交互方式。

1
AI 模型 ↔ MCP Client ↔ MCP Server → 数据库/文件系统/API/浏览器

可以把 MCP 理解为 AI 世界的 USB 协议:设备插上就能用,不用管具体实现。MCP Server 只要符合协议,任何 MCP Client(Claude Code、Cursor、OpenCode 等)都能直接连接。

MCP 出现之前,每个 AI 工具都需要各自适配工具集成:

1
2
3
4
5
6
7
传统方案(N 个工具 × M 个 AI 工具 = N×M 次适配):
Claude Code → 自己的工具适配
Cursor → 自己的工具适配
OpenCode → 自己的工具适配

MCP 方案(N 个工具 × 1 个协议 = N 次开发):
MCP Server → 任何支持 MCP 的 AI 工具即插即用

二、核心概念

概念 说明 类比
MCP Server 提供工具和资源的服务进程 USB 设备
MCP Client 连接 Server 和 AI 模型 USB 接口
Tool 可执行的操作(函数) 键盘按键
Resource 可读取的数据 硬盘数据
Transport 通信方式(stdio/SSE) USB 线缆

MCP 支持两种传输方式:

  • stdio:本地进程间通信,Server 作为子进程运行(适合本地开发)
  • SSE:通过 HTTP 服务端推送事件(适合远程服务器)

三、开发第一个 MCP Server

3.1 Python MCP Server(文件系统)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from mcp.server import Server, stdio_server

server = Server("file-system")

@server.list_tools()
async def list_tools():
return [
{
"name": "read_file",
"description": "读取文件内容",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "文件路径"}
},
"required": ["path"]
}
},
{
"name": "write_file",
"description": "写入文件内容",
"parameters": {
"type": "object",
"properties": {
"path": {"type": "string"},
"content": {"type": "string"}
},
"required": ["path", "content"]
}
},
{
"name": "list_files",
"description": "列出目录下的文件",
"parameters": {
"type": "object",
"properties": {
"dir": {"type": "string"}
},
"required": ["dir"]
}
}
]

@server.call_tool()
async def call_tool(name: str, arguments: dict):
if name == "read_file":
content = open(arguments["path"], encoding="utf-8").read()
return {"content": [{"type": "text", "text": content}]}
elif name == "write_file":
with open(arguments["path"], "w", encoding="utf-8") as f:
f.write(arguments["content"])
return {"content": [{"type": "text", "text": "写入成功"}]}
elif name == "list_files":
import os
files = os.listdir(arguments["dir"])
return {"content": [{"type": "text", "text": "\n".join(files)}]}

# 启动服务
if __name__ == "__main__":
stdio_server.run(server)

3.2 Node.js MCP Server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';

const server = new Server({
name: "sql-query",
version: "1.0.0"
}, {
capabilities: { tools: {} }
});

server.setRequestHandler('tools/list', async () => ({
tools: [{
name: "query_sqlite",
description: "执行 SQLite 查询",
inputSchema: {
type: "object",
properties: {
query: { type: "string", description: "SQL 查询语句" }
},
required: ["query"]
}
}]
}));

server.setRequestHandler('tools/call', async (request) => {
if (request.params.name === "query_sqlite") {
const { query } = request.params.arguments;
// 执行 SQLite 查询
return { content: [{ type: "text", text: queryResult }] };
}
});

const transport = new StdioServerTransport();
await server.connect(transport);

四、MCP Client 配置使用

4.1 Claude Code 中使用

1
2
3
4
5
# 连接 MCP Server
claude --mcp-server python file_system_server.py

# 或通过配置文件
# 在 ~/.claude.json 中添加:

4.2 OpenCode 中配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"mcpServers": {
"file-system": {
"command": "python",
"args": ["file_system_server.py"]
},
"sqlite": {
"command": "node",
"args": ["sql_server.mjs"]
},
"playwright": {
"command": "npx",
"args": ["@anthropic/mcp-playwright"]
}
}
}

4.3 Cursor 中配置

在 Cursor 的 Settings → MCP Servers 中添加:

1
2
3
Name: sqlite
Type: command
Command: node sql_server.mjs

五、常用 MCP Server 生态

Server 用途 安装方式 开发者
File System 文件读写 npx @anthropic/mcp-fs Anthropic
SQLite 数据库查询 npx @anthropic/mcp-sqlite Anthropic
PostgreSQL 数据库查询 npx @anthropic/mcp-postgres 社区
Playwright 浏览器自动化 npx @anthropic/mcp-playwright Anthropic
GitHub PR、Issue、代码管理 npx @anthropic/mcp-github 社区
Figma 设计稿信息 npx @figma/mcp Figma
Memory 长期记忆存储 npx @anthropic/mcp-memory Anthropic

六、MCP vs Function Calling

维度 Function Calling MCP
标准化 各模型各自定义 统一协议
复用性 不可跨框架 一次开发到处用
服务发现 代码中注册 自动发现 + 动态加载
传输层 仅在 API 调用中 支持 stdio/SSE/WebSocket
资源感知 仅支持函数 支持工具 + 资源 + 提示模板
生态 碎片化,各自实现 快速增长,社区驱动

七、最佳实践

原则 说明 示例
单一职责 一个 MCP Server 只做一件事 文件 Server 不负责数据库查询
参数校验 对工具输入做校验 检查路径是否在白名单内
错误处理 返回清晰错误信息 return {"isError": true, "content": [...]}
幂等性 同参数多次调用结果一致 查询类操作天然幂等
资源安全 限制可访问的范围 只允许操作项目目录内的文件

本章小结

  • MCP 是 AI 和工具之间的标准化通信协议,类似 AI 世界的 USB 协议
  • 开发 MCP Server 只需实现 list_tools 和 call_tool 两个接口
  • 支持 stdio(本地进程)和 SSE(远程服务)两种传输方式
  • Python 和 Node.js 都有官方 SDK,开发成本低
  • MCP 生态正在快速增长,主流工具已经支持
  • 和 Function Calling 比,MCP 的核心优势在标准化和复用性——写一次到处用

下一篇进入 Skill 开发——在 MCP 之上构建更高层的 AI 技能。

ByteFisher
分享编程技术 · 记录钓鱼乐趣
扫码关注
▸ 扫码关注 ◂
分享: