Skip to content

1.5 MCP协议规范

🎯 学习目标:深入理解MCP协议的技术规范和实现细节
⏱️ 预计时间:40分钟
📊 难度等级:⭐⭐⭐

📋 协议规范概览

MCP协议建立在 JSON-RPC 2.0 之上,定义了AI模型与外部工具之间的标准通信规范。本节将详细介绍协议的各个组成部分。

🎯 规范结构图

🔧 1. 基础协议层

📡 JSON-RPC 2.0 基础

MCP完全兼容JSON-RPC 2.0规范,所有消息都遵循以下基本结构:

📝 基本消息结构

typescript
// 请求消息
interface JSONRPCRequest {
  jsonrpc: "2.0";           // 协议版本
  id: string | number;      // 请求ID(用于匹配响应)
  method: string;           // 方法名
  params?: object;          // 参数对象(可选)
}

// 响应消息
interface JSONRPCResponse {
  jsonrpc: "2.0";           // 协议版本
  id: string | number;      // 请求ID(与请求匹配)
  result?: any;             // 结果(成功时)
  error?: JSONRPCError;     // 错误(失败时)
}

// 错误对象
interface JSONRPCError {
  code: number;             // 错误代码
  message: string;          // 错误消息
  data?: any;               // 附加错误信息(可选)
}

// 通知消息(无需响应)
interface JSONRPCNotification {
  jsonrpc: "2.0";           // 协议版本
  method: string;           // 方法名
  params?: object;          // 参数对象(可选)
}

🔢 标准错误代码

MCP使用JSON-RPC 2.0标准错误代码,并扩展了一些MCP特定的错误代码:

typescript
enum JSONRPCErrorCode {
  // JSON-RPC 2.0 标准错误代码
  PARSE_ERROR = -32700,      // 解析错误
  INVALID_REQUEST = -32600,   // 无效请求
  METHOD_NOT_FOUND = -32601,  // 方法不存在
  INVALID_PARAMS = -32602,    // 无效参数
  INTERNAL_ERROR = -32603,    // 内部错误
  
  // MCP 扩展错误代码
  TOOL_NOT_FOUND = -32000,    // 工具不存在
  RESOURCE_NOT_FOUND = -32001, // 资源不存在
  PERMISSION_DENIED = -32002,  // 权限拒绝
  RATE_LIMITED = -32003,       // 速率限制
  TIMEOUT = -32004,            // 超时
  INVALID_TOOL_INPUT = -32005  // 工具输入无效
}

🌐 2. 传输层规范

MCP支持多种传输协议,以适应不同的部署场景:

🔗 支持的传输协议

📡 HTTP/HTTPS 传输

基本配置

json
{
  "transport": {
    "type": "http",
    "host": "localhost",
    "port": 8080,
    "path": "/mcp",
    "secure": true,
    "headers": {
      "Content-Type": "application/json",
      "User-Agent": "MCP-Client/1.0"
    }
  }
}

HTTP请求示例

http
POST /mcp HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Content-Length: 156

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "get_weather",
    "arguments": {
      "city": "北京"
    }
  }
}

HTTP响应示例

http
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 234

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "北京当前温度25°C,天气晴朗"
      }
    ]
  }
}

🔌 WebSocket 传输

连接建立

javascript
// 客户端连接
const ws = new WebSocket('ws://localhost:8080/mcp');

ws.onopen = function() {
  // 发送初始化消息
  ws.send(JSON.stringify({
    jsonrpc: "2.0",
    id: 1,
    method: "initialize",
    params: {
      protocolVersion: "2024-11-05",
      capabilities: {
        tools: {},
        resources: {},
        prompts: {}
      },
      clientInfo: {
        name: "my-mcp-client",
        version: "1.0.0"
      }
    }
  }));
};

ws.onmessage = function(event) {
  const message = JSON.parse(event.data);
  console.log('收到消息:', message);
};

双向通信示例

json
// 客户端 → 服务器:调用工具
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/call",
  "params": {
    "name": "analyze_data",
    "arguments": {
      "data": [1, 2, 3, 4, 5],
      "type": "statistics"
    }
  }
}

