Skip to content

3 报文速查(抓包视角) ​

调试 MCP 时,日志里最常出现的是一串串 JSON-RPC 报文。看懂它们,就能判断连接卡在握手、能力协商、参数校验,还是工具内部执行。

这一篇按「速查手册」组织,配了大量原始报文。第一次读可以跳过,等写实现或排错时再回来查。叙事与概念在1.4 JSON-RPC 与2.4 生命周期,两代差异在版本演进。

一、读报文的三把尺子 ​

1.1 先认三种信封 ​

MCP 消息遵循 JSON-RPC 2.0,先看它属于哪一类:

类型关键字段是否带 id是否要回复
请求jsonrpc、id、method、params带要
响应jsonrpc、id、result 或 error带不回复
通知jsonrpc、method、params不带不回复
json
{"jsonrpc": "2.0", "id": 42, "method": "tools/list", "params": {}}
json
{"jsonrpc": "2.0", "method": "notifications/tools/list_changed"}

id 可以是字符串或整数,禁止用 null。2025-11-25 版要求同一会话内不重复使用已经用过的 id;2026-07-28 版放宽为不要与尚未收到响应的请求撞号。

尺子一:版本

协议版本是日期字符串,例如 2025-11-25,它决定字段形状和错误码含义。2025-11-25 版有三个位置会出现版本:initialize 请求的 params.protocolVersion(客户端支持)、响应的 result.protocolVersion(服务端选定)、HTTP 头 MCP-Protocol-Version(后续每个请求都带)。2025 的 stdio 靠握手结果确定;2026-07-28 版把版本放进每个请求的 _meta,HTTP 头仍要带且必须与 body 一致,不一致返回 -32020。版本号按规范支持列表判断,别按语义化版本拆。

尺子二:方向

同一套信封两个方向都能用。判断方向,才知道谁该发响应、谁该处理取消。

