乐闻世界logo
搜索文章和话题

MCP 的消息格式是怎样的?有哪些常用的消息类型?

2月19日 21:35

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 定义了标准的错误代码:

代码名称描述
-32700Parse errorJSON 解析错误
-32600Invalid Request无效的请求
-32601Method not found方法不存在
-32602Invalid params无效的参数
-32603Internal error内部错误
-32000Server 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 } } }

最佳实践:

  1. 唯一 ID:每个请求必须有唯一的 ID
  2. 类型验证:严格验证参数类型和格式
  3. 错误处理:提供详细的错误信息和数据
  4. 超时处理:实现请求超时机制
  5. 日志记录:记录所有消息用于调试和审计

理解 MCP 的消息格式对于实现兼容的服务器和客户端至关重要。

标签:MCP