JSON-RPC 2.0基础

JSON-RPC 2.0概述

MCP协议基于JSON-RPC 2.0规范构建,这是一个轻量级的远程过程调用协议。JSON-RPC 2.0提供了简单、标准化的方式来进行客户端和服务器之间的通信。

JSON-RPC 2.0的核心特性

  • 无状态:每个请求都是独立的
  • 双向通信:支持客户端到服务器和服务器到客户端的调用
  • 批量请求:支持在单个HTTP请求中发送多个RPC调用
  • 错误处理:标准化的错误响应格式

基本消息结构

请求消息

{
  "jsonrpc": "2.0",
  "method": "method_name",
  "params": {
    "param1": "value1",
    "param2": "value2"
  },
  "id": "unique_request_id"
}

响应消息

{
  "jsonrpc": "2.0",
  "result": {
    "data": "response_data"
  },
  "id": "unique_request_id"
}

错误响应

{
  "jsonrpc": "2.0",
  "error": {
    "code": -32600,
    "message": "Invalid Request",
    "data": {
      "details": "Additional error information"
    }
  },
  "id": "unique_request_id"
}

通知消息(无需响应)

{
  "jsonrpc": "2.0",
  "method": "notification_method",
  "params": {
    "event": "something_happened"
  }
}

JSON-RPC 2.0错误码

错误码 消息 含义
-32700 Parse error 解析JSON时发生错误
-32600 Invalid Request 请求格式无效
-32601 Method not found 方法不存在
-32602 Invalid params 参数无效
-32603 Internal error 内部错误
-32000 to -32099 Server error 服务器错误(保留给实现定义)

MCP协议扩展

MCP特定的消息类型

MCP协议在JSON-RPC 2.0基础上定义了特定的方法和消息格式:

1. 初始化消息

{
  "jsonrpc": "2.0",
  "method": "initialize",
  "params": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
      "tools": {},
      "resources": {},
      "prompts": {}
    },
    "clientInfo": {
      "name": "MyMCPClient",
      "version": "1.0.0"
    }
  },
  "id": "init_001"
}

2. 初始化响应

{
  "jsonrpc": "2.0",
  "result": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
      "tools": {
        "listChanged": true
      },
      "resources": {
        "subscribe": true,
        "listChanged": true
      },
      "prompts": {
        "listChanged": true
      },
      "logging": {}
    },
    "serverInfo": {
      "name": "MyMCPServer",
      "version": "2.1.0"
    }
  },
  "id": "init_001"
}

MCP协议版本

当前版本:2024-11-05

  • 主要特性:工具、资源、提示的完整支持
  • 兼容性:向后兼容早期版本
  • 新增功能:增强的错误处理、改进的类型系统

版本协商

{
  "jsonrpc": "2.0",
  "method": "initialize",
  "params": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
      "experimental": {
        "customFeature": true
      }
    }
  },
  "id": "version_check"
}

工具相关消息

工具列表查询

请求

{
  "jsonrpc": "2.0",
  "method": "tools/list",
  "params": {},
  "id": "tools_list_001"
}

响应

{
  "jsonrpc": "2.0",
  "result": {
    "tools": [
      {
        "name": "web_search",
        "description": "在互联网上搜索信息",
        "inputSchema": {
          "type": "object",
          "properties": {
            "query": {
              "type": "string",
              "description": "搜索查询字符串"
            },
            "max_results": {
              "type": "integer",
              "description": "最大结果数量",
              "default": 10,
              "minimum": 1,
              "maximum": 100
            },
            "language": {
              "type": "string",
              "description": "搜索语言",
              "enum": ["zh", "en", "auto"],
              "default": "auto"
            }
          },
          "required": ["query"]
        }
      },
      {
        "name": "database_query",
        "description": "执行数据库查询",
        "inputSchema": {
          "type": "object",
          "properties": {
            "sql": {
              "type": "string",
              "description": "SQL查询语句"
            },
            "database": {
              "type": "string",
              "description": "数据库名称",
              "default": "default"
            },
            "timeout": {
              "type": "integer",
              "description": "查询超时时间(秒)",
              "default": 30,
              "minimum": 1,
              "maximum": 300
            }
          },
          "required": ["sql"]
        }
      }
    ]
  },
  "id": "tools_list_001"
}

工具调用

请求

