Model Context Protocol (MCP),是 Anthropic 推出的用于大语言模型(LLM)与外部系统集成的开源协议。以下是详细解析,包含核心设计、消息格式和具体示例:
{
"mcp_version": "1.0",
"request_id": "req_123456",
"action": "execute_tool",
"tool": {
"name": "weather_api",
"parameters": {
"location": "San Francisco",
"unit": "celsius"
}
},
"context": {
"session_id": "sess_7890",
"user_id": "user_abc",
"memory": {
"previous_city": "New York"
}
}
}
字段说明:
| 字段 | 类型 | 必填 | 说明 |
|------|------|------|------|
| mcp_version | string | ✅ | 协议版本 (e.g., "1.0") |
| request_id | string | ✅ | 唯一请求标识符 |
| action | string | ✅ | execute_tool/update_context/get_state |
| tool | object | △ | 工具调用详情(action=execute_tool时必填) |
| context | object | △ | 会话上下文数据 |
{
"mcp_version": "1.0",
"request_id": "req_123456",
"status": "success",
"data": {
"temperature": 22,
"forecast": "sunny"
},
"context_updates": {
"last_location": "San Francisco"
}
}
字段说明:
| 字段 | 类型 | 说明 |
|------|------|------|
| status | string | success/error/pending |
| data | object | 工具执行结果 |
| context_updates | object | 需要更新的上下文字段 |
| error | object | 错误时包含 code 和 message |
{
"mcp_version": "1.0",
"action": "inject_context",
"context": {
"user_preferences": {
"language": "zh-CN",
"timezone": "Asia/Shanghai"
},
"document_summary": "会议重点:Q3 销售目标提升20%..."
},
"priority": "high"
}
特殊字段:
priority: low/medium/high(上下文注入优先级)ttl: 上下文有效时间(秒)sequenceDiagram
participant User
participant LLM
participant MCP_Router
participant FlightAPI
User->>LLM: "帮我订周五纽约到伦敦的机票"
LLM->>MCP_Router: MCP 工具请求(航班查询)
MCP_Router->>FlightAPI: 标准API调用
FlightAPI->>MCP_Router: 航班数据
MCP_Router->>LLM: MCP 结构化响应
LLM->>User: "找到3个航班:1. AA101 $680..."
工具沙箱: ```python
from mcp_sandbox import execute_tool
result = execute_tool(
tool_name="sql_query",
params={"query": "SELECT * FROM users"},
permissions=["read_only"] # 禁止写操作
)
2. **权限控制清单**:
```yaml
# mcp_permissions.yaml
tools:
- name: email_sender
allowed_domains: ["@company.com"]
rate_limit: 5/hour
- name: database
allowed_operations: ["SELECT"]
row_limit: 100
上下文过滤:
{
"context": {
"financial_data": "FILTERED[GDP数据]",
"user_identity": "REDACTED"
}
}
// 1. LLM 发送工具请求
{
"action": "execute_tool",
"tool": {
"name": "crm_lookup",
"parameters": {
"customer_id": "CUST-2023-789",
"fields": ["order_history", "support_tickets"]
}
}
}
// 2. CRM 系统响应
{
"status": "success",
"data": {
"last_order": "2023-08-10",
"open_tickets": 2
},
"context_updates": {
"customer_tier": "gold"
}
}
// 3. LLM 使用上下文生成回复
"您好金卡会员!您最近在8月10日有订单..."
上下文感知工具调用:
# 伪代码示例
if context.get("user_mood") == "angry":
tool_params["priority"] = "urgent"
json
{
"action": "pipeline",
"steps": [
{"tool": "geocoder", "params": {"address": input}},
{"tool": "weather", "params": {"coords": "$step1.output"}}
]
}
动态上下文管理:
{
"action": "update_context",
"operations": [
{"op": "merge", "path": "/user_prefs", "value": {"theme": "dark"}},
{"op": "delete", "path": "/temp_data"}
]
}
| 特性 | MCP | OpenAI Function Calling | LangChain |
|---|---|---|---|
| 上下文管理 | ✅ 动态注入 | ❌ 有限 | ⚠️ 需自定义 |
| 工具链组合 | ✅ 原生支持 | ❌ 单次调用 | ✅ 通过代理 |
| 安全沙箱 | ✅ 内置 | ❌ 依赖实现 | ⚠️ 部分支持 |
| 多模态支持 | ✅ (v1.1+) | ❌ | ⚠️ 实验性 |
上下文压缩:
# 移除过期上下文
context = {k: v for k,v in context.items() if time() < v["expiry"]}
工具降级策略:
{
"fallback_chain": [
{"tool": "paid_flight_api", "budget": 0.1},
{"tool": "free_flight_api"}
]
}
log
[MCP_AUDIT] req_id=req_123
| Tool: stock_trade
| Params: {"symbol":"AAPL","qty":100}
| User: id123
| Context_hash: a1b2c3d4
该协议目前处于活跃开发阶段,最新规范请参考 Anthropic 官方 GitHub 仓库。