跳转至

Mini JSON-RPC 2.0

通用 JSON-RPC 2.0 库,transport-agnostic(可换 stdio / WebSocket / HTTP)。 7 测试场景:request / notification / method-not-found / invalid-params / parse-error / batch / concurrent。

文件

mini-json-rpc/
├── src/
│   ├── jsonrpc.ts  Types + Transport + Server + Client + parse/encode(~200 行)
│   └── cli.ts      7 测试场景(in-process transport)
└── README.md

npm install && npm start

真实代码对照

Demo 真实代码 简化
jsonrpc.ts mini-mcp-server/src/server.ts (180 行) 通用 + 跨 transport
协议层 MCP spec 引用 JSON-RPC 2.0 完整 RFC 7792
Error codes -32700 ~ -32603 全实现
Batch mcp 实际不用 本 demo 演示完整 batch

核心 4 件套

1️⃣ 3 种 message 类型

  • Request(有 id,期望 Response)
  • Notification(无 id,不响应)
  • Response(result 或 error)

2️⃣ Batch = 数组

[
  {"jsonrpc":"2.0","id":1,"method":"add","params":[1,2]},
  {"jsonrpc":"2.0","id":2,"method":"add","params":[3,4]}
]
单 round-trip 多次调用。Notification 在 batch 里也不响应

3️⃣ 5 个标准 Error Code

Code 含义 何时抛
-32700 Parse error JSON.parse 失败
-32600 Invalid Request 消息结构不对
-32601 Method not found 未注册
-32602 Invalid params 参数缺失/类型错
-32603 Internal error handler 抛错

4️⃣ Transport = 抽象接口

interface Transport {
  send(msg: string): void;          // 发送
  onMessage(handler): void;          // 接收
  close(): void;
}
实现任意 transport: - stdio(mcp 默认) - WebSocket(浏览器) - HTTP POST(web fetch) - in-process(本 demo 用)

7 场景输出

📌 Test 1: request / response (add 2 + 3) → 5
📌 Test 2: notification (no response)
📌 Test 3: method not found → -32601
📌 Test 4: invalid params (divide by 0) → -32602
📌 Test 5: parse error → -32700
📌 Test 6: batch (3 calls) → [3, 30, 20]
📌 Test 7: concurrent → [2, 4, 6]

进阶练习

  1. 加 WebSocket transport:用 ws 包实现
  2. 加 HTTP POST transport:fetch 端点 + Accept: application/json-rpc
  3. 加 cancellation:实现 $/cancelRequest(JSON-RPC 2.0 扩展)
  4. 加 schema validation:用 zod 验证 params
  5. 加 request middleware:logger / auth / rate limit
  6. 加 introspection:注册 _listMethods / _methodHelp 元方法

相关阅读