方向典型方法
客户端 → 服务端initialize、tools/*、resources/*、prompts/*
服务端 → 客户端sampling/createMessage、elicitation/create、roots/list
双向通知notifications/progress、notifications/cancelled
服务端 → 客户端通知三组 list_changed、notifications/resources/updated、notifications/message

2026-07-28 版不再允许服务端在连接上反向发请求,原先的反向请求改为嵌在 tools/call 结果里,由客户端带答案重试。抓 2026 代的包时,看到 resultType: "input_required" 就属于这种多轮往返。

1.2 尺子三:能力 ​

能力(capability)在握手时交换,双方只使用协商成功的部分。

方法需要的能力
tools/list、tools/call服务端 tools
resources/list、resources/templates/list、resources/read服务端 resources
resources/subscribe服务端 resources.subscribe
prompts/list、prompts/get服务端 prompts
logging/setLevel服务端 logging

listChanged 和 subscribe 是子能力。声明了 resources: {"subscribe": true},客户端才能订阅;声明了 tools: {"listChanged": true},客户端才该期待工具列表变更通知。

抓包里的方法名是 tools/call、resources/read、prompts/get。callTools 之类是代码里的俗称,过滤日志时用规范名。

二、initialize 握手报文 ​

请求

客户端必须先发 initialize,声明版本、能力和自身信息:

json
{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {
  "protocolVersion": "2025-11-25",
  "capabilities": {"roots": {"listChanged": true}, "sampling": {}, "elicitation": {"form": {}, "url": {}}},
  "clientInfo": {"name": "ExampleClient", "version": "1.0.0"}}}

响应

服务端返回自己选定的版本、能力和信息:

json
{"jsonrpc": "2.0", "id": 1, "result": {
  "protocolVersion": "2025-11-25",
  "capabilities": {"logging": {}, "prompts": {"listChanged": true}, "resources": {"subscribe": true, "listChanged": true}, "tools": {"listChanged": true}},
  "serverInfo": {"name": "ExampleServer", "version": "1.0.0"},
  "instructions": "Optional instructions for the client"}}

instructions 是给模型的使用说明,可选。capabilities 决定本次会话能调用哪些方法。

initialized 通知

客户端收到成功响应后,再发通知表示准备就绪:

json
{"jsonrpc": "2.0", "method": "notifications/initialized"}

顺序很重要:收到 initialize 响应前,客户端除 ping 外不应发请求;收到 notifications/initialized 前,服务端除 ping 和日志外不应发请求。2026-07-28 版删除了 ping。

版本不匹配

服务端支持则原样返回,否则返回一个自己支持的版本;客户端不支持该版本时应断开。协商失败示例:

json
{"jsonrpc": "2.0", "id": 1, "error": {
  "code": -32602,
  "message": "Unsupported protocol version",
  "data": {"supported": ["2024-11-05"], "requested": "1.0.0"}}}

HTTP 传输下,后续请求如果带了无效或不支持的 MCP-Protocol-Version,服务端必须返回 400。

2026-07-28 版移除了 initialize 握手,版本与能力改为每个请求自带;本节的握手报文适用于 2025-11-25 及更早的版本,新版见版本演进。

三、tools/list 与 tools/call ​

3.1 tools/list ​

发现工具用 tools/list,支持分页:

json
{"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}
json
{"jsonrpc": "2.0", "id": 2, "result": {
  "tools": [{
    "name": "get_weather",
    "description": "Get current weather information for a location",
    "inputSchema": {"type": "object", "properties": {"location": {"type": "string"}}, "required": ["location"]},
    "outputSchema": {"type": "object", "properties": {"temperature": {"type": "number"}, "conditions": {"type": "string"}}}
  }],
  "nextCursor": "next-page-cursor"}}

inputSchema 是参数 schema,outputSchema 可选;nextCursor 存在表示还有下一页,把它放进下一次请求的 params.cursor。

3.2 tools/call ​

调用工具用 tools/call,参数放在 arguments 对象里:

json
{"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {
  "name": "get_weather",
  "arguments": {"location": "New York"}}}
json
{"jsonrpc": "2.0", "id": 3, "result": {
  "content": [{"type": "text", "text": "{\"temperature\": 22.5, \"conditions\": \"Partly cloudy\"}"}],
  "structuredContent": {"temperature": 22.5, "conditions": "Partly cloudy"},
  "isError": false}}

content、structuredContent 与 isError

content 是内容块数组,常见类型有 text、image、audio、resource_link、resource。structuredContent 是结构化结果;声明了 outputSchema 时,服务端必须返回符合 schema 的结果,客户端应当校验,并在 content 里附一份序列化 JSON 文本以兼容旧客户端。isError 表示工具执行失败,与 JSON-RPC 的 error 分属两层。

3.3 协议错误与执行错误 ​

工具不存在、请求不符合 CallToolRequest schema、服务端内部故障,走协议错误:

json
{"jsonrpc": "2.0", "id": 4, "error": {"code": -32602, "message": "Unknown tool: invalid_tool_name"}}

参数格式不对、外部 API 失败、业务规则拒绝,走执行错误,JSON-RPC 层仍是成功响应,只有 isError 为 true:

json
{"jsonrpc": "2.0", "id": 5, "result": {
  "content": [{"type": "text", "text": "Invalid departure date: must be in the future."}],
  "isError": true}}

客户端应把执行错误交给模型改参数重试;协议错误也可以给模型看,但模型通常修不了请求结构。

list_changed

工具列表变化时,声明了 listChanged 的服务端发通知:

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

客户端收到后重新调用 tools/list。通知不带变更详情,也没有 id。2026-07-28 版要求客户端先通过 subscriptions/listen 订阅 toolsListChanged,服务端才会发这条通知。

四、resources 报文 ​

4.1 resources/list ​

资源用 URI 标识,列表同样支持分页:

json
{"jsonrpc": "2.0", "id": 6, "method": "resources/list", "params": {}}
json
{"jsonrpc": "2.0", "id": 6, "result": {
  "resources": [{"uri": "file:///project/src/main.rs", "name": "main.rs", "title": "Rust main file", "mimeType": "text/x-rust"}],
  "nextCursor": "next-page-cursor"}}

uri 是唯一标识,name 是程序名,title 是展示名。

resources/templates/list

带参数的资源用 URI 模板描述:

json
{"jsonrpc": "2.0", "id": 7, "method": "resources/templates/list", "params": {}}
json
{"jsonrpc": "2.0", "id": 7, "result": {
  "resourceTemplates": [{"uriTemplate": "file:///{path}", "name": "Project Files", "description": "Access files in the project directory", "mimeType": "application/octet-stream"}]}}

uriTemplate 遵循 RFC 6570。客户端把用户选的路径填进去,得到具体 URI,再调用 resources/read。

resources/read:文本

json
{"jsonrpc": "2.0", "id": 8, "method": "resources/read", "params": {"uri": "file:///project/src/main.rs"}}
json
{"jsonrpc": "2.0", "id": 8, "result": {
  "contents": [{"uri": "file:///project/src/main.rs", "mimeType": "text/x-rust", "text": "fn main() {\n    println!(\"Hello world!\");\n}"}]}}

resources/read:二进制

二进制资源放在 blob 字段,值是 base64:

json
{"jsonrpc": "2.0", "id": 9, "method": "resources/read", "params": {"uri": "file:///project/assets/logo.png"}}
json
{"jsonrpc": "2.0", "id": 9, "result": {
  "contents": [{"uri": "file:///project/assets/logo.png", "mimeType": "image/png", "blob": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="}]}}

同一个内容块里 text 和 blob 二选一,解码前先看 mimeType。

subscribe 与 updated

服务端声明 resources.subscribe 后,客户端可以订阅单个资源:

json
{"jsonrpc": "2.0", "id": 10, "method": "resources/subscribe", "params": {"uri": "file:///project/src/main.rs"}}

资源变化时服务端发通知:

json
{"jsonrpc": "2.0", "method": "notifications/resources/updated", "params": {"uri": "file:///project/src/main.rs"}}

通知只带 URI,客户端收到后重新 resources/read;官方示例没有规定确认响应的具体 result 形状。2026-07-28 版移除 resources/subscribe,改用 subscriptions/listen 的 resourceSubscriptions。

资源不存在:-32002

json
{"jsonrpc": "2.0", "id": 11, "error": {
  "code": -32002,
  "message": "Resource not found",
  "data": {"uri": "file:///nonexistent.txt"}}}

2026-07-28 版把资源不存在改成 -32602,新版实现不再发 -32002,客户端仍应接受旧服务端的 -32002。

五、prompts 报文 ​

prompts/list

提示模板由用户选择,常见形态是斜杠命令:

json
{"jsonrpc": "2.0", "id": 12, "method": "prompts/list", "params": {}}
json
{"jsonrpc": "2.0", "id": 12, "result": {
  "prompts": [{"name": "code_review", "title": "Request Code Review", "description": "Asks the LLM to analyze code quality", "arguments": [{"name": "code", "description": "The code to review", "required": true}]}]}}

arguments 描述模板参数,required 为 true 的必须提供。

5.1 prompts/get ​

json
{"jsonrpc": "2.0", "id": 13, "method": "prompts/get", "params": {
  "name": "code_review",
  "arguments": {"code": "def hello():\n    print('world')"}}}
json
{"jsonrpc": "2.0", "id": 13, "result": {
  "description": "Code review prompt",
  "messages": [{"role": "user", "content": {"type": "text", "text": "Please review this Python code:\ndef hello():\n    print('world')"}}]}}

messages 与对话消息同构,role 取 user 或 assistant,客户端拿到后直接放进对话。

list_changed 与错误

json
{"jsonrpc": "2.0", "method": "notifications/prompts/list_changed"}

客户端收到后重新拉取 prompts/list。模板名不存在或缺少必填参数返回 -32602,服务端内部错误返回 -32603。

六、通知报文 ​

6.1 progress ​

想接收进度,就在请求的 _meta 里放一个 progressToken:

json
{"jsonrpc": "2.0", "id": 14, "method": "tools/call", "params": {
  "name": "get_weather", "arguments": {"location": "New York"}, "_meta": {"progressToken": "weather-001"}}}

服务端可以随后发进度通知:

json
{"jsonrpc": "2.0", "method": "notifications/progress", "params": {
  "progressToken": "weather-001", "progress": 1, "total": 2, "message": "Geocoding location..."}}

最终仍然是一条正常响应:

json
{"jsonrpc": "2.0", "id": 14, "result": {"content": [{"type": "text", "text": "22.5 C, partly cloudy"}], "isError": false}}

progressToken 必须是字符串或整数,且在活动请求中唯一;progress 必须递增,total 可省略,两者允许浮点数。操作完成或任务进入终态后停止通知。

cancelled

json
{"jsonrpc": "2.0", "id": 15, "method": "tools/call", "params": {"name": "get_weather", "arguments": {"location": "New York"}}}
json
{"jsonrpc": "2.0", "method": "notifications/cancelled", "params": {"requestId": 15, "reason": "User requested cancellation"}}

接收方应停止处理、释放资源,不再为被取消的请求发响应。取消可能晚于响应到达,双方都要容忍竞态。initialize 不允许取消;任务式请求用 tasks/cancel。2026-07-28 的 Streamable HTTP 用关闭 SSE 流表示取消,stdio 仍用这条通知。

message

服务端通过 notifications/message 发结构化日志。客户端可以先用 logging/setLevel 设置最低级别,成功时返回空结果;2026-07-28 版删除该方法,改用每请求 _meta.logLevel。日志通知本身:

json
{"jsonrpc": "2.0", "method": "notifications/message", "params": {
  "level": "error", "logger": "database", "data": {"error": "Connection failed", "details": {"host": "localhost", "port": 5432}}}}

level 采用 syslog 八级:debug、info、notice、warning、error、critical、alert、emergency。data 可以是任意可序列化 JSON,日志里不要放凭据、密钥和个人身份信息。

6.2 三组 list_changed ​

json
{"jsonrpc": "2.0", "method": "notifications/tools/list_changed"}
json
{"jsonrpc": "2.0", "method": "notifications/resources/list_changed"}
json
{"jsonrpc": "2.0", "method": "notifications/prompts/list_changed"}

三组通知形状一样,客户端收到后分别重新拉取对应列表;服务端需在能力里声明 listChanged: true。2026-07-28 版要求先 subscriptions/listen 并打开对应的 *ListChanged 开关。

七、错误结构 ​

7.1 标准错误码 ​

码名称典型场景
-32700Parse error内容无法解析为 JSON
-32600Invalid RequestJSON 合法,但不符合 JSON-RPC 请求结构
-32601Method not found方法名不存在
-32602Invalid params参数结构、工具名、模板名不合法
-32603Internal error服务端内部故障
-32002Resource not found资源不存在(2025-11-25 及更早)
-32042URLElicitationRequiredError需要先完成 URL 模式 elicitation

前五个来自 JSON-RPC 2.0 标准。-32002 是 MCP 在资源规范里定义的;-32042 是 2025-11-25 版引入的 URL elicitation 专用码。

错误对象的解剖

错误响应固定是 error 对象,里面放 code、message,可选的 data 承载细节:

json
{"jsonrpc": "2.0", "id": 16, "error": {
  "code": -32602,
  "message": "Invalid params",
  "data": {"field": "arguments.location", "reason": "required"}}}

code 必须是整数,message 应当简短;data 的形状由具体错误决定,例如版本错误用 supported 和 requested。

保留区

JSON-RPC 2.0 把 -32000 到 -32099 留给实现自定义的服务端错误。MCP 在 2026-07-28 版的总览里又切了一刀:-32000 到 -32019 是历史遗留码,新代码不得再分配;-32020 到 -32099 是 MCP 规范专用。-32002 位于遗留区,但保留“资源不存在”的含义;-32042 只在 2025-11-25 版使用。应用自定义错误码应放在 -32768 到 -32000 之外。

三层错误:HTTP、JSON-RPC 与 isError

层载体典型例子含义
HTTP状态码400、403、404、405传输或会话层面的结果
JSON-RPCerror.code-32602、-32601、-32002请求、方法或协议状态有问题
工具结果result.isErrortrue工具执行失败,模型可以改参数重试

HTTP 层由传输规范决定:通知或响应被接受返回 202;Origin 非法返回 403;2025 的会话过期返回 404;GET 不提供 SSE 流返回 405;MCP-Protocol-Version 无效返回 400。2026-07-28 版还要求缺少必需 _meta 时返回 -32602 且 HTTP 400,缺少客户端能力时返回 -32021 且 HTTP 400,版本不支持返回 -32022 且 HTTP 400。HTTP 200 只说明交换完成,响应体仍可能是 JSON-RPC 错误或 isError: true;HTTP 400 也可能带完整错误体。排查时三层都要看。

八、2026-07-28 报文形态 ​

2026-07-28 的报文形态变化集中在:不再有 initialize 握手,每个请求在 _meta 里带版本与能力;每个结果带 resultType;服务端用 server/discover 公布能力;错误码新增 -32020、-32021、-32022。完整报文示例见版本演进。

九、抓包方法 ​

用 Inspector 看双向报文

MCP Inspector 提供 Web、CLI、TUI 三个客户端,底层是同一套连接逻辑。Web 界面的 Protocol 面板能看到每一帧请求、响应和通知:

bash
npx @modelcontextprotocol/inspector node path/to/server/index.js

CLI 适合脚本化验证,例如只拉工具列表:

bash
npx @modelcontextprotocol/inspector --cli node path/to/server/index.js --method tools/list

2026 年的 Inspector 把协议代际作为独立设置,取值为 legacy、auto、modern,默认是 legacy。CLI 和 TUI 可以用 --protocol-era 覆盖单个连接的设置;auto 先探测 server/discover,失败再回退到 initialize,modern 固定使用 2026-07-28。

stdio:stdout 只放 MCP 消息

stdio 传输按行分隔消息,每条消息一行 JSON,行内不能有真实换行。服务端的 stdout 只能写合法的 MCP 消息,调试日志必须写到 stderr:

text
stdout: {"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-11-25"}}    stderr: [debug] loaded 3 tools

JSON 字符串内部的换行写成 \n 转义,不会破坏分帧;很多“客户端解析失败”源于服务端在 stdout 打了 print("server started")。

9.1 用 curl 观察 SSE ​

Streamable HTTP 的客户端 POST 要在 Accept 里同时声明 JSON 和 SSE(Server-Sent Events)。假设已完成 initialize 并拿到 Mcp-Session-Id,后续请求带上会话 ID 和协商后的版本:

bash
curl -N -X POST https://api.example.com/mcp \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -H 'MCP-Protocol-Version: 2025-11-25' \
  -H 'Mcp-Session-Id: 1868a90c-...' \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"get_weather","arguments":{"location":"New York"}}}'

服务端选择 SSE 时,终端会看到一条条 data: 帧:

text
data: {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"..."}],"isError":false}}

data: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"weather-001","progress":1,"total":2}}

每条 data: 是一个完整 JSON-RPC 消息。通知或客户端响应的 POST 通常返回 202;GET 打开独立通知流时,服务端不支持会返回 405。-N 关闭 curl 缓冲。

读包顺序

  1. 看 id、method 和方向:有 method 无 id 是通知,有 method 有 id 是请求,有 id 无 method 是响应;再确认所需能力是否声明过。
  2. 看 result、error、isError 和版本:分清成功、协议错误和工具执行错误;2025 代查 initialize 与 HTTP 头,2026 代查每请求 _meta。

十、小结 ​

  • MCP 报文都是 JSON-RPC 2.0:请求带 id,响应回显 id,通知不带 id。
  • 读报文先看三件事:协议版本、消息方向、请求声明的能力。
  • 规范方法名是 tools/call、resources/read、prompts/get,按这些名字过滤日志。
  • 2025-11-25 版用 initialize 协商版本和能力,客户端收到响应后再发 notifications/initialized。
  • 工具结果用 content 承载可读内容,structuredContent 承载结构化数据;执行失败看 isError,请求结构问题看 JSON-RPC error。
  • 资源读取返回 text 或 blob,订阅后用 notifications/resources/updated 提醒重新读取;进度用 _meta.progressToken 关联,取消用 notifications/cancelled,日志用 notifications/message。
  • 错误分三层:HTTP 状态码、JSON-RPC 错误码、工具结果的 isError,排查时逐层确认。
  • 2026-07-28 的报文形态见版本演进。
  • 抓包优先用 Inspector 的 Protocol 面板;stdio 记住 stdout 只放 MCP 消息,HTTP 用 curl -N 看 data: 帧。

基于 VitePress 搭建 · 资料持续整理中