{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "web_search",
    "arguments": {
      "query": "MCP协议最新发展",
      "max_results": 5,
      "language": "zh"
    }
  },
  "id": "tool_call_001"
}

响应

{
  "jsonrpc": "2.0",
  "result": {
    "content": [
      {
        "type": "text",
        "text": "搜索结果:\n\n1. MCP协议2024年最新规范发布\n   - 新增了增强的类型系统\n   - 改进了错误处理机制\n   - 支持更多的传输协议\n\n2. MCP生态系统快速发展\n   - 超过100个官方工具\n   - 多语言SDK支持\n   - 企业级部署案例\n\n3. 社区贡献活跃\n   - GitHub上超过1000个相关项目\n   - 月度活跃开发者超过5000人\n   - 丰富的文档和教程资源"
      },
      {
        "type": "resource",
        "resource": {
          "uri": "https://modelcontextprotocol.io/docs/latest",
          "text": "MCP协议官方文档"
        }
      }
    ],
    "isError": false
  },
  "id": "tool_call_001"
}

错误响应

{
  "jsonrpc": "2.0",
  "result": {
    "content": [
      {
        "type": "text",
        "text": "搜索服务暂时不可用,请稍后重试。"
      }
    ],
    "isError": true
  },
  "id": "tool_call_001"
}

工具列表变更通知

{
  "jsonrpc": "2.0",
  "method": "notifications/tools/list_changed",
  "params": {}
}

资源相关消息

资源列表查询

请求

{
  "jsonrpc": "2.0",
  "method": "resources/list",
  "params": {
    "cursor": null
  },
  "id": "resources_list_001"
}

响应

{
  "jsonrpc": "2.0",
  "result": {
    "resources": [
      {
        "uri": "file:///home/user/documents/report.pdf",
        "name": "月度报告",
        "description": "2024年11月月度业务报告",
        "mimeType": "application/pdf"
      },
      {
        "uri": "database://localhost/users",
        "name": "用户数据库",
        "description": "用户信息数据库表",
        "mimeType": "application/x-sql"
      },
      {
        "uri": "https://api.example.com/data",
        "name": "外部API数据",
        "description": "第三方服务提供的数据接口",
        "mimeType": "application/json"
      }
    ],
    "nextCursor": "cursor_abc123"
  },
  "id": "resources_list_001"
}

资源读取

请求

{
  "jsonrpc": "2.0",
  "method": "resources/read",
  "params": {
    "uri": "file:///home/user/documents/report.pdf"
  },
  "id": "resource_read_001"
}

响应

{
  "jsonrpc": "2.0",
  "result": {
    "contents": [
      {
        "uri": "file:///home/user/documents/report.pdf",
        "mimeType": "application/pdf",
        "text": "月度报告\n\n执行摘要\n本月业务表现良好,主要指标如下:\n- 营收增长15%\n- 用户增长12%\n- 客户满意度提升至92%\n\n详细分析\n..."
      }
    ]
  },
  "id": "resource_read_001"
}

资源订阅

订阅请求

{
  "jsonrpc": "2.0",
  "method": "resources/subscribe",
  "params": {
    "uri": "file:///home/user/documents/report.pdf"
  },
  "id": "resource_subscribe_001"
}

订阅响应

{
  "jsonrpc": "2.0",
  "result": {},
  "id": "resource_subscribe_001"
}

资源更新通知

{
  "jsonrpc": "2.0",
  "method": "notifications/resources/updated",
  "params": {
    "uri": "file:///home/user/documents/report.pdf"
  }
}

取消订阅

{
  "jsonrpc": "2.0",
  "method": "resources/unsubscribe",
  "params": {
    "uri": "file:///home/user/documents/report.pdf"
  },
  "id": "resource_unsubscribe_001"
}

提示相关消息

提示列表查询

请求

{
  "jsonrpc": "2.0",
  "method": "prompts/list",
  "params": {},
  "id": "prompts_list_001"
}

响应

{
  "jsonrpc": "2.0",
  "result": {
    "prompts": [
      {
        "name": "code_review",
        "description": "代码审查提示模板",
        "arguments": [
          {
            "name": "code",
            "description": "要审查的代码",
            "required": true
          },
          {
            "name": "language",
            "description": "编程语言",
            "required": false
          },
          {
            "name": "focus",
            "description": "审查重点",
            "required": false
          }
        ]
      },
      {
        "name": "document_summary",
        "description": "文档摘要生成模板",
        "arguments": [
          {
            "name": "document",
            "description": "要摘要的文档内容",
            "required": true
          },
          {
            "name": "length",
            "description": "摘要长度(短/中/长)",
            "required": false
          }
        ]
      }
    ]
  },
  "id": "prompts_list_001"
}