// 服务器 → 客户端:进度通知
{
  "jsonrpc": "2.0",
  "method": "tools/progress",
  "params": {
    "toolRequestId": 2,
    "progress": 50,
    "message": "正在分析数据..."
  }
}

// 服务器 → 客户端:最终结果
{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "数据分析完成:平均值=3.0,标准差=1.58"
      }
    ]
  }
}

📟 STDIO 传输

STDIO传输特别适合命令行工具和进程间通信:

启动方式

bash
# 启动MCP服务器(STDIO模式)
./mcp-server --transport stdio

# 或通过配置文件
./mcp-server --config config.json

配置文件示例

json
{
  "transport": {
    "type": "stdio",
    "encoding": "utf-8",
    "bufferSize": 8192
  },
  "logging": {
    "level": "info",
    "file": "/tmp/mcp-server.log"
  }
}

通信示例

bash
# 输入(客户端发送)
{"jsonrpc":"2.0","id":1,"method":"tools/list"}

# 输出(服务器响应)
{"jsonrpc":"2.0","id":1,"result":{"tools":[{"name":"calculator","description":"执行数学计算"}]}}

📨 3. 消息层规范

🚀 初始化流程

每个MCP连接都必须先完成初始化握手:

初始化序列图

初始化请求

json
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "initialize",
  "params": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
      "tools": {
        "listChanged": true
      },
      "resources": {
        "subscribe": true,
        "listChanged": true
      },
      "prompts": {
        "listChanged": true
      },
      "logging": {}
    },
    "clientInfo": {
      "name": "example-client",
      "version": "1.0.0"
    }
  }
}

初始化响应

json
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
      "tools": {
        "listChanged": true
      },
      "resources": {
        "subscribe": true,
        "listChanged": true
      },
      "prompts": {
        "listChanged": true
      },
      "logging": {
        "level": "info"
      }
    },
    "serverInfo": {
      "name": "example-server",
      "version": "1.0.0"
    }
  }
}

🛠️ 工具管理消息

列出工具

json
// 请求
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "tools/list"
}

// 响应
{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "tools": [
      {
        "name": "calculator",
        "description": "执行基本数学计算",
        "inputSchema": {
          "type": "object",
          "properties": {
            "operation": {
              "type": "string",
              "enum": ["add", "subtract", "multiply", "divide"]
            },
            "a": {"type": "number"},
            "b": {"type": "number"}
          },
          "required": ["operation", "a", "b"]
        }
      },
      {
        "name": "weather",
        "description": "获取天气信息",
        "inputSchema": {
          "type": "object",
          "properties": {
            "city": {"type": "string"},
            "units": {"type": "string", "enum": ["celsius", "fahrenheit"], "default": "celsius"}
          },
          "required": ["city"]
        }
      }
    ]
  }
}

调用工具

json
// 请求
{
  "jsonrpc": "2.0",
  "id": 3,
  "method": "tools/call",
  "params": {
    "name": "calculator",
    "arguments": {
      "operation": "add",
      "a": 15,
      "b": 25
    }
  }
}

// 响应
{
  "jsonrpc": "2.0",
  "id": 3,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "15 + 25 = 40"
      }
    ],
    "isError": false
  }
}

工具执行错误

json
{
  "jsonrpc": "2.0",
  "id": 3,
  "result": {
    "content": [
      {
        "type": "text", 
        "text": "错误:除数不能为零"
      }
    ],
    "isError": true
  }
}

📁 资源管理消息

列出资源

json
// 请求
{
  "jsonrpc": "2.0",
  "id": 4,
  "method": "resources/list"
}

// 响应
{
  "jsonrpc": "2.0",
  "id": 4,
  "result": {
    "resources": [
      {
        "uri": "file:///docs/readme.md",
        "name": "项目说明文档",
        "description": "项目的详细说明和使用指南",
        "mimeType": "text/markdown"
      },
      {
        "uri": "mysql://localhost/users",
        "name": "用户数据库",
        "description": "用户信息表",
        "mimeType": "application/json"
      }
    ]
  }
}

读取资源

json
// 请求
{
  "jsonrpc": "2.0",
  "id": 5,
  "method": "resources/read",
  "params": {
    "uri": "file:///docs/readme.md"
  }
}

