mcp.md 6.1 KB

Model Context Protocol (MCP),是 Anthropic 推出的用于大语言模型(LLM)与外部系统集成的开源协议。以下是详细解析,包含核心设计、消息格式和具体示例:


MCP 核心设计目标

  1. 模型扩展性:允许 LLM 调用外部工具(API、数据库、函数等)
  2. 上下文管理:动态注入/更新模型上下文
  3. 标准化交互:统一模型与外部系统的通信协议
  4. 安全控制:通过沙箱机制限制模型权限

协议基础

  • 传输方式:HTTP/HTTPS 或 WebSocket
  • 数据格式:JSON
  • 交互模式:同步请求/响应 或 异步流式响应
  • 官方文档Anthropic MCP GitHub

核心消息格式

1. 模型请求(Model → 外部系统)

{
  "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 | △ | 会话上下文数据 |


2. 工具响应(外部系统 → 模型)

{
  "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 | 错误时包含 codemessage |


3. 上下文更新(系统 → 模型)

{
  "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..."

安全机制

  1. 工具沙箱: ```python

    示例: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
  1. 上下文过滤

    {
     "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日有订单..."
    

协议优势

  1. 上下文感知工具调用

    # 伪代码示例
    if context.get("user_mood") == "angry":
       tool_params["priority"] = "urgent"
    
    1. 多工具链式调用json { "action": "pipeline", "steps": [ {"tool": "geocoder", "params": {"address": input}}, {"tool": "weather", "params": {"coords": "$step1.output"}} ] }
  2. 动态上下文管理

    {
     "action": "update_context",
     "operations": [
       {"op": "merge", "path": "/user_prefs", "value": {"theme": "dark"}},
       {"op": "delete", "path": "/temp_data"}
     ]
    }
    

    与类似协议对比

    特性 MCP OpenAI Function Calling LangChain
    上下文管理 ✅ 动态注入 ❌ 有限 ⚠️ 需自定义
    工具链组合 ✅ 原生支持 ❌ 单次调用 ✅ 通过代理
    安全沙箱 ✅ 内置 ❌ 依赖实现 ⚠️ 部分支持
    多模态支持 ✅ (v1.1+) ⚠️ 实验性

    最佳实践建议

    1. 上下文压缩

      # 移除过期上下文
      context = {k: v for k,v in context.items() if time() < v["expiry"]}
      
  3. 工具降级策略

    {
     "fallback_chain": [
       {"tool": "paid_flight_api", "budget": 0.1},
       {"tool": "free_flight_api"}
     ]
    }
    
    1. 审计日志log [MCP_AUDIT] req_id=req_123 | Tool: stock_trade | Params: {"symbol":"AAPL","qty":100} | User: id123 | Context_hash: a1b2c3d4

该协议目前处于活跃开发阶段,最新规范请参考 Anthropic 官方 GitHub 仓库