获取提示

请求

{
  "jsonrpc": "2.0",
  "method": "prompts/get",
  "params": {
    "name": "code_review",
    "arguments": {
      "code": "function calculateTotal(items) {\n  let total = 0;\n  for (let i = 0; i < items.length; i++) {\n    total += items[i].price * items[i].quantity;\n  }\n  return total;\n}",
      "language": "javascript",
      "focus": "性能和可读性"
    }
  },
  "id": "prompt_get_001"
}

响应

{
  "jsonrpc": "2.0",
  "result": {
    "description": "代码审查提示模板",
    "messages": [
      {
        "role": "user",
        "content": {
          "type": "text",
          "text": "请审查以下JavaScript代码,重点关注性能和可读性:\n\n```javascript\nfunction calculateTotal(items) {\n  let total = 0;\n  for (let i = 0; i < items.length; i++) {\n    total += items[i].price * items[i].quantity;\n  }\n  return total;\n}\n```\n\n请提供:\n1. 代码质量评估\n2. 潜在问题识别\n3. 改进建议\n4. 最佳实践推荐"
        }
      }
    ]
  },
  "id": "prompt_get_001"
}

日志相关消息

日志记录

请求

{
  "jsonrpc": "2.0",
  "method": "logging/setLevel",
  "params": {
    "level": "info"
  },
  "id": "logging_set_001"
}

日志消息

{
  "jsonrpc": "2.0",
  "method": "notifications/message",
  "params": {
    "level": "info",
    "logger": "mcp.server",
    "data": {
      "message": "工具调用成功",
      "tool": "web_search",
      "duration": 1250,
      "timestamp": "2024-11-05T10:30:45.123Z"
    }
  }
}

日志级别

级别 数值 描述
debug 0 调试信息
info 1 一般信息
notice 2 重要信息
warning 3 警告信息
error 4 错误信息
critical 5 严重错误
alert 6 告警信息
emergency 7 紧急情况

错误处理

MCP特定错误码

错误码 名称 描述
-32001 InvalidParams 参数无效
-32002 InternalError 内部错误
-32003 MethodNotFound 方法未找到
-32004 InvalidRequest 请求无效
-32005 ParseError 解析错误
-32006 ResourceNotFound 资源未找到
-32007 ToolNotFound 工具未找到
-32008 PromptNotFound 提示未找到
-32009 Unauthorized 未授权
-32010 Forbidden 禁止访问
-32011 TooManyRequests 请求过多
-32012 Timeout 超时

错误响应示例

工具未找到错误

{
  "jsonrpc": "2.0",
  "error": {
    "code": -32007,
    "message": "Tool not found",
    "data": {
      "toolName": "nonexistent_tool",
      "availableTools": ["web_search", "database_query", "file_read"]
    }
  },
  "id": "tool_call_error_001"
}

参数验证错误

{
  "jsonrpc": "2.0",
  "error": {
    "code": -32001,
    "message": "Invalid params",
    "data": {
      "field": "query",
      "reason": "Required parameter missing",
      "schema": {
        "type": "string",
        "description": "搜索查询字符串"
      }
    }
  },
  "id": "param_error_001"
}

权限错误

{
  "jsonrpc": "2.0",
  "error": {
    "code": -32009,
    "message": "Unauthorized",
    "data": {
      "resource": "database://sensitive/users",
      "requiredPermission": "read:sensitive_data",
      "userPermissions": ["read:public_data", "write:public_data"]
    }
  },
  "id": "auth_error_001"
}

批量请求

批量请求格式

[
  {
    "jsonrpc": "2.0",
    "method": "tools/list",
    "params": {},
    "id": "batch_001"
  },
  {
    "jsonrpc": "2.0",
    "method": "resources/list",
    "params": {},
    "id": "batch_002"
  },
  {
    "jsonrpc": "2.0",
    "method": "prompts/list",
    "params": {},
    "id": "batch_003"
  }
]

批量响应格式

