本文详细介绍 MCP 协议定义的 JSON-RPC 错误码(-32000 到 -32099 和 32600-32603),包括每个错误码的含义、常见原因和排查步骤。
MCP (Model Context Protocol) 使用 JSON-RPC 2.0 作为通信协议,定义了一套标准的错误码。本文提供完整的错误码参考和排查指南。
| 错误码 | 名称 | 说明 |
|---|---|---|
| -32700 | Parse error | JSON 解析失败 |
| -32600 | Invalid Request | 无效的请求格式 |
| -32601 | Method not found | 方法不存在 |
| -32602 | Invalid params | 无效的参数 |
| -32603 | Internal error | 内部错误 |
| 错误码 | 名称 | 说明 |
|---|---|---|
| -32000 | Server error | MCP Server 内部错误 |
| -32001 | Connection error | 连接错误 |
| -32002 | Timeout error | 操作超时 |
| -32003 | Resource not found | 资源不存在 |
| -32004 | Resource expired | 资源已过期 |
| -32005 | Invalid resource | 无效的资源 |
{
"jsonrpc": "2.0",
"error": {
"code": -32600,
"message": "Invalid Request: missing method field",
"data": {
"details": "The 'method' field is required"
}
},
"id": 1
}
import json
def send_request(method: str, params: dict = None):
"""发送 MCP 请求"""
request = {
"jsonrpc": "2.0",
"method": method,
"params": params or {},
"id": generate_id()
}
try:
json_str = json.dumps(request, ensure_ascii=False)
except TypeError as e:
raise ValueError(f"无法序列化请求: {e}")
response = send_to_server(json_str)
try:
return json.loads(response)
except json.JSONDecodeError as e:
raise ValueError(f"服务器响应格式错误: {e}")
def validate_mcp_params(method: str, params: dict):
"""验证 MCP 参数"""
# 定义每个方法的必需参数
required_params = {
"tools/list": [],
"tools/call": ["name"],
"resources/list": [],
"resources/read": ["uri"]
}
required = required_params.get(method, [])
missing = [p for p in required if p not in params]
if missing:
raise ValueError(
f"Missing required params for {method}: {missing}"
)
return True
Auto-repair applied and deterministic inspection checks passed.
排查流程完整
错误码参考准确