MCP-02_MCP 协议规范深度解析:消息格式与通信模型

发布时间:2026/9/10 9:33:50
MCP-02_MCP 协议规范深度解析:消息格式与通信模型 MCP 协议规范深度解析消息格式与通信模型摘要MCP 建立在 JSON-RPC 2.0 之上定义了完整的请求-响应-通知通信模型。本文从协议底层出发深入解析 MCP 的消息类型、能力协商机制、传输层设计结合源码级分析帮助读者建立对协议的完整认知。一、前言理解一个协议的最佳方式是阅读它的规范文档并亲手解析它的消息。MCP 的协议规范虽然篇幅不小但其核心设计遵循了简洁而优雅的原则基于 JSON-RPC 2.0通过能力协商实现功能发现通过传输层抽象实现环境适配。本文将带你从 JSON-RPC 2.0 基础开始逐步深入 MCP 的消息格式、能力协商、传输层等核心机制。每个知识点都配有真实的协议消息示例。二、JSON-RPC 2.0 基础MCP 选择 JSON-RPC 2.0 作为消息格式基础这是一个轻量级的远程过程调用协议。2.1 JSON-RPC 2.0 核心结构JSON-RPC 2.0 定义了三种消息类型类型结构特征是否需要响应Request包含idmethodparams是Response包含idresult或error-Notification包含methodparams无id否一个标准的 JSON-RPC 2.0 请求{jsonrpc:2.0,id:1,method:tools/call,params:{name:get_weather,arguments:{city:北京}}}对应的响应{jsonrpc:2.0,id:1,result:{content:[{type:text,text:北京晴25°C湿度 40%}]}}2.2 MCP 对 JSON-RPC 的扩展MCP 在标准 JSON-RPC 2.0 基础上做了几个关键扩展_meta字段在params中引入_meta用于传递协议元数据progressToken支持长时间操作的进度跟踪_meta中的命名空间使用io.modelcontextprotocol/前缀避免冲突{jsonrpc:2.0,id:2,method:tools/call,params:{name:long_running_task,arguments:{dataset:large_file.csv},_meta:{progressToken:task-001,io.modelcontextprotocol/clientInfo:{name:my-agent,version:1.0.0}}}}三、消息类型详解3.1 Request请求MCP 中的请求遵循 JSON-RPC 2.0 规范包含以下字段jsonrpc固定为2.0id请求标识符用于匹配响应整数或字符串method方法名如initialize、tools/list、tools/callparams方法参数可选MCP 定义的标准方法方法方向作用initializeClient → Server初始化握手协商能力tools/listClient → Server列出可用工具tools/callClient → Server调用指定工具resources/listClient → Server列出可用资源resources/readClient → Server读取指定资源resources/subscribeClient → Server订阅资源变更prompts/listClient → Server列出提示模板prompts/getClient → Server获取提示模板内容ping双向心跳检测sampling/createMessageServer → Client请求 LLM 推理roots/listServer → Client查询文件系统根目录elicitation/createServer → Client请求用户输入3.2 Response响应响应包含id与请求匹配和result或error成功响应{jsonrpc:2.0,id:1,result:{tools:[{name:get_weather,description:查询城市天气,inputSchema:{type:object,properties:{city:{type:string,description:城市名称}},required:[city]}}]}}错误响应{jsonrpc:2.0,id:1,error:{code:-32602,message:Invalid params,data:{details:Missing required parameter: city}}}MCP 定义的错误码继承自 JSON-RPC 2.0 并扩展错误码含义-32700Parse errorJSON 解析错误-32600Invalid Request无效请求-32601Method not found方法不存在-32602Invalid params参数无效-32603Internal error内部错误-32000 to -32099Server-defined errors服务器自定义错误3.3 Notification通知通知是没有id字段的消息不需要响应。MCP 大量使用通知来实现异步事件推送{jsonrpc:2.0,method:notifications/tools/list_changed,params:{}}常用通知类型通知方法方向触发场景notifications/initializedClient → Server客户端初始化完成notifications/cancelled双向请求被取消notifications/progress双向长操作进度更新notifications/resources/list_changedServer → Client资源列表变更notifications/tools/list_changedServer → Client工具列表变更notifications/prompts/list_changedServer → Client提示模板列表变更notifications/resources/updatedServer → Client订阅的资源内容更新notifications/messageServer → Client日志消息四、能力协商机制4.1 初始化握手MCP 连接的生命周期始于initialize握手。Client 发送自身能力和协议版本Server 响应自身能力和支持的协议版本Client → Serverinitialize 请求{jsonrpc:2.0,id:0,method:initialize,params:{protocolVersion:2025-11-25,capabilities:{roots:{listChanged:true},sampling:{},elicitation:{}},clientInfo:{name:claude-desktop,version:1.5.0}}}Server → Clientinitialize 响应{jsonrpc:2.0,id:0,result:{protocolVersion:2025-11-25,capabilities:{tools:{listChanged:true},resources:{subscribe:true,listChanged:true},prompts:{listChanged:true},logging:{}},serverInfo:{name:filesystem-server,version:2.1.0},instructions:这是一个文件系统 MCP Server提供文件读写能力。}}4.2 能力字段详解capabilities对象声明了各功能模块的支持情况Client 能力能力作用roots支持文件系统根目录查询listChanged表示会推送变更通知sampling支持 Server 发起的 LLM 推理请求elicitation支持 Server 向用户请求额外信息Server 能力能力作用tools暴露可调用工具listChanged表示工具列表可能动态变化resources暴露可读资源subscribe表示支持资源订阅prompts暴露提示模板logging支持日志级别配置4.3 版本协商Client 和 Server 必须就协议版本达成一致。如果 Server 不支持 Client 请求的版本它可以在响应中返回自己支持的版本列表{jsonrpc:2.0,id:0,result:{protocolVersion:2025-11-25,supportedVersions:[2025-11-25,2025-06-18],...}}五、传输层设计MCP 的传输层负责将 JSON-RPC 消息在 Client 和 Server 之间传递。协议规范定义了三种传输方式5.1 Stdio标准输入/输出Stdio 是最常用的传输方式特别适合本地部署的 MCP Server。工作原理Host 启动 Server 进程通过 stdin/stdout 进行通信每条消息以换行符\n分隔Server 的 stderr 用于日志输出不参与协议通信优势简单、无需网络配置、天然的进程隔离适用场景本地工具文件系统、Git、本地数据库MCP Server 进程Host 应用MCP Server 进程Host 应用stderr 用于日志输出启动进程 (stdin)initialize 请求 (stdin)initialize 响应 (stdout)notifications/initialized (stdin)tools/list 请求 (stdin)tools/list 响应 (stdout)tools/call 请求 (stdin)tools/call 响应 (stdout)5.2 SSEServer-Sent EventsSSE 是基于 HTTP 的单向推送协议MCP 使用它实现 Server 到 Client 的流式通信。工作原理Client 通过 HTTP POST 发送请求到/message端点Server 通过 SSE 连接推送响应和通知一个 SSE 连接可以承载多个请求-响应对优势支持远程部署、浏览器兼容、自动重连适用场景远程 MCP Server、Web 应用集成5.3 Streamable HTTP2026-07-28 新增Streamable HTTP 是 2026-07-28 版本引入的新传输方式旨在替代 SSE。核心变化移除了专用的/sse端点所有通信通过统一的/mcp端点Server 可选择是否使用 SSE 流式响应天然支持无状态部署无需 Session 管理请求示例POST /mcp HTTP/1.1 Content-Type: application/json MCP-Protocol-Version: 2026-07-28 Mcp-Method: tools/call Mcp-Name: search { jsonrpc: 2.0, id: 1, method: tools/call, params: { name: search, arguments: { q: MCP protocol } } }5.4 传输层对比特性StdioSSEStreamable HTTP部署方式本地进程远程 HTTP远程 HTTP通信方向双向stdin/stdout请求 POST SSE 推送灵活可选 SSE状态管理进程级连接级无状态可选浏览器支持❌✅✅负载均衡❌有限✅ 天然支持复杂度低中低引入版本2024-11-252024-11-252026-07-28六、代码示例消息解析器以下是一个 Python 实现的 MCP 消息解析器展示了协议消息的底层处理逻辑# mcp_message_parser.py# MCP 消息解析器 —— 演示 JSON-RPC 2.0 消息的解析与路由importjsonfromtypingimportAny,OptionalfromdataclassesimportdataclassdataclassclassMCPMessage:MCP 消息基类jsonrpc:str2.0method:Optional[str]Noneid:Optional[int|str]Noneparams:Optional[dict]Noneresult:Optional[Any]Noneerror:Optional[dict]NoneclassMCPMessageParser: MCP 消息解析器 负责将原始 JSON 字符串解析为结构化的 MCP 消息对象 staticmethoddefparse(raw:str)-MCPMessage:解析原始 JSON 字符串为 MCPMessagetry:datajson.loads(raw)exceptjson.JSONDecodeErrorase:# JSON-RPC 2.0 规范: -32700 表示 Parse errorraiseValueError(fParse error (-32700):{e})# 验证 jsonrpc 版本字段ifdata.get(jsonrpc)!2.0:raiseValueError(Invalid JSON-RPC version, expected 2.0)msgMCPMessage(jsonrpc2.0)# 判断消息类型: 有 id 字段的是 Request 或 Responseifidindata:msg.iddata[id]ifmethodindata:# 有 method id → Request请求msg.methoddata[method]msg.paramsdata.get(params,{})else:# 有 id 但无 method → Response响应iferrorindata:msg.errordata[error]else:msg.resultdata.get(result)else:# 无 id → Notification通知msg.methoddata.get(method)msg.paramsdata.get(params,{})returnmsgstaticmethoddefbuild_request(method:str,params:dictNone,msg_id:int1)-str:构建 Request 消息msg{jsonrpc:2.0,id:msg_id,method:method,}ifparams:msg[params]paramsreturnjson.dumps(msg)staticmethoddefbuild_response(result:Any,msg_id:int)-str:构建成功 Response 消息returnjson.dumps({jsonrpc:2.0,id:msg_id,result:result})staticmethoddefbuild_error(code:int,message:str,msg_id:int,data:AnyNone)-str:构建错误 Response 消息error{code:code,message:message}ifdata:error[data]datareturnjson.dumps({jsonrpc:2.0,id:msg_id,error:error})staticmethoddefbuild_notification(method:str,params:dictNone)-str:构建 Notification 消息无 idmsg{jsonrpc:2.0,method:method}ifparams:msg[params]paramsreturnjson.dumps(msg)# 使用示例 parserMCPMessageParser()# 解析一个 tools/list 请求raw_requestparser.build_request(methodtools/list,params{_meta:{progressToken:req-001}},msg_id42)print(fRequest:{raw_request})msgparser.parse(raw_request)print(f Method:{msg.method}, ID:{msg.id})# 解析一个成功响应raw_responseparser.build_response(result{tools:[{name:get_weather,description:查天气}]},msg_id42)print(fResponse:{raw_response})respparser.parse(raw_response)print(f Tools count:{len(resp.result[tools])})# 构建一个通知notificationparser.build_notification(methodnotifications/tools/list_changed)print(fNotification:{notification})代码解读MCPMessage数据类封装了 JSON-RPC 2.0 消息的所有可能字段parse()方法通过id和method字段的存在性来区分 Request、Response 和 Notification 三种消息类型build_*系列方法提供了消息构建的便利接口确保生成的 JSON 符合协议规范七、请求路由与方法命名空间MCP 使用/分隔的命名空间来组织方法名命名空间作用域示例initialize顶级初始化握手tools/*工具相关tools/list,tools/callresources/*资源相关resources/list,resources/read,resources/subscribeprompts/*提示模板相关prompts/list,prompts/getnotifications/*通知notifications/progress,notifications/cancelledsampling/*LLM 采样sampling/createMessageroots/*文件系统roots/list这种命名空间设计使得 MCP 可以方便地扩展新的功能域而不会与现有方法冲突。八、总结MCP 的协议设计体现了几个重要的工程原则基于成熟标准选择 JSON-RPC 2.0 作为消息格式避免了重新发明轮子最小化扩展仅在 JSON-RPC 2.0 基础上增加了_meta、progressToken等必要扩展传输层抽象将消息格式与传输方式解耦使得协议可以适配不同的部署环境能力协商通过初始化握手实现功能发现避免了硬编码的版本依赖异步友好通过 Notification 机制支持异步事件推送通过 progressToken 支持进度跟踪理解了这些底层机制我们就能更好地理解和开发 MCP Server 与 Client。在下一篇文章中我们将动手实践从零构建一个完整的 MCP Server。参考资料JSON-RPC Working Group. “JSON-RPC 2.0 Specification.”jsonrpc.org, https://www.jsonrpc.org/specificationAnthropic. “MCP Base Protocol — Lifecycle.”modelcontextprotocol.io, https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycleAnthropic. “MCP Base Protocol — Transports.”modelcontextprotocol.io, https://modelcontextprotocol.io/specification/2025-11-25/basic/transportsAnthropic. “MCP Architecture.”modelcontextprotocol.io, https://modelcontextprotocol.io/specification/2025-11-25/architectureModel Context Protocol Schema.github.com, https://github.com/modelcontextprotocol/specification/blob/main/schema/2025-11-25/schema.ts本系列覆盖AI 大模型基础、Agent 开发、MCP 协议、Skill 开发、RAG、模型微调、部署推理七大方向从入门到实战的全栈内容持续更新中。所有文章的 Markdown 源文件、可运行代码、高清配图已整理成完整资料包。 点赞 ⭐ 关注评论区扣「1」挨个发你领取方式