// 响应
{
  "jsonrpc": "2.0",
  "id": 5,
  "result": {
    "contents": [
      {
        "uri": "file:///docs/readme.md",
        "mimeType": "text/markdown",
        "text": "# 项目说明\n\n这是一个示例项目..."
      }
    ]
  }
}

订阅资源变更

json
// 请求订阅
{
  "jsonrpc": "2.0",
  "id": 6,
  "method": "resources/subscribe",
  "params": {
    "uri": "file:///docs/readme.md"
  }
}

// 订阅确认
{
  "jsonrpc": "2.0",
  "id": 6,
  "result": {}
}

// 变更通知(无ID的通知消息)
{
  "jsonrpc": "2.0",
  "method": "notifications/resources/updated",
  "params": {
    "uri": "file:///docs/readme.md"
  }
}

💬 提示词管理消息

列出提示词模板

json
// 请求
{
  "jsonrpc": "2.0",
  "id": 7,
  "method": "prompts/list"
}

// 响应
{
  "jsonrpc": "2.0",
  "id": 7,
  "result": {
    "prompts": [
      {
        "name": "code_reviewer",
        "description": "代码审查助手提示词",
        "arguments": [
          {
            "name": "language",
            "description": "编程语言",
            "required": true
          },
          {
            "name": "focus",
            "description": "审查重点",
            "required": false
          }
        ]
      }
    ]
  }
}

获取提示词

json
// 请求
{
  "jsonrpc": "2.0",
  "id": 8,
  "method": "prompts/get",
  "params": {
    "name": "code_reviewer",
    "arguments": {
      "language": "Python",
      "focus": "安全性"
    }
  }
}

// 响应
{
  "jsonrpc": "2.0",
  "id": 8,
  "result": {
    "description": "代码审查助手提示词",
    "messages": [
      {
        "role": "system",
        "content": {
          "type": "text",
          "text": "你是一个专业的Python代码审查专家,重点关注代码的安全性..."
        }
      }
    ]
  }
}

🔒 4. 安全和认证规范

🛡️ 认证机制

MCP支持多种认证方式:

API密钥认证

json
{
  "transport": {
    "type": "http",
    "auth": {
      "type": "api_key",
      "header": "X-API-Key",
      "value": "your-api-key-here"
    }
  }
}

Bearer Token认证

json
{
  "transport": {
    "type": "http", 
    "auth": {
      "type": "bearer",
      "token": "eyJhbGciOiJIUzI1NiIs..."
    }
  }
}

自定义认证头

json
{
  "transport": {
    "type": "http",
    "auth": {
      "type": "custom",
      "headers": {
        "Authorization": "Custom auth-token-here",
        "X-Client-ID": "client-123"
      }
    }
  }
}

🔐 权限控制

权限控制通过工具和资源级别的访问控制实现:

json
// 权限拒绝响应
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32002,
    "message": "Permission denied",
    "data": {
      "resource": "sensitive_data",
      "required_permission": "admin",
      "user_permissions": ["read", "write"]
    }
  }
}

📊 5. 内容类型规范

MCP定义了标准的内容类型来表示不同格式的数据:

📝 文本内容

json
{
  "type": "text",
  "text": "这是一段文本内容"
}

🖼️ 图像内容

json
{
  "type": "image",
  "data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==",
  "mimeType": "image/png"
}

📁 资源引用

json
{
  "type": "resource",
  "resource": {
    "uri": "file:///path/to/file.txt",
    "text": "文件内容..."
  }
}

🛠️ 工具结果

json
{
  "type": "tool_result",
  "toolUseId": "tool-123",
  "content": [
    {
      "type": "text",
      "text": "工具执行结果"
    }
  ],
  "isError": false
}

⚡ 6. 流式和批量操作

🌊 流式传输

对于大型数据或长时间运行的操作,MCP支持流式传输:

json
// 开始流式操作
{
  "jsonrpc": "2.0",
  "id": 10,
  "method": "tools/call",
  "params": {
    "name": "analyze_large_dataset",
    "arguments": {
      "dataset": "sales_data_2023.csv",
      "streaming": true
    }
  }
}

