MCP 协议规范
概述
Model Context Protocol (MCP) 是基于 JSON-RPC 2.0 的协议规范,定义了 AI 模型与 MCP 服务器之间的通信标准。
协议基础
JSON-RPC 2.0
MCP 采用 JSON-RPC 2.0 作为底层通信协议:
- 请求-响应模型:客户端发送请求,服务器返回响应
- 批量请求:支持一次发送多个请求
- 通知消息:支持无需响应的通知
- 错误处理:标准化的错误格式
消息格式
所有消息都遵循以下结构:
{
"jsonrpc": "2.0",
"id": "唯一标识符",
"method": "方法名",
"params": {
// 方法参数
}
}
核心方法
1. 初始化
initialize
客户端首次连接时调用:
请求:
{
"jsonrpc": "2.0",
"id": "init-1",
"method": "initialize",
"params": {
"protocolVersion": "2024-11-05",
"capabilities": {
"tools": {},
"resources": {},
"logging": {}
},
"clientInfo": {
"name": "claude-code",
"version": "1.0.0"
}
}
}
响应:
{
"jsonrpc": "2.0",
"id": "init-1",
"result": {
"protocolVersion": "2024-11-05",
"capabilities": {
"tools": {
"listChanged": true
},
"resources": {
"subscribe": true,
"listChanged": true
},
"logging": {}
},
"serverInfo": {
"name": "my-mcp-server",
"version": "1.0.0"
}
}
}
initialized
初始化完成后通知:
{
"jsonrpc": "2.0",
"method": "notifications/initialized"
}
2. 工具管理
tools/list
列出可用工具:
请求:
{
"jsonrpc": "2.0",
"id": "tools-1",
"method": "tools/list",
"params": {
"cursor": "可选的分页游标"
}
}
响应:
{
"jsonrpc": "2.0",
"id": "tools-1",
"result": {
"tools": [
{
"name": "read_file",
"description": "读取文件内容",
"inputSchema": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "文件路径"
}
},
"required": ["path"]
}
}
],
"nextCursor": "下一页游标(如有)"
}
}
tools/call
调用工具:
请求:
{
"jsonrpc": "2.0",
"id": "call-1",
"method": "tools/call",
"params": {
"name": "read_file",
"arguments": {
"path": "/path/to/file.txt"
},
"_meta": {
"progressToken": "progress-123"
}
}
}
响应:
{
"jsonrpc": "2.0",
"id": "call-1",
"result": {
"content": [
{
"type": "text",
"text": "文件内容..."
},
{
"type": "image",
"data": "base64-encoded-image-data",
"mimeType": "image/png"
}
],
"isError": false
}
}
3. 资源管理
resources/list
列出可用资源:
请求:
{
"jsonrpc": "2.0",
"id": "res-1",
"method": "resources/list",
"params": {
"cursor": "分页游标"
}
}
响应:
{
"jsonrpc": "2.0",
"id": "res-1",
"result": {
"resources": [
{
"uri": "file:///home/user/config.json",
"name": "配置文件",
"description": "应用配置",
"mimeType": "application/json"
}
]
}
}
resources/read
读取资源内容:
请求:
{
"jsonrpc": "2.0",
"id": "read-1",
"method": "resources/read",
"params": {
"uri": "file:///home/user/config.json"
}
}
响应:
{
"jsonrpc": "2.0",
"id": "read-1",
"result": {
"contents": [
{
"uri": "file:///home/user/config.json",
"mimeType": "application/json",
"text": "{\"key\": \"value\"}"
}
]
}
}
resources/subscribe
订阅资源更新:
请求:
{
"jsonrpc": "2.0",
"id": "sub-1",
"method": "resources/subscribe",
"params": {
"uri": "file:///home/user/config.json"
}
}
4. 提示词模板
prompts/list
列出提示词模板:
响应:
{
"jsonrpc": "2.0",
"id": "prompts-1",
"result": {
"prompts": [
{
"name": "analyze_code",
"description": "分析代码质量",
"arguments": [
{
"name": "language",
"description": "编程语言",
"required": false
}
]
}
]
}
}
prompts/get
获取提示词内容:
请求:
{
"jsonrpc": "2.0",
"id": "prompt-1",
"method": "prompts/get",
"params": {
"name": "analyze_code",
"arguments": {
"language": "javascript"
}
}
}
响应:
{
"jsonrpc": "2.0",
"id": "prompt-1",
"result": {
"description": "分析 JavaScript 代码质量",
"messages": [
{
"role": "user",
"content": {
"type": "text",
"text": "请分析以下 JavaScript 代码的质量..."
}
}
]
}
}
通知消息
1. 进度通知
{
"jsonrpc": "2.0",
"method": "notifications/progress",
"params": {
"progressToken": "progress-123",
"progress": 0.5,
"total": null,
"message": "正在处理文件..."
}
}
2. 资源更新通知
{
"jsonrpc": "2.0",
"method": "notifications/resources/updated",
"params": {
"uri": "file:///home/user/config.json"
}
}
3. 工具列表变更通知
{
"jsonrpc": "2.0",
"method": "notifications/tools/list_changed"
}
4. 日志消息
{
"jsonrpc": "2.0",
"method": "notifications/message",
"params": {
"level": "info",
"logger": "my-server",
"data": {
"message": "操作完成"
}
}
}
错误处理
错误代码
| 代码 | 含义 | 描述 |
|---|---|---|
| -32700 | Parse error | 无效的 JSON |
| -32600 | Invalid Request | 无效的请求 |
| -32601 | Method not found | 方法不存在 |
| -32602 | Invalid params | 参数无效 |
| -32603 | Internal error | 内部错误 |
| -32000 | Server error | 服务器错误 |
错误响应格式
{
"jsonrpc": "2.0",
"id": "req-id",
"error": {
"code": -32602,
"message": "Invalid params",
"data": {
"details": "参数 'path' 不能为空"
}
}
}
内容类型
Text 内容
{
"type": "text",
"text": "纯文本内容"
}
Image 内容
{
"type": "image",
"data": "base64-encoded-image",
"mimeType": "image/png"
}
Resource 内容
{
"type": "resource",
"resource": {
"uri": "file:///path/to/file",
"mimeType": "application/json"
}
}
批量请求
发送批量请求
[
{
"jsonrpc": "2.0",
"id": "1",
"method": "tools/list"
},
{
"jsonrpc": "2.0",
"id": "2",
"method": "resources/list"
},
{
"jsonrpc": "2.0",
"method": "notifications/log",
"params": {
"level": "info",
"message": "开始批量操作"
}
}
]
批量响应
[
{
"jsonrpc": "2.0",
"id": "1",
"result": { /* tools list result */ }
},
{
"jsonrpc": "2.0",
"id": "2",
"result": { /* resources list result */ }
}
]
实现建议
1. 并发控制
- 使用请求 ID 追踪响应
- 实现请求队列管理
- 支持取消长时间运行的操作
2. 流式响应
对于长时间运行的操作:
{
"jsonrpc": "2.0",
"id": "stream-1",
"method": "tools/call",
"params": {
"name": "long_operation",
"arguments": {...},
"_stream": true
}
}
3. 状态管理
interface MCPServerState {
initialized: boolean;
capabilities: ServerCapabilities;
clientCapabilities?: ClientCapabilities;
subscriptions: Set<string>;
activeRequests: Map<string, RequestContext>;
}
安全考虑
1. 输入验证
- 验证所有输入参数
- 限制文件访问路径
- 检查资源权限
2. 输出过滤
- 过滤敏感信息
- 限制响应大小
- 清理危险内容
3. 访问控制
interface AccessControl {
allowedPaths: string[];
deniedPaths: string[];
maxFileSize: number;
allowedOperations: string[];
}
版本控制
协议版本
- 版本格式:YYYY-MM-DD
- 向后兼容性保证
- 废弃功能的迁移路径
服务器版本
服务器应在初始化时声明版本:
{
"serverInfo": {
"name": "my-server",
"version": "2.1.0"
}
}
测试规范
1. 协议一致性
- 验证消息格式
- 检查错误处理
- 测试边界条件
2. 性能测试
- 响应时间测试
- 并发请求测试
- 内存使用测试
3. 兼容性测试
- 不同客户端测试
- 版本兼容性测试
- 错误恢复测试