MCP 的消息格式基于 JSON-RPC 2.0 协议,并进行了扩展以支持 AI 模型与外部系统的交互。以下是详细的消息格式说明:
基础消息结构
所有 MCP 消息都遵循 JSON-RPC 2.0 的基本格式:
json{ "jsonrpc": "2.0", "id": "unique-request-id", "method": "method-name", "params": { ... } }
1. 请求消息(Request)
用于客户端向服务器发送工具调用请求:
json{ "jsonrpc": "2.0", "id": "req-123", "method": "tools/call", "params": { "name": "calculate", "arguments": { "expression": "2 + 2" } } }
2. 响应消息(Response)
服务器返回执行结果:
json{ "jsonrpc": "2.0", "id": "req-123", "result": { "content": [ { "type": "text", "text": "结果: 4" } ] } }
3. 错误响应(Error Response)
当请求失败时返回:
json{ "jsonrpc": "2.0", "id": "req-123", "error": { "code": -32602, "message": "Invalid params", "data": { "details": "参数 'expression' 不能为空" } } }
4. 通知消息(Notification)
服务器主动推送的消息(无需响应):
json{ "jsonrpc": "2.0", "method": "notifications/progress", "params": { "progress": 0.5, "message": "处理中..." } }
常用方法类型
tools/list - 获取可用工具列表
json{ "jsonrpc": "2.0", "id": "req-001", "method": "tools/list" }
resources/list - 获取可用资源列表
json{ "jsonrpc": "2.0", "id": "req-002", "method": "resources/list" }
resources/read - 读取资源内容
json{ "jsonrpc": "2.0", "id": "req-003", "method": "resources/read", "params": { "uri": "file:///data/config.json" } }
prompts/list - 获取提示词列表
json{ "jsonrpc": "2.0", "id": "req-004", "method": "prompts/list" }
错误代码
MCP 定义了标准的错误代码:
| 代码 | 名称 | 描述 |
|---|---|---|
| -32700 | Parse error | JSON 解析错误 |
| -32600 | Invalid Request | 无效的请求 |
| -32601 | Method not found | 方法不存在 |
| -32602 | Invalid params | 无效的参数 |
| -32603 | Internal error | 内部错误 |
| -32000 | Server error | 服务器错误 |
内容类型(Content Types)
MCP 支持多种内容类型:
json{ "type": "text", "text": "纯文本内容" }
json{ "type": "image", "data": "base64-encoded-image-data", "mimeType": "image/png" }
json{ "type": "resource", "uri": "file:///data/report.pdf", "mimeType": "application/pdf" }
消息流(Message Streaming)
对于长时间运行的操作,支持流式响应:
json{ "jsonrpc": "2.0", "id": "req-005", "method": "tools/call", "params": { "name": "generate_report", "arguments": { "stream": true } } }
最佳实践:
- 唯一 ID:每个请求必须有唯一的 ID
- 类型验证:严格验证参数类型和格式
- 错误处理:提供详细的错误信息和数据
- 超时处理:实现请求超时机制
- 日志记录:记录所有消息用于调试和审计
理解 MCP 的消息格式对于实现兼容的服务器和客户端至关重要。