// 流式数据通知
{
  "jsonrpc": "2.0",
  "method": "notifications/tools/stream",
  "params": {
    "toolRequestId": 10,
    "content": [
      {
        "type": "text",
        "text": "已处理1000行数据..."
      }
    ]
  }
}

// 流结束
{
  "jsonrpc": "2.0",
  "id": 10,
  "result": {
    "content": [
      {
        "type": "text",
        "text": "数据分析完成,共处理50000行数据"
      }
    ]
  }
}

📦 批量操作

json
// 批量调用工具
{
  "jsonrpc": "2.0",
  "id": 11,
  "method": "tools/batch_call",
  "params": {
    "calls": [
      {
        "name": "get_weather",
        "arguments": {"city": "北京"}
      },
      {
        "name": "get_weather", 
        "arguments": {"city": "上海"}
      },
      {
        "name": "get_weather",
        "arguments": {"city": "广州"}
      }
    ]
  }
}

// 批量响应
{
  "jsonrpc": "2.0",
  "id": 11,
  "result": {
    "results": [
      {
        "content": [{"type": "text", "text": "北京:25°C,晴"}],
        "isError": false
      },
      {
        "content": [{"type": "text", "text": "上海:28°C,多云"}],
        "isError": false
      },
      {
        "content": [{"type": "text", "text": "广州:30°C,雨"}],
        "isError": false
      }
    ]
  }
}

🔍 7. 调试和日志规范

📝 日志消息

MCP支持结构化日志记录:

json
// 客户端启用日志
{
  "jsonrpc": "2.0",
  "method": "notifications/logging/setLevel",
  "params": {
    "level": "debug"
  }
}

// 服务器日志消息
{
  "jsonrpc": "2.0",
  "method": "notifications/message",
  "params": {
    "level": "info",
    "logger": "weather-tool",
    "data": {
      "message": "正在获取北京天气信息",
      "city": "北京",
      "timestamp": "2024-01-15T10:30:00Z"
    }
  }
}

🐛 错误详情

详细的错误信息帮助调试:

json
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32005,
    "message": "Invalid tool input",
    "data": {
      "tool": "calculator",
      "validation_errors": [
        {
          "field": "operation",
          "message": "必须是 add, subtract, multiply, divide 之一",
          "received": "power"
        }
      ],
      "stack_trace": "ValidationError at line 45..."
    }
  }
}

🎯 协议规范总结

📚 核心要点

通过本节学习,你应该掌握了:

🏗️协议结构

  • JSON-RPC 2.0基础:消息格式和错误处理
  • 传输层支持:HTTP、WebSocket、STDIO多种传输方式
  • 初始化流程:连接建立和能力协商

🛠️功能规范

  • 工具管理:列出、调用、错误处理
  • 资源管理:列出、读取、订阅变更
  • 提示词管理:模板列出和获取

🔒安全规范

  • 认证机制:API密钥、Token、自定义认证
  • 权限控制:访问控制和错误响应
  • 安全传输:HTTPS和WSS支持

⚡高级特性

  • 流式传输:大数据和长时间操作支持
  • 批量操作:多个请求的批量处理
  • 调试支持:日志记录和错误详情

🔗 规范文档导航

🤔 实践思考

💭 理解检测

  1. 协议选择:为什么MCP选择JSON-RPC 2.0而不是REST或GraphQL?

  2. 传输方式:不同传输方式的适用场景是什么?

  3. 错误处理:如何设计合理的错误处理机制?

  4. 安全考虑:在实际部署中需要考虑哪些安全问题?

🛠️ 实践挑战

尝试设计一个符合MCP规范的简单协议交互:

  1. 初始化握手:客户端和服务器的能力协商
  2. 工具调用:包含参数验证和错误处理
  3. 资源访问:支持权限控制
  4. 错误场景:各种异常情况的处理

📖 扩展学习

🔗 参考资料

🎓 下一步

掌握了协议规范后,你就可以:

  • 📝 实现符合规范的MCP客户端
  • 🔧 开发标准的MCP服务器
  • 🐛 有效调试MCP通信问题
  • 🔒 设计安全的MCP部署方案

准备好了解MCP生态系统了吗?让我们看看实际的应用场景!

👉 下一小节:1.5 应用场景