[
  {
    "jsonrpc": "2.0",
    "result": {
      "tools": [
        {
          "name": "web_search",
          "description": "在互联网上搜索信息"
        }
      ]
    },
    "id": "batch_001"
  },
  {
    "jsonrpc": "2.0",
    "result": {
      "resources": [
        {
          "uri": "file:///example.txt",
          "name": "示例文件"
        }
      ]
    },
    "id": "batch_002"
  },
  {
    "jsonrpc": "2.0",
    "error": {
      "code": -32601,
      "message": "Method not found",
      "data": {
        "method": "prompts/list"
      }
    },
    "id": "batch_003"
  }
]

内容类型

文本内容

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

图片内容

{
  "type": "image",
  "data": "base64_encoded_image_data",
  "mimeType": "image/png"
}

资源引用

{
  "type": "resource",
  "resource": {
    "uri": "file:///path/to/file.pdf",
    "text": "PDF文档"
  }
}

嵌入内容

{
  "type": "embed",
  "source": "https://example.com/widget",
  "title": "嵌入式组件"
}

协议扩展机制

实验性功能

{
  "jsonrpc": "2.0",
  "method": "initialize",
  "params": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
      "experimental": {
        "customFeature": {
          "version": "1.0.0",
          "description": "自定义功能扩展"
        }
      }
    }
  },
  "id": "init_experimental"
}

自定义方法

{
  "jsonrpc": "2.0",
  "method": "custom/myMethod",
  "params": {
    "customParam": "value"
  },
  "id": "custom_001"
}

扩展数据格式

{
  "jsonrpc": "2.0",
  "result": {
    "content": [
      {
        "type": "text",
        "text": "标准文本内容"
      },
      {
        "type": "custom/chart",
        "data": {
          "chartType": "bar",
          "data": [1, 2, 3, 4, 5],
          "labels": ["A", "B", "C", "D", "E"]
        }
      }
    ]
  },
  "id": "custom_content_001"
}

最佳实践

1. 消息ID管理

// 生成唯一ID的示例
class MessageIdGenerator {
  constructor() {
    this.counter = 0;
    this.prefix = `client_${Date.now()}_`;
  }
  
  generate() {
    return `${this.prefix}${++this.counter}`;
  }
}

const idGenerator = new MessageIdGenerator();
const messageId = idGenerator.generate(); // "client_1699123456789_1"

2. 错误处理

// 错误处理示例
function handleMCPResponse(response) {
  if (response.error) {
    switch (response.error.code) {
      case -32007: // ToolNotFound
        console.error('工具未找到:', response.error.data.toolName);
        break;
      case -32009: // Unauthorized
        console.error('权限不足:', response.error.data.requiredPermission);
        break;
      default:
        console.error('未知错误:', response.error.message);
    }
    return null;
  }
  return response.result;
}

3. 参数验证

// 参数验证示例
function validateToolCall(toolName, arguments) {
  const toolSchema = getToolSchema(toolName);
  if (!toolSchema) {
    throw new Error(`工具 ${toolName} 不存在`);
  }
  
  const requiredParams = toolSchema.inputSchema.required || [];
  for (const param of requiredParams) {
    if (!(param in arguments)) {
      throw new Error(`缺少必需参数: ${param}`);
    }
  }
  
  return true;
}

4. 超时处理

// 超时处理示例
function callWithTimeout(method, params, timeout = 30000) {
  return Promise.race([
    mcpClient.call(method, params),
    new Promise((_, reject) => {
      setTimeout(() => {
        reject(new Error(`请求超时: ${method}`));
      }, timeout);
    })
  ]);
}

本章总结

本章详细介绍了MCP协议的技术规范和消息格式:

  1. JSON-RPC 2.0基础:了解了MCP协议的基础通信协议
  2. MCP协议扩展:学习了MCP在JSON-RPC基础上的扩展
  3. 消息类型:掌握了工具、资源、提示等各类消息的格式
  4. 错误处理:理解了标准化的错误处理机制
  5. 批量请求:学习了如何进行批量操作
  6. 扩展机制:了解了协议的扩展能力
  7. 最佳实践:掌握了实际开发中的注意事项

理解这些技术规范是实现MCP客户端和服务器的基础,为后续的实际开发奠定了坚实的理论基础。

下一章我们将学习如何搭建MCP开发环境并创建第一个MCP应用。