784 字
2 分钟
MCP 协议解析:Agent 的工具标准
如果 Agent 是「大脑」,工具是「双手」,那 MCP 就是连接它们的「神经系统」。
在 MCP 出现之前,每个 AI 应用都有自己的工具接口标准。开发者需要为不同的平台重复开发相似的功能。
MCP(Model Context Protocol)的出现,让「一次开发,处处可用」成为可能。
本文要点
- MCP 诞生的背景与价值
- 协议架构:Host、Client、Server
- 消息类型与 JSON-RPC 2.0
- 工具定义 Schema 与发现机制
- 资源访问与订阅模式
- MCP vs Function Calling vs OpenAPI
- 主流 MCP Server 实现
一、MCP 诞生的背景
1.1 工具接口的碎片化问题
问题现状:
Claude Desktop → 需要开发 Claude 专用工具Cursor IDE → 需要开发 Cursor 专用工具Windsurf → 需要开发 Windsurf 专用工具自定义应用 → 需要开发自己的工具体系
结果:• 开发者重复造轮子• 用户在不同平台体验不一致• 工具生态无法共享• 维护成本高昂1.2 MCP 的解决方案
flowchart LR
subgraph 传统模式
A1[工具 A] --> B1[Claude]
A2[工具 A'] --> B2[Cursor]
A3[工具 A''] --> B3[其他应用]
end
subgraph MCP 模式
C[MCP Server<br/>工具 A] --> D[MCP 协议]
D --> E[Claude]
D --> F[Cursor]
D --> G[其他应用]
end
1.3 MCP 的核心价值
┌─────────────────────────────────────────────────────────────┐│ MCP 核心价值 │├─────────────────────────────────────────────────────────────┤│ ││ 对开发者: ││ 一次开发,多处使用 ││ 统一的工具接口标准 ││ 减少维护成本 ││ 接入更多 AI 应用 ││ ││ 对用户: ││ 工具可在不同应用间共享 ││ 体验一致性 ││ 更丰富的工具生态 ││ ││ 对 AI 应用: ││ 即插即用的工具生态 ││ 降低工具开发门槛 ││ 专注核心能力 ││ │└─────────────────────────────────────────────────────────────┘二、协议架构
2.1 三层架构模型
flowchart TB
subgraph MCP Host(宿主应用)
A[Claude Desktop]
B[Cursor IDE]
C[自定义应用]
end
subgraph MCP Client(客户端)
D[连接管理]
E[消息路由]
F[能力协商]
end
subgraph MCP Server(服务器)
G[文件系统]
H[数据库]
I[搜索 API]
J[自定义工具]
end
A --> D
B --> D
C --> D
D <--> G
D <--> H
D <--> I
D <--> J
2.2 组件职责
┌─────────────────────────────────────────────────────────────┐│ MCP 组件职责 │├─────────────────────────────────────────────────────────────┤│ ││ MCP Host(宿主应用) ││ ├── 定义:集成 MCP 的 AI 应用 ││ ├── 职责: ││ │ ├── 提供 AI 能力 ││ │ ├── 管理 MCP Client ││ │ ├── 展示工具结果 ││ │ └── 处理用户交互 ││ └── 示例:Claude Desktop、Cursor、Windsurf ││ ││ MCP Client(客户端) ││ ├── 定义:Host 内的 MCP 客户端组件 ││ ├── 职责: ││ │ ├── 建立 Server 连接 ││ │ ├── 发送请求和接收响应 ││ │ ├── 能力协商 ││ │ └── 消息路由 ││ └── 每个 Host 可管理多个 Client ││ ││ MCP Server(服务器) ││ ├── 定义:提供工具和资源的后端服务 ││ ├── 职责: ││ │ ├── 暴露工具列表 ││ │ ├── 提供资源访问 ││ │ ├── 执行工具调用 ││ │ └── 发送通知 ││ └── 可以是本地进程或远程服务 ││ │└─────────────────────────────────────────────────────────────┘2.3 连接方式
# MCP 支持两种传输方式
# 1. Stdio(标准输入输出)# 适用于本地工具,Server 作为子进程运行{ "transport": "stdio", "command": "python", "args": ["mcp_server.py"]}
# 2. SSE(Server-Sent Events)# 适用于远程服务,通过 HTTP 连接{ "transport": "sse", "url": "https://api.example.com/mcp"}三、消息类型与 JSON-RPC 2.0
3.1 JSON-RPC 2.0 基础
MCP 基于 JSON-RPC 2.0 协议,这是一种轻量级的远程过程调用协议。
// 请求格式{ "jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}
// 成功响应格式{ "jsonrpc": "2.0", "id": 1, "result": { "tools": [...] }}
// 错误响应格式{ "jsonrpc": "2.0", "id": 1, "error": { "code": -32600, "message": "Invalid Request" }}3.2 MCP 消息类型
flowchart TB
A[MCP 消息] --> B[Request]
A --> C[Response]
A --> D[Notification]
B --> B1[initialize]
B --> B2[tools/list]
B --> B3[tools/call]
B --> B4[resources/list]
B --> B5[resources/read]
C --> C1[成功结果]
C --> C2[错误信息]
D --> D1[resources/updated]
D --> D2[tools/list_changed]
D --> D3[logging/log]
3.3 核心消息详解
┌─────────────────────────────────────────────────────────────┐│ MCP 核心消息 │├─────────────────────────────────────────────────────────────┤│ ││ 初始化阶段 ││ ├── initialize:Client 发送能力列表,Server 返回自身能力 ││ └── notifications/initialized:确认初始化完成 ││ ││ 工具操作 ││ ├── tools/list:获取可用工具列表 ││ ├── tools/call:调用指定工具 ││ └── notifications/tools/list_changed:工具列表变更通知 ││ ││ 资源操作 ││ ├── resources/list:获取可用资源列表 ││ ├── resources/read:读取指定资源 ││ ├── resources/templates/list:获取资源模板 ││ └── notifications/resources/updated:资源更新通知 ││ ││ 提示词操作 ││ ├── prompts/list:获取可用提示词模板 ││ └── prompts/get:获取指定提示词 ││ ││ 日志与采样 ││ ├── logging/setLevel:设置日志级别 ││ └── sampling/createMessage:请求 AI 生成消息 ││ │└─────────────────────────────────────────────────────────────┘3.4 初始化握手流程
sequenceDiagram
participant C as Client
participant S as Server
C->>S: initialize
Note right of C: 发送客户端能力和协议版本
S-->>C: initialize response
Note left of S: 返回服务端能力
C->>S: notifications/initialized
Note right of C: 确认初始化完成
Note over C,S: 连接建立,可以开始通信
// 初始化请求{ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2024-11-05", "capabilities": { "tools": {}, "resources": {"subscribe": true}, "prompts": {} }, "clientInfo": { "name": "my-client", "version": "1.0.0" } }}
// 初始化响应{ "jsonrpc": "2.0", "id": 1, "result": { "protocolVersion": "2024-11-05", "capabilities": { "tools": {"listChanged": true}, "resources": {"subscribe": true, "listChanged": true} }, "serverInfo": { "name": "my-server", "version": "1.0.0" } }}四、工具定义 Schema
4.1 工具列表响应
{ "jsonrpc": "2.0", "id": 2, "result": { "tools": [ { "name": "get_weather", "description": "获取指定城市的天气信息", "inputSchema": { "type": "object", "properties": { "city": { "type": "string", "description": "城市名称" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "default": "celsius" } }, "required": ["city"] } }, { "name": "search_web", "description": "搜索网络获取信息", "inputSchema": { "type": "object", "properties": { "query": { "type": "string", "description": "搜索关键词" }, "limit": { "type": "integer", "description": "返回结果数量", "default": 5 } }, "required": ["query"] } } ] }}4.2 工具调用流程
sequenceDiagram
participant AI as AI Model
participant C as MCP Client
participant S as MCP Server
AI->>C: 决定调用 get_weather
C->>S: tools/call
Note right of C: {"name": "get_weather",<br/>"arguments": {"city": "北京"}}
S->>S: 执行工具
S-->>C: 工具结果
Note left of S: {"content": [...],<br/>"isError": false}
C-->>AI: 返回结果给 AI
AI->>AI: 基于结果生成回答
4.3 工具调用请求与响应
// 工具调用请求{ "jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": { "name": "get_weather", "arguments": { "city": "北京", "unit": "celsius" } }}
// 工具调用响应(成功){ "jsonrpc": "2.0", "id": 3, "result": { "content": [ { "type": "text", "text": "北京今天晴,温度 15-25°C,空气质量良好" } ], "isError": false }}
// 工具调用响应(错误){ "jsonrpc": "2.0", "id": 3, "result": { "content": [ { "type": "text", "text": "错误:无法获取城市天气信息" } ], "isError": true }}五、资源访问与订阅
5.1 资源类型
┌─────────────────────────────────────────────────────────────┐│ MCP 资源类型 │├─────────────────────────────────────────────────────────────┤│ ││ 静态资源 ││ ├── 文件资源:https://github.com/modelcontextprotocol/servers/blob/main/src/filesystem/README.md ││ ├── 文档资源:document:///project/README.md ││ └── 配置资源:config:///settings.json ││ ││ 动态资源 ││ ├── 数据库记录:db:///users/123 ││ ├── API 响应:api:///weather/beijing ││ └── 实时数据:stream:///logs/app ││ ││ 资源模板 ││ ├── 参数化路径:https://github.com/{org}/{repo}/blob/{branch}/{path} ││ ├── 查询参数:db:///users?id={user_id} ││ └── 模式匹配:log:///{app}/{date} ││ │└─────────────────────────────────────────────────────────────┘5.2 资源列表与读取
// 资源列表请求{ "jsonrpc": "2.0", "id": 4, "method": "resources/list"}
// 资源列表响应{ "jsonrpc": "2.0", "id": 4, "result": { "resources": [ { "uri": "https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/__init__.py", "name": "__init__.py", "description": "MCP SDK 主模块", "mimeType": "text/x-python" }, { "uri": "https://github.com/modelcontextprotocol/python-sdk/blob/main/pyproject.toml", "name": "pyproject.toml", "description": "项目配置文件", "mimeType": "application/json" } ] }}
// 资源读取请求{ "jsonrpc": "2.0", "id": 5, "method": "resources/read", "params": { "uri": "https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/__init__.py" }}
// 资源读取响应{ "jsonrpc": "2.0", "id": 5, "result": { "contents": [ { "uri": "https://github.com/modelcontextprotocol/python-sdk/blob/main/src/mcp/__init__.py", "mimeType": "text/x-python", "text": "def main():\n print('Hello, World!')\n" } ] }}5.3 资源订阅机制
sequenceDiagram
participant C as Client
participant S as Server
C->>S: resources/subscribe
Note right of C: {"uri": "https://github.com/modelcontextprotocol/servers/blob/main/src/README.md"}
S-->>C: 订阅确认
loop 资源变化时
S->>C: notifications/resources/updated
Note left of S: {"uri": "https://github.com/modelcontextprotocol/servers/blob/main/src/README.md"}
end
C->>S: resources/unsubscribe
Note right of C: 取消订阅
六、MCP vs Function Calling vs OpenAPI
6.1 对比分析
┌─────────────────────────────────────────────────────────────┐│ 三种方案对比 │├───────────────┬─────────────┬────────────────┬──────────────┤│ 维度 │ MCP │ Function Call │ OpenAPI │├───────────────┼─────────────┼────────────────┼──────────────┤│ 设计目标 │ AI 工具标准 │ 模型能力扩展 │ API 文档标准 ││ 发起方 │ Anthropic │ OpenAI │ Linux 基金会 ││ 适用范围 │ 跨平台通用 │ 特定模型 │ REST API ││ 协议层 │ 应用层协议 │ 模型接口 │ 描述规范 ││ 双向通信 │ 支持 │ 不支持 │ 不适用 ││ 资源订阅 │ 支持 │ 不支持 │ 不适用 ││ 发现机制 │ 内置 │ 需手动配置 │ Swagger UI ││ 状态管理 │ 支持 │ 不支持 │ 不适用 ││ 安全模型 │ 权限控制 │ 依赖应用 │ OAuth 等 │└───────────────┴─────────────┴────────────────┴──────────────┘6.2 关系图解
flowchart TB
subgraph MCP 协议层
A[MCP Server]
B[工具定义]
C[资源管理]
D[提示词模板]
end
subgraph 模型接口层
E[Function Calling]
F[Tool Use]
end
subgraph API 层
G[OpenAPI Spec]
H[REST Endpoint]
end
A --> E
A --> F
B --> G
B --> H
style A fill:#4caf50,color:#fff
style E fill:#2196f3,color:#fff
style G fill:#ff9800,color:#fff
6.3 各方案适用场景
MCP 适合:• 需要跨多个 AI 平台使用的工具• 需要资源订阅和实时更新• 需要统一的工具发现机制• 构建可复用的工具生态
Function Calling 适合:• 单一平台深度集成• 快速原型开发• 简单的工具调用场景• 与特定模型深度优化
OpenAPI 适合:• 已有 REST API 的 AI 化• API 文档自动生成• 与现有系统集成• 企业内部 API 管理七、主流 MCP Server 实现
7.1 官方参考实现
┌─────────────────────────────────────────────────────────────┐│ 官方 MCP Server │├─────────────────────────────────────────────────────────────┤│ ││ @modelcontextprotocol/server-filesystem ││ ├── 功能:文件系统操作 ││ ├── 支持:读写文件、目录遍历、文件搜索 ││ └── 用法:npx @modelcontextprotocol/server-filesystem ││ ││ @modelcontextprotocol/server-github ││ ├── 功能:GitHub 操作 ││ ├── 支持:仓库管理、Issue、PR、搜索 ││ └── 用法:需要 GitHub Token ││ ││ @modelcontextprotocol/server-postgres ││ ├── 功能:PostgreSQL 数据库 ││ ├── 支持:查询、Schema 发现 ││ └── 用法:配置数据库连接 ││ ││ @modelcontextprotocol/server-sqlite ││ ├── 功能:SQLite 数据库 ││ ├── 支持:查询、Schema 发现 ││ └── 用法:指定数据库文件路径 ││ ││ @modelcontextprotocol/server-brave-search ││ ├── 功能:Brave 搜索 ││ ├── 支持:网页搜索 ││ └── 用法:需要 Brave API Key ││ │└─────────────────────────────────────────────────────────────┘7.2 社区实现
流行社区 MCP Server:
• mcp-server-puppeteer - 浏览器自动化• mcp-server-docker - Docker 容器管理• mcp-server-kubernetes - K8s 集群管理• mcp-server-aws - AWS 服务集成• mcp-server-linear - 项目管理• mcp-server-notion - Notion 笔记• mcp-server-slack - Slack 集成7.3 自定义 MCP Server 示例
from mcp.server import Serverfrom mcp.types import Tool, TextContentimport asyncio
# 创建 Server 实例server = Server("my-custom-server")
# 定义工具列表@server.list_tools()async def list_tools(): return [ Tool( name="calculate", description="执行数学计算", inputSchema={ "type": "object", "properties": { "expression": { "type": "string", "description": "数学表达式,如:2 + 3 * 4" } }, "required": ["expression"] } ), Tool( name="get_time", description="获取当前时间", inputSchema={ "type": "object", "properties": {}, "required": [] } ) ]
# 实现工具调用@server.call_tool()async def call_tool(name: str, arguments: dict): if name == "calculate": try: result = eval(arguments["expression"]) return [TextContent(type="text", text=str(result))] except Exception as e: return [TextContent(type="text", text=f"计算错误:{e}")]
elif name == "get_time": from datetime import datetime now = datetime.now().strftime("%Y-%m-%d %H:%M:%S") return [TextContent(type="text", text=f"当前时间:{now}")]
return [TextContent(type="text", text=f"未知工具:{name}")]
# 运行 Serverasync def main(): from mcp.server.stdio import stdio_server
async with stdio_server() as (read_stream, write_stream): await server.run( read_stream, write_stream, server.create_initialization_options() )
if __name__ == "__main__": asyncio.run(main())常见问题 FAQ
Q1:MCP 和 LangChain Tools 有什么关系?
A:
- MCP 是协议标准,LangChain Tools 是框架实现
- LangChain 可以集成 MCP Server 作为工具来源
- MCP 更侧重跨平台互操作性
Q2:MCP Server 如何部署?
A:
- 本地部署:作为子进程通过 stdio 通信
- 远程部署:作为 HTTP 服务通过 SSE 通信
- 容器化:打包为 Docker 容器
Q3:MCP 的安全性如何保证?
A:
- 权限控制:Host 可以限制 Server 的访问范围
- 沙箱隔离:敏感操作在隔离环境中执行
- 审计日志:记录所有工具调用
- 用户确认:高风险操作需要用户批准
Q4:如何调试 MCP Server?
A:
- 使用 MCP Inspector 工具可视化调试
- 查看 JSON-RPC 消息日志
- 使用 Claude Desktop 的开发者模式
Q5:MCP 的未来发展方向是什么?
A:
- 更多官方 Server 实现
- 标准化的安全模型
- 流式响应支持
- 与更多 AI 平台集成
小结
MCP 是 AI Agent 工具生态的「USB 接口」——一个开放、统一的标准。
核心要点回顾:
┌─────────────────────────────────────────────────────────────┐│ MCP 协议核心总结 │├─────────────────────────────────────────────────────────────┤│ ││ 架构:Host(应用)+ Client(连接)+ Server(工具) ││ ││ 协议:基于 JSON-RPC 2.0,支持请求、响应、通知 ││ ││ 能力:工具调用、资源访问、提示词模板、订阅机制 ││ ││ 价值:一次开发,多处使用,工具生态共享 ││ ││ 对比:比 Function Calling 更通用,比 OpenAPI 更适合 AI ││ │└─────────────────────────────────────────────────────────────┘下一步学习:
下篇预告
《Agent 安全与伦理:责任 AI 的边界》
深入解析:
- Agent 安全风险与防护
- 提示词注入攻击与防御
- 隐私保护与数据安全
- Agent 伦理设计原则
参考资料
支持与分享
如果这篇文章对你有帮助,欢迎支持作者或分享给更多人
MCP 协议解析:Agent 的工具标准
https://blog.souloss.com/posts/machine-learning/agent-guide/mcp-protocol-analysis/ 部分信息可能已经过时
相关文章 智能推荐
1
Agent 构建方法论深度解析
AI 深入解析 LLM Agent 的核心组件——Tool Use、ReAct 架构、Planning 能力、Memory 系统与主流框架对比。
2
从Chatbot到Agent:打造能自主干活的AI
AI 从Chatbot到Agent——打造能自主干活的AI
3
让AI使用工具:Function Calling实战
AI 让AI使用工具——Function Calling实战
4
Agent 工具调用:Function Calling 与 Tool Use 实战
AI 深入解析 Agent 工具调用机制——Function Calling 原理、Tool Schema 设计、工具选择策略,以及多工具协同的实战指南。
5
Agent 评估体系:如何衡量 Agent 的能力
AI 深度解读 Agent 评估体系——任务完成率、工具调用准确率、成本效率等多维度评估框架






