智能体与工具协议:先谈妥会话,再调用任何东西
Agent and tool protocols
AI 应用与工具之间、或两个智能体之间的协议必须固定哪些东西,独立编写的程序才能协同工作:生命周期、单轮版本协商、能力协商、发现、两条错误通道、超时与取消;以 MCP 2025-11-25 和 A2A v1.0.1 为实例。
agent-protocols两个素未谋面的程序
一个编程助手想使用别人写的工具服务器:一个能搜索代码仓库、读取文件、运行测试的小程序。这两个程序由不同的人、在不同的时间、按同一套公开规则的不同版本写成。在助手调用任何一个工具之前,它必须先解决一些与工具本身毫无关系的问题。我们双方讲的是哪个版本的规则?这个服务器到底提供工具,还是只提供数据?如果工具有几百个,我怎样得知它们的名字?交谈期间工具列表变了怎么办?我怎样区分“工具运行了并报告了一个问题”和“你发给我的东西没法理解”?如果一次调用太久,我怎样叫停它?如果叫停的消息在工作完成之后才到,又会怎样?
函数调用一文构建的是单次调用的接收端:JSON-RPC 信封、模式校验、权限与确认层、幂等键。本文讨论的是其上一层:两个独立编写的程序为保证调用顺利进行而共同遵守的会话协议。问题是:这样的协议必须固定什么,又有意把什么留给应用。
主要实例是模型上下文协议(Model Context Protocol,MCP),固定在规范版本 2025-11-25。MCP 自述为一个开放协议,用于把基于大语言模型的应用连接到外部数据源和工具;其权威要求以一份 TypeScript 模式为基础,消息采用 JSON-RPC 2.0。规范概览 它说自己借鉴了语言服务器协议(Language Server Protocol):后者统一了编辑器获得编程语言支持的方式,MCP 则希望统一上下文与工具接入各类 AI 应用的方式。规范概览 对照实例是 Agent2Agent 协议(A2A),规范版本 v1.0.1,它处理的是智能体之间的通信,而不是应用与工具之间的通信。A2A 第 1 节 两者都是由各自项目维护的已发布规范;本文不对其实际采用情况作判断。下面代码中的一切都是原创的进程内模拟:没有用到模型、网络或真实的 MCP 软件开发包。
会话协议在信封之上增加了什么
先回顾信封,再看对比。JSON-RPC 2.0 称自己是一个无状态、轻量、与传输方式无关的远程过程调用协议,只定义数据结构和处理规则。JSON-RPC 第 1 节 请求 id 可以是字符串、数或 null(不鼓励用 null),没有 id 的请求是通知,不得回复。JSON-RPC 第 4、4.1 节 信封的其余部分见函数调用一文。MCP 保留了信封,但收紧了规则:请求 id 必须是字符串或整数,不得为 null,并且同一请求方在同一会话中不得重复使用;通知不得携带 id,也不得回复。基础协议 2025-06-18 版本移除了对 JSON-RPC 批量的支持。2025-06-18 变更 于是 MCP 把一个无状态信封变成了有状态的对话,禁止了 JSON-RPC 只是不鼓励的 null id,并去掉了 JSON-RPC 允许的批量。
角色。MCP 规定了三方。宿主是 AI 应用:它创建客户端,执行安全策略和用户同意,并汇总上下文。每个客户端是宿主内部的一个连接器,与恰好一个服务器保持一个有状态会话,是一对一关系。服务器是对外提供上下文与能力的本地进程或远程服务。架构 规范列出的一条设计原则是:服务器不应能读到整个对话,也不应能看到其他服务器的内部;完整历史留在宿主,由宿主控制跨服务器的交互。架构 注意语言模型根本不是协议的一方。模型通过宿主提出工具调用;协议运行在客户端与服务器之间。
服务器可以提供三类功能:资源(上下文与数据)、提示模板(供用户使用的模板化消息)和工具(供模型执行的函数)。客户端可以提供采样(服务器请宿主运行一次模型调用)、根目录(文件系统或 URI 边界)和信息征询(服务器向用户索取更多信息)。规范概览
生命周期。一个会话有三个阶段:初始化、运行和关闭。初始化必须是第一次交互。客户端发送 initialize 请求,附上它的协议版本、能力和实现信息;服务器以自己的相应信息回复;随后客户端发送通知 notifications/initialized。生命周期 在服务器回复 initialize 之前,客户端除 ping 外不应发送其他请求;在服务器收到 initialized 之前,它除 ping 和日志外不应发送其他请求。生命周期 没有关闭消息。关闭借助传输层完成:对子进程,先关闭其标准输入,再发 SIGTERM,必要时发 SIGKILL;对 HTTP,关闭连接即可。生命周期
版本协商只有一轮。客户端必须发送一个自己支持的版本,并且应发送最新的。如果服务器支持该版本,必须原样回复;否则必须回复另一个自己支持的版本,并且应选最新的。如果客户端不支持这个回复,应断开连接。生命周期 记 c 为所请求的版本,C 为客户端支持的集合,S 为服务器支持的集合,latest(S) 为 S 中最新的元素:
其中没有求交集的步骤。两个程序可能共同支持某个较旧版本,却仍然连不上,因为服务器提出的是它自己的最新版本,而规则里没有还价这一步。在 HTTP 上,客户端此后必须在每个请求中用 MCP-Protocol-Version 头带上协商好的版本;服务器收到无效或不支持的值时必须回复 HTTP 400,没有收到该头且无从判断时应假定为 2025-03-26。生命周期;传输
能力协商决定会话中存在哪些可选功能。服务器一侧的例子有 tools、resources、prompts、logging、completions 和 tasks;客户端一侧有 roots、sampling、elicitation 和 tasks。子能力包括 listChanged 和 subscribe。运行期间双方都必须只使用已协商的能力,并遵守已协商的版本。生命周期;架构 因此,调用一个未声明功能的方法并不是工具错误,而是超出了本次会话约定的词汇。
发现与变更。支持工具的服务器必须声明 tools 能力。客户端用 tools/list 发现工具,它支持通过 cursor 参数分页;用 tools/call 调用工具;声明了 listChanged 的服务器在工具列表变化时应发送 notifications/tools/list_changed。工具 对任务列表,规范说游标是不透明的标记;我们没有读单独的分页页面,不作进一步推广。若有 N 个工具,服务器选择的页大小为 s,新客户端需要
次往返。一个工具定义包含 name、可选的 title、description、inputSchema(一个 JSON Schema 对象,默认方言为 2020-12,不得为 null),以及可选的 outputSchema 和 annotations。对没有参数的工具,规范建议使用把 additionalProperties 设为 false 的对象模式。工具;基础协议 注解(例如表示某工具只读的提示)除非来自可信服务器,否则必须视为不可信;规范还说应始终有一个人在回路中,能够拒绝工具调用。工具;规范概览
两条错误通道。MCP 区分协议错误和工具执行错误。前者是 JSON-RPC 错误,用于未知工具、格式错误的请求或服务器故障(其示例用 −32602);后者放在一个正常结果里返回,并把 isError 设为 true,例如上游 API 失败、输入未通过校验、业务规则拒绝。客户端应把工具执行错误交给模型,让它自行纠正。工具 2025-11-25 版本澄清,输入校验错误属于第二条通道。变更说明 这种划分之所以重要,是因为模型从不直接看到协议层:带 isError 的结果是模型可以据以行动的信息(“金额必须为正”),而协议错误说明对话本身出了问题。
传输方式。MCP 定义了两种标准传输。stdio 方式下,服务器是一个子进程;消息以换行分隔,消息内部不得含有换行;标准输出只承载 MCP 消息,标准错误可以承载日志。Streamable HTTP(可流式 HTTP)方式下,一个端点同时接受 POST 和 GET,响应可以使用服务器发送事件(SSE)流,服务器可以分配 MCP-Session-Id,客户端可以用 Last-Event-ID 恢复一个流。客户端应尽可能支持 stdio,自定义传输必须保留消息格式和生命周期。传输 Streamable HTTP 取代了 2024-11-05 版本中基于 HTTP 加 SSE 的传输。传输 在 Streamable HTTP 上,连接断开不应被理解为取消;要取消,客户端须发送显式的取消通知。服务器必须校验 Origin 头,无效时回复 403,以防 DNS 重绑定攻击;在本地运行时应绑定到 localhost。传输
超时与取消。实现应为发出的所有请求设置超时。超时后,发送方应发出取消通知并停止等待;进度通知可以重置计时,但始终应强制一个最大超时。生命周期 取消是通知 notifications/cancelled,携带请求 id 和可选的原因。它可能在处理完成之后、甚至在响应已发出之后才到达;此时接收方可以忽略它,而发送方应忽略此后到达的任何响应。客户端不得取消 initialize。取消 规范只说这种竞争存在。为了看清它的形状,我们用一个自己的合成模型(不属于规范):单程延迟 ℓ,客户端从发送时起计的超时 T,服务器处理时间 d。响应在 d + 2ℓ 时到达;取消在 T 时发出,于 T + ℓ 到达服务器,而工作在 ℓ + d 时结束。于是
三种结果依次是:按时得到回复;已经完成,但客户端已经放弃;运行中被取消。中间区间最麻烦:服务器做完了工作,副作用已经发生,客户端却已不再等待。此后如何安全重试,是智能体失败恢复一文的主题。
持久任务(实验性)。2025-11-25 版本加入了实验性的任务:包裹一个请求的持久状态机,任务 id 由接收方生成,通过 tasks/get 轮询,通过 tasks/result 获取延后的结果。状态有 working、input_required、completed、failed 和 cancelled。任务必须从 working 开始,可以在 working 与 input_required 之间往返;终止状态 completed、failed 和 cancelled 不得再转移。任务;变更说明
智能体对智能体的对照。A2A 自述为一个开放标准,用于独立的、可能不透明的智能体系统之间的通信,这些系统在无法访问彼此内部状态、记忆或工具的情况下协作;它复用 HTTP、JSON-RPC 2.0 和服务器发送事件。A2A 第 1、1.2 节 它的工作单位是由服务器生成的任务(Task);客户端不能自行创建任务 id。按规范正文的描述,发往终止状态任务(completed、failed、canceled、rejected)的消息会被拒绝,而 input-required 和 auth-required 是被中断的非终止状态。A2A 第 3.1.1、3.2.2、3.4.2 节 A2A 服务器必须提供一张智能体卡片(Agent Card),描述其身份、能力、技能、端点和认证要求;一种发现机制是服务器域名下 /.well-known/agent-card.json 这个 well-known URI。A2A 第 2.2、8.1—8.2 节 版本号为“主版本.次版本”;客户端必须发送 A2A-Version 头(空值按 0.3 理解),不支持所请求版本的服务器必须返回 VersionNotSupportedError,JSON-RPC 错误码 −32009。同一组操作被映射到 JSON-RPC、gRPC 和 HTTP+JSON 三种绑定。A2A 第 3.6、5.3—5.4 节 它的附录把 MCP 定位为智能体到工具或资源,把 A2A 定位为智能体到智能体,二者互补:一个 A2A 服务器智能体自身也可以用 MCP 访问它的工具。A2A 附录 B MCP 在会话内用一轮完成版本协商,A2A 则在每个请求上携带所请求的版本,并以带类型的错误拒绝不支持的版本。
这里的协议都不保证什么。MCP 的安全一节把用户同意、数据隐私、工具安全和采样控制列为原则,并说明协议本身无法强制执行它们;实现者应自行建立同意与授权流程。规范概览 服务器之间的隔离同样是一条需要宿主来实现的设计原则,而不是线上格式本身提供的性质。
一个进程内的脚本化会话
下面的程序把消息组织成以换行分隔的 JSON 字符串,就像 stdio 那样,并在同一进程内的脚本化客户端与脚本化服务器之间传递。它检查 MCP 2025-11-25 规则的一个子集:收紧后的请求 id、不允许批量、result 与 error 二选一、stdio 分帧、initialize/initialized 握手、单轮版本协商、分页的 tools/list、两条错误通道和实验性任务的状态。它还用上面的三区间模型对超时竞争分类。有两个错误码是我们自己的选择,而非规范规定:规范说客户端不应在 initialize 之前发送请求、id 不得重复使用,但没有规定如何回复,因此这个玩具程序对两者都回复 −32600,措辞也是自拟的。服务器支持 2025-11-25、2025-06-18 和 2025-03-26 三个版本,提供 tool_0 到 tool_4 五个工具,每页两个,其中 tool_3 计算非负整数 n 的平方。
"""Synthetic, in-process MCP-style session (spec version 2025-11-25 rules, simplified).
No model, no network, no real MCP SDK: a scripted client talks to a scripted
server through a list of newline-delimited JSON strings, the way the stdio
transport frames messages. The code checks a subset of the published rules.
"""
import json
import math
SERVER_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26'] # newest first
TOOLS = [{'name': f'tool_{i}', 'inputSchema': {'type': 'object'}} for i in range(5)]
PAGE = 2
def negotiate(requested, server_versions):
"""Echo the requested version if supported, otherwise offer the newest supported one."""
return requested if requested in server_versions else server_versions[0]
def classify(text):
"""Return (kind, message, problem) for one stdio line."""
if '\n' in text:
return 'reject', None, 'embedded newline breaks stdio framing'
try:
msg = json.loads(text)
except json.JSONDecodeError:
return 'reject', None, 'parse error (-32700)'
if isinstance(msg, list):
return 'reject', None, 'batch array (removed from MCP in 2025-06-18)'
if not isinstance(msg, dict) or msg.get('jsonrpc') != '2.0':
return 'reject', None, 'not a JSON-RPC 2.0 object (-32600)'
has_id = 'id' in msg
if 'method' in msg:
if not has_id:
return 'notification', msg, None
if msg['id'] is None or isinstance(msg['id'], bool) or not isinstance(msg['id'], (str, int)):
return 'reject', None, 'request id must be string or integer, never null (-32600)'
return 'request', msg, None
if has_id and (('result' in msg) != ('error' in msg)):
return 'response', msg, None
return 'reject', None, 'response needs exactly one of result/error (-32600)'
class Server:
def __init__(self):
self.state = 'new'
self.seen_ids = set()
self.version = None
self.log = []
def error(self, mid, code, text):
return {'jsonrpc': '2.0', 'id': mid, 'error': {'code': code, 'message': text}}
def ok(self, mid, result):
return {'jsonrpc': '2.0', 'id': mid, 'result': result}
def handle(self, line):
kind, msg, problem = classify(line)
if kind == 'reject':
self.log.append(('rejected', problem))
return None
if kind == 'notification':
if msg['method'] == 'notifications/initialized' and self.state == 'initializing':
self.state = 'operating'
self.log.append(('notification', msg['method']))
return None
if kind == 'response':
return None
mid, method = msg['id'], msg['method']
if mid in self.seen_ids:
self.log.append(('rejected', f'id {mid!r} reused in this session'))
return self.error(mid, -32600, 'duplicate request id')
self.seen_ids.add(mid)
if method == 'ping':
return self.ok(mid, {})
if method == 'initialize':
if self.state != 'new':
return self.error(mid, -32600, 'already initialized')
self.version = negotiate(msg['params']['protocolVersion'], SERVER_VERSIONS)
self.state = 'initializing'
return self.ok(mid, {'protocolVersion': self.version,
'capabilities': {'tools': {'listChanged': True}},
'serverInfo': {'name': 'toy-server', 'version': '0.1'}})
if self.state == 'new':
return self.error(mid, -32600, 'initialize first')
if method == 'tools/list':
start = int(msg.get('params', {}).get('cursor', '0'))
page = TOOLS[start:start + PAGE]
result = {'tools': [t['name'] for t in page]}
if start + PAGE < len(TOOLS):
result['nextCursor'] = str(start + PAGE)
return self.ok(mid, result)
if method == 'tools/call':
name = msg['params'].get('name')
args = msg['params'].get('arguments', {})
if name not in {t['name'] for t in TOOLS}:
return self.error(mid, -32602, f'Unknown tool: {name}')
if not isinstance(args.get('n'), int) or isinstance(args.get('n'), bool) or args['n'] < 0:
return self.ok(mid, {'content': [{'type': 'text', 'text': 'n must be a non-negative integer'}],
'isError': True})
return self.ok(mid, {'content': [{'type': 'text', 'text': str(args['n'] ** 2)}],
'structuredContent': {'square': args['n'] ** 2}, 'isError': False})
return self.error(mid, -32601, f'Method not found: {method}')
def send(server, msg, trace):
line = json.dumps(msg) if not isinstance(msg, str) else msg
trace.append(('C->S', line))
reply = server.handle(line)
if reply is not None:
trace.append(('S->C', json.dumps(reply)))
return reply
def session(client_version, client_supported):
server, trace = Server(), []
early = send(server, {'jsonrpc': '2.0', 'id': 0, 'method': 'tools/list'}, trace)
init = send(server, {'jsonrpc': '2.0', 'id': 1, 'method': 'initialize',
'params': {'protocolVersion': client_version, 'capabilities': {},
'clientInfo': {'name': 'toy-client', 'version': '0.1'}}}, trace)
agreed = init['result']['protocolVersion']
if agreed not in client_supported:
return server, trace, early, agreed, 'client disconnects'
send(server, {'jsonrpc': '2.0', 'method': 'notifications/initialized'}, trace)
return server, trace, early, agreed, 'operating'
print('== 1. Version negotiation ==')
cases = [('2025-11-25', ['2025-11-25']),
('2026-01-01', ['2026-01-01', '2025-11-25']),
('2026-01-01', ['2026-01-01', '2025-06-18']),
('2025-03-26', ['2025-03-26'])]
for requested, supported in cases:
srv, tr, early, agreed, outcome = session(requested, supported)
print(f'client asks {requested}, supports {supported} -> server answers {agreed}: {outcome}')
print('request sent before initialize ->', early['error'])
print('\n== 2. A full toy session ==')
srv, trace, _, _, _ = session('2025-11-25', ['2025-11-25'])
next_id, cursor, names, pages = 2, None, [], 0
while True:
params = {} if cursor is None else {'cursor': cursor}
r = send(srv, {'jsonrpc': '2.0', 'id': next_id, 'method': 'tools/list', 'params': params}, trace)
next_id += 1
pages += 1
names += r['result']['tools']
cursor = r['result'].get('nextCursor')
if cursor is None:
break
print(f'tools/list pages: {pages} (ceil({len(TOOLS)}/{PAGE}) = {math.ceil(len(TOOLS) / PAGE)}), tools: {names}')
calls = [('tool_3', {'n': 7}), ('tool_3', {'n': -1}), ('tool_9', {'n': 2})]
for name, args in calls:
r = send(srv, {'jsonrpc': '2.0', 'id': next_id, 'method': 'tools/call',
'params': {'name': name, 'arguments': args}}, trace)
next_id += 1
if 'error' in r:
print(f'tools/call {name} {args}: protocol error {r["error"]["code"]} {r["error"]["message"]}')
else:
print(f'tools/call {name} {args}: isError={r["result"]["isError"]} '
f'text={r["result"]["content"][0]["text"]!r}')
r = send(srv, {'jsonrpc': '2.0', 'id': next_id, 'method': 'resources/list'}, trace)
print('resources/list (capability not declared) ->', r['error']['code'], r['error']['message'])
kinds = {}
for direction, line in trace:
k = classify(line)[0]
kinds[(direction, k)] = kinds.get((direction, k), 0) + 1
print('message counts:', {f'{d} {k}': n for (d, k), n in sorted(kinds.items())}, 'total', len(trace))
print('\n== 3. Malformed inputs caught by the classifier ==')
bad = [
'{"jsonrpc": "2.0", "id": null, "method": "ping"}',
'[{"jsonrpc": "2.0", "id": 20, "method": "ping"}]',
'{"jsonrpc": "2.0", "id": 21, "result": {}, "error": {"code": 1, "message": "x"}}',
'{"jsonrpc": "2.0", "id": 22,\n "method": "ping"}',
'{"jsonrpc": "1.0", "id": 23, "method": "ping"}',
'{"jsonrpc": "2.0", "id": 2, "method": "ping"}',
]
for line in bad:
before = len(srv.log)
reply = srv.handle(line)
problem = srv.log[-1][1] if len(srv.log) > before else 'accepted'
shown = line.replace('\n', '\\n')
print(f'{shown:<84} -> {problem}' + (f' [reply code {reply["error"]["code"]}]' if reply else ''))
print('\n== 4. Timeout and cancellation race (one-way latency l, timeout T) ==')
l, T = 0.2, 3.0
durations = [0.5, 1.0, 2.0, 2.5, 2.7, 2.9, 3.2, 4.0, 6.0, 9.0]
zones = {'answered in time': 0, 'finished but client gave up': 0, 'cancelled while running': 0}
for d in durations:
if d + 2 * l <= T:
zones['answered in time'] += 1
elif d <= T:
zones['finished but client gave up'] += 1
else:
zones['cancelled while running'] += 1
print(f'boundaries: d <= T-2l = {T - 2 * l:.1f} answered; {T - 2 * l:.1f} < d <= T = {T:.1f} wasted; d > {T:.1f} cancelled')
print('durations', durations, '->', zones)
print('\n== 5. MCP task status transitions (2025-11-25, experimental) ==')
ALLOWED = {'working': {'input_required', 'completed', 'failed', 'cancelled'},
'input_required': {'working', 'completed', 'failed', 'cancelled'}}
def valid_path(path):
if path[0] != 'working':
return False, 'must start in working'
for a, b in zip(path, path[1:]):
if b not in ALLOWED.get(a, set()):
return False, f'{a} -> {b} not allowed'
return True, 'ok'
for p in [['working', 'input_required', 'working', 'completed'],
['working', 'cancelled'],
['working', 'completed', 'working'],
['input_required', 'completed'],
['working', 'failed', 'cancelled']]:
print(' -> '.join(p), ':', valid_path(p))
第一部分进行四次握手。每个会话还会在 initialize 之前发送一次 tools/list,玩具程序以 −32600 “initialize first” 拒绝它。
| 客户端请求 | 客户端支持 | 服务器回复 | 结果 |
|---|---|---|---|
| 2025-11-25 | 2025-11-25 | 2025-11-25 | 进入运行 |
| 2026-01-01(虚构) | 2026-01-01、2025-11-25 | 2025-11-25 | 进入运行 |
| 2026-01-01(虚构) | 2026-01-01、2025-06-18 | 2025-11-25 | 客户端断开 |
| 2025-03-26 | 2025-03-26 | 2025-03-26 | 进入运行 |
第三行是协商规则的边界情形:双方都支持 2025-06-18,会话却没有建立,因为服务器提出的是它自己的最新版本,而且没有第二轮。
第二部分在 2025-11-25 下运行一个完整会话。以每页两个列出五个工具,需要 3 次 tools/list 请求,与 ⌈5/2⌉ = 3 一致。然后:
| 请求 | 通道 | 结果 |
|---|---|---|
| tools/call tool_3,n = 7 | 正常结果 | isError 为 false,文本 49 |
| tools/call tool_3,n = −1 | 工具执行错误 | isError 为 true,“n must be a non-negative integer” |
| tools/call tool_9 | 协议错误 | −32602,Unknown tool: tool_9 |
| resources/list | 协议错误 | −32601,方法不存在(未声明 resources 能力) |
轨迹中有 9 个客户端请求(提前发出的 tools/list、initialize、三个列表分页、三次调用和 resources/list)、9 个服务器响应和 1 个客户端通知,共 19 条消息。负的 n 是模型可以修正的输入,所以作为数据传回;未知的工具名是一个坏掉的请求,所以作为 JSON-RPC 错误传回。
第三部分向同一服务器送入六行格式错误的消息,每一行都被拦下:null id(JSON-RPC 允许但不鼓励,MCP 禁止);批量数组(2025-06-18 已移除);同时带有 result 和 error 的响应;内部含有换行的消息,在 stdio 上会被拆成两行坏消息;声明 jsonrpc 为 1.0 的消息;以及在会话内重复使用请求 id 2,玩具程序以 −32600 回复。
第四部分取 ℓ = 0.2、T = 3.0,所以区间边界是 T − 2ℓ = 2.6 和 T = 3.0。在 0.5、1.0、2.0、2.5、2.7、2.9、3.2、4.0、6.0 和 9.0 这十个处理时间中,四个按时得到回复,两个(2.7 和 2.9)在客户端放弃之后才完成,四个在运行中被取消。
第五部分按实验性的 2025-11-25 规则检查任务路径。working → input_required → working → completed 和 working → cancelled 合法。completed → working 不合法,因为 completed 是终止状态;从 input_required 开始的路径不合法,因为任务必须从 working 开始;failed → cancelled 不合法,因为 failed 是终止状态。
玩具程序与协议各自遗漏了什么
这个模拟没有真实的传输、没有并发、没有 HTTP 头、没有会话 id,也没有授权。它只校验参数 n,而不是完整的 JSON Schema;没有实现资源和提示模板;服务器从不向客户端发送请求,因此采样、根目录和信息征询都没有被演示。它的超时模型假设延迟固定且对称、服务器立即响应取消;而规范允许接收方忽略针对无法取消之请求的取消。这里只建模了 2025-11-25 的规则;规范仓库还收有更早的各个带日期版本和一份草案,本文不作描述。
更大的局限属于协议本身。一个格式正确的会话不能说明工具描述是否真实、注解是否诚实、用户是否同意了某次调用;MCP 声明它无法强制执行同意、隐私或工具安全,这些留给宿主。规范概览 服务器隔离只有在宿主维持它时才成立:一个把某服务器的输出粘贴进发往另一服务器请求中的宿主已经泄露了它,无论线上格式如何规定。A2A 提到消息可以通过消息 id 实现幂等,这是一个“可以”,不是去重保证。A2A 第 3.3.1 节 共同的线上格式也不会让智能体正确协作:误解、过早终止和缺少验证都发生在协议之上,这正是权限、沙箱和失败恢复各自成为独立主题的原因。
协商、分页、分流错误
-
一个宿主运行三个 MCP 服务器:文件、数据库和网络搜索。它持有多少个 MCP 客户端?为什么网络搜索服务器不能直接读到数据库服务器的结果?
答案:三个客户端,每个服务器一个,因为每个客户端与恰好一个服务器保持一个会话。完整对话和服务器之间的任何路由都留在宿主,所以搜索服务器只能看到宿主选择发给它的内容。这是规范列出的设计原则,不是协议强制的东西:一个把数据库输出复制进搜索查询的宿主已经泄露了它,所以隔离是宿主的责任。
-
一个服务器提供 23 个工具,每页 10 个。(a) 新客户端需要多少次 tools/list 往返?(b) 把 initialize 请求与响应以及 initialized 通知计算在内,第一次 tools/call 之前共交换多少条消息?(c) 随后服务器发送 notifications/tools/list_changed,列表增长到 31 个工具。完整重新列出还需要多少条消息?
答案:(a) ⌈23/10⌉ = 3 页。(b) initialize 及其响应 2 条,加 1 条 initialized 通知,加列表请求与响应 3 × 2 条:共 9 条消息。(c) 1 条通知加 ⌈31/10⌉ = 4 页 × 2 = 8 条消息,所以再多 9 条。
-
客户端请求 2026-01-01,支持 2026-01-01 和 2025-06-18。服务器支持 2025-11-25 和 2025-06-18。会话能否建立?在规则之内怎样补救?
答案:不能。服务器不支持 2026-01-01,所以回复它的最新版本 2025-11-25;客户端不支持这个版本,应断开连接,这正是示例中的第三种情况。规则中没有还价一步。补救办法:客户端新开一个会话,在 initialize 中请求 2025-06-18;服务器实现 2026-01-01;或者服务器回复 2025-06-18,这是允许的,因为选择最新版本只是“应当”(SHOULD),任何受支持的版本都满足“必须”(MUST)。
-
工具 create_invoice 收到的金额为 −5。服务器应返回 JSON-RPC 错误,还是 isError 为 true 的结果?如果客户端调用的是拼错的 create_invoce 呢?
答案:负金额是输入校验或业务问题,所以服务器返回一个 isError 为 true、附有说明的正常结果;2025-11-25 版本说输入校验错误属于工具执行错误,它们会到达模型,使模型能够纠正调用。拼错的名字是未知工具,属于协议错误,例如 −32602。这种不对称是有意的:模型可以根据“金额必须为正”采取行动,而协议错误说明请求本身坏了。
-
你要连接 (a) 一个编程助手与本地 git 仓库,(b) 另一家公司运营的旅行预订智能体,它需要数小时,并可能要求用户登录。各自适合哪种协议和哪些功能?
答案:(a) 基于 stdio 的 MCP:一个本地服务器子进程提供工具和资源,凭据从环境中获取,而不是走 HTTP 授权框架。(b) A2A:远程智能体不透明,它的工作是由服务器拥有的长时间任务,可以停在 input-required 或 auth-required 状态,客户端通过其智能体卡片找到它。MCP 的实验性任务也允许对长时间工具调用进行轮询,但 MCP 的设计目的是让宿主使用服务器的能力,而不是把工作委托给对等的智能体。
-
在玩具计时模型中取 ℓ = 0.1 s、T = 2.0 s,对处理时间 1.7、1.85 和 2.5 s 分类。
答案:T − 2ℓ = 1.8。1.7 ≤ 1.8,按时得到回复。1.8 < 1.85 ≤ 2.0,已经完成但客户端已经放弃;工作以及任何副作用都已发生。2.5 > 2.0,在运行中被取消,前提是服务器响应取消;规范允许接收方在请求无法取消时忽略它。
读规范
我们在一个早于事实截止日期的固定仓库提交上,以原始源文件形式读了 MCP 2025-11-25 规范:概览、架构、基础协议、生命周期、传输、工具、取消、ping 和任务各页以及变更说明。授权、资源、提示模板、采样、根目录、信息征询、分页、进度和日志各页以及 TypeScript 模式没有读,因此本文除概览中的一句话定义外不描述它们。MCP 2025-11-25 从 2025-06-18 的变更说明中,我们用了移除批量和版本头两条。2025-06-18 变更 对 A2A,我们读了 v1.0.1 规范的引言、核心概念、错误条目、取消任务、阻塞行为、幂等性、任务与版本各节、绑定映射、智能体卡片发现及其关于 MCP 的附录;自动生成的数据表没有读,本文的 A2A 状态名只来自正文。A2A 的旧版本在命名上有差异,不应与 v1.0.1 混用。A2A v1.0.1 JSON-RPC 2.0 只用于对比。JSON-RPC 2.0
尚待解决的问题都很实际。宿主应如何呈现它无法信任的注解和工具描述?当一轮协商让本可兼容的程序无法交谈时,版本协商应如何演进?实验性的持久任务与超时、取消和重试如何相互作用?以及怎样测试两个实现在正常路径之外也一致?一份有用的集成报告应写明协商得到的版本与能力、每次失败走的是哪条错误通道、超时与最大超时,以及宿主如何取得用户同意。
先判断,再看解释
客户端请求协议版本 2026-01-01,并且也支持 2025-06-18;服务器支持 2025-11-25 与 2025-06-18。按 MCP 2025-11-25 的规则,会发生什么?
学习目标
- 说明会话协议在 JSON-RPC 信封之上增加了什么:生命周期、单轮版本协商、能力协商、分页发现、变更通知、超时与取消。
- 区分协议错误与工具执行错误、MCP 的宿主—客户端—服务器与 A2A 的智能体对智能体任务,并说明协议不能保证的同意与授权。
先修与延伸
查看知识关联图 →参考文献
- Model Context Protocol Specification, version 2025-11-25 (pinned repository commit)
Model Context Protocol contributors · 2025 - Model Context Protocol Specification 2025-06-18 — Key Changes (pinned repository commit)
Model Context Protocol contributors · 2025 - Agent2Agent (A2A) Protocol Specification, tag v1.0.1
A2A Project contributors · 2026 - JSON-RPC 2.0 Specification
JSON-RPC Working Group · 2013
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Claude · 2026-12-03 · Independent AI check (Claude subagent, not the author; not a human or expert review). Gemini-app style edits logged in gemini-edits-016a.json were applied to the opening sections before this check; research was done by a separate research subagent (facts.md) and the prose by a writer subagent. I ran example.py with python3 and diffed it against example.stdout.txt (identical), confirmed the python block in en.mdx and zh.mdx is byte-identical to example.py, and matched every quoted number (negotiation table, 3 list pages, 9/9/1 = 19 messages, six malformed lines, 4/2/4 timeout zones with boundaries 2.6 and 3.0, task paths). I re-derived the one-round negotiation rule, ceil(N/s), the three-zone timeout model (response at d+2l, cancellation reaches the server at T+l, work ends at l+d) and all exercise answers (9 and 9 messages, 1.8 boundary). I re-fetched the MCP 2025-11-25 raw MDX at commit 1b40699 (confirmed committed 2026-07-20 via the GitHub API): specification index, architecture, basic/index, lifecycle, transports, server/tools, cancellation and tasks pages and the changelog, and the 2025-06-18 changelog, checking the request-id rules, ping-only before initialize, version negotiation MUST/SHOULD wording and disconnect, MCP-Protocol-Version 400 and 2025-03-26 default, Origin 403, disconnection-is-not-cancellation, cursor pagination in tools/list and opaque cursors for tasks, the -32602 unknown-tool example and isError channel, input-validation clarification (SEP-1303), initialize not cancellable, tasks marked experimental with receiver-generated ids and the status rules, and batching removal in 2025-06-18. I re-read the A2A specification.md at the v1.0.1 tag commit 3303592 (2026-05-28): sections 1-1.2, terminal-state error entries, 3.2.2, 3.3.1, task-id generation, 3.6 versioning (empty header read as 0.3), the -32009 mapping, 8.1-8.2 and Appendix B; state names in the article come from prose only. I did not read the MCP authorization, resources, prompts, pagination or schema files, the A2A generated tables or the JSON-RPC page beyond what the writer cites. I compared zh and en section by section (same claims, numbers, equations, exercises and caveats) and checked data.json IDs against src/data/catalogue.txt and the quiz answer. The Gemini edits changed wording only; no fact, hedge or attribution changed.
- 示例程序输出与 example.stdout.txt 一致,中英文代码块与 example.py 逐字节相同,正文引用的数字均与输出相符。
- 按固定提交复核 MCP 2025-11-25:单轮版本协商、请求 id 规则、分页、两条错误通道、取消竞争、任务标为实验性;2025-06-18 移除批量。
- 复核 A2A v1.0.1:任务 id 由服务器生成、终止与中断状态名取自正文、A2A-Version 空值按 0.3、VersionNotSupportedError 为 −32009、智能体卡片 well-known URI、附录 B。
- 三区间超时模型和对提前请求、重复 id 回复 −32600 均明确标为本文自己的设计选择,并非规范规定;推导与练习答案正确。
- Gemini 风格修改只改措辞,未改变事实、限定语或出处;中英文仍一致。
核对的来源位置:
- Model Context Protocol Specification, version 2025-11-25 (pinned repository commit) · Raw MDX at commit 1b406997d2bf55a6801bbbaf601a24763a6f5569 (2026-07-20). Per the GitHub API the only later pre-cutoff commit touching docs/specification/2025-11-25 is e88ed95 (2026-07-28), a typo fix in the authorization page, which was not read. specification/index.mdx lines 7–121 (roles, features, LSP inspiration, security principles, protocol cannot enforce them); architecture/index.mdx lines 7–174 (host/client/server, 1:1 sessions, design principles incl. isolation, capability negotiation); basic/index.mdx lines 7–186 (request id string/integer, not null, not reused; notifications no id; auth for HTTP vs stdio; JSON Schema 2020-12 default); basic/lifecycle.mdx lines 7–286 (phases, initialize/initialized, ping-only before init, version negotiation, capability table, shutdown via transport, timeouts and maximum timeout, error example −32602); basic/transports.mdx lines 7–320 (stdio framing and stderr, Streamable HTTP POST/GET, Origin 403, 202 for notifications, SSE polling and retry field, disconnection is not cancellation, resumability via Last-Event-ID, MCP-Session-Id and 404 → re-initialize, MCP-Protocol-Version header and 2025-03-26 default, backwards compatibility, custom transports); server/tools.mdx lines 7–524 (model-controlled, human in the loop SHOULD, capability, tools/list with cursor, tools/call, list_changed, Tool fields, untrusted annotations, tool names, content types, structuredContent and outputSchema, protocol vs tool execution errors, security MUST/SHOULD lists); basic/utilities/cancellation.mdx lines 7–84; basic/utilities/ping.mdx lines 7–41; basic/utilities/tasks.mdx lines 7–32, 386–500, 700–722 (experimental status, requestor/receiver, status lifecycle, TTL, result retrieval, cancellation rules); changelog.mdx lines 7–49. NOT read: authorization, security_best_practices, resources, prompts, sampling, roots, elicitation, pagination, progress, logging, completion pages, tasks message-flow and error sections (lines 119–385, 500–699, 757–900), schema.ts/schema.json. Directory listing of docs/specification at the pinned commit shows 2024-11-05, 2025-03-26, 2025-06-18, 2025-11-25, draft.
- Model Context Protocol Specification 2025-06-18 — Key Changes (pinned repository commit) · docs/specification/2025-06-18/changelog.mdx lines 1–40 at the same commit: major change 1 removes JSON-RPC batching (PR #416); 2 structured tool output; 6 elicitation; 7 resource links; 8 MCP-Protocol-Version header; 9 SHOULD→MUST in lifecycle operation. Rest of the file (after line 40) and other 2025-06-18 pages not read.
- Agent2Agent (A2A) Protocol Specification, tag v1.0.1 · docs/specification.md at commit 3303592588e388e62e0f69f701af531d2f4e3991 (tag v1.0.1, committed 2026-05-28): lines 1–42 (§1–1.2), 125–160 (§2–3.1), 175 and 200/210 (terminal-state errors and stream closing), 264–285 (§3.1.5 Cancel Task), 446–448 (§3.2.2 blocking vs return_immediately), 490–497 (§3.3.1 idempotency), 600–646 (§3.4.1–3.4.3, server-generated taskId, contextId rules, input-required), 706–745 (§3.6 versioning), 1154–1200 (§5.2–5.4 method and error-code mappings incl. VersionNotSupportedError −32009), 1964–1985 (§8.1–8.2 Agent Card and well-known URI), 2229–2260 (§9.1–9.2) and 3598–3610 (Appendix B). §4 object tables are template placeholders rendered from a2a.proto and were not read; §6, §7, §10–§14 and Appendix A not read; a2a.proto not read.
- JSON-RPC 2.0 Specification · Re-fetched https://www.jsonrpc.org/specification on 2026-12-03 and read the header (origin 2010-03-26, updated 2013-01-04), §1 (stateless, transport agnostic), §2–3, §4–4.2 (id string/number/null, null discouraged; notifications unanswerable), §5–5.1 (result/error exclusivity, reserved codes −32768..−32000) and §6 (batches). Only §1, §4.1 and the null-id rule are used for contrast here; the full envelope is in function-calling.
相关主题