AI Wiki中文/EN

Agent and tool protocols: agree on a session before calling anything

智能体与工具协议

What a protocol between an AI application and its tools, or between two agents, must fix so that independent programs interoperate: lifecycle, one-round version negotiation, capabilities, discovery, two error channels, timeouts and cancellation, with MCP 2025-11-25 and A2A v1.0.1 as worked cases.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Two programs that have never met

A coding assistant wants to use a tool server that someone else wrote: a small program that can search a repository, read files and run tests. The two programs were built by different people, at different times, against different versions of the same published rules. Before calling a tool, the assistant must settle questions that have nothing to do with the tool itself. Which version of the rules are we both speaking? Does this server offer tools at all, or only data? How do I learn the tool names if there are hundreds of them? What happens if the list changes while we talk? How do I tell “the tool ran and reported a problem” from “you sent me nonsense”? If a call takes too long, how do I stop it, and what if the stop arrives after the work is done?

The article on function calling builds the receiving side of one call: a JSON-RPC envelope, schema checks, permission and confirmation layers, idempotency keys. This article is about the layer above that: the session protocol that two independently written programs follow so that calls can happen at all. It asks what such a protocol must fix and what it deliberately leaves to the application.

The main worked case is the Model Context Protocol (MCP), pinned to specification version 2025-11-25. MCP describes itself as an open protocol for connecting applications built on large language models to external data sources and tools; its authoritative requirements are based on a TypeScript schema, and it uses JSON-RPC 2.0 messages. Specification overview It says it takes inspiration from the Language Server Protocol, which standardized how editors gain support for programming languages. MCP aims to standardize how AI applications integrate context and tools. Specification overview By contrast, the Agent2Agent protocol (A2A), specification v1.0.1, addresses communication between agents rather than between an application and its tools. A2A §1 Both are published specifications maintained by their projects; this article makes no claim about their adoption. Everything in the code below is an original in-process simulation: it uses no model, network or real MCP software development kit.

What a session protocol adds to an envelope

Recall the envelope, then the contrast. JSON-RPC 2.0 calls itself a stateless, light-weight, transport-agnostic remote-procedure-call protocol that defines only data structures and processing rules. JSON-RPC §1 A request id may be a string, a number or null (null is discouraged), and a request without an id is a notification that must not be answered. JSON-RPC §4, §4.1 The function-calling article covers the rest of the envelope. MCP keeps the envelope but narrows it: request ids must be a string or an integer, must not be null, and must not have been used before by the same requestor in the same session; notifications must carry no id and must not be answered. Base protocol Version 2025-06-18 removed support for JSON-RPC batching. 2025-06-18 changes So MCP turns a stateless envelope into a stateful conversation, forbids the null id that JSON-RPC merely discourages, and drops batches that JSON-RPC allows.

Roles. MCP names three parties. The host is the AI application: it creates clients, enforces security policy and user consent, and aggregates context. Each client is a connector inside the host that holds one stateful session with exactly one server, a one-to-one relation. Servers are local processes or remote services that expose context and capabilities. Architecture A stated design principle is that a server should not be able to read the whole conversation or see into other servers; the full history stays with the host, which controls any interaction across servers. Architecture Note that the language model is not a party to the protocol at all. The model proposes tool calls through the host; the protocol runs between client and server.

Servers may offer three kinds of feature: resources (context and data), prompts (templated messages for users) and tools (functions for the model to execute). Clients may offer sampling (the server asks the host to run a model call), roots (filesystem or URI boundaries) and elicitation (the server asks for more information from the user). Specification overview

Lifecycle. A session has three phases: initialization, operation and shutdown. Initialization must be the first interaction. The client sends an initialize request with its protocol version, its capabilities and information about its implementation; the server answers with its own; the client then sends the notification notifications/initialized. Lifecycle Until the server has answered initialize, the client should send nothing but pings; until the server has received initialized, it should send nothing but pings and logging. Lifecycle There is no shutdown message. Shutdown uses the transport: for a subprocess, close its standard input, then send SIGTERM, then SIGKILL if needed; over HTTP, close the connection. Lifecycle

Version negotiation is one round. The client must send a version it supports, and should send its latest. If the server supports that version it must answer with the same one; otherwise it must answer with another version it supports, and should choose its latest. If the client does not support the answer, it should disconnect. Lifecycle Write c for the requested version, C for the set the client supports, S for the set the server supports and latest(S) for the newest element of S:

v∗={c,c∈S,latest⁡(S),c∉S,session continues  ⟺  v∗∈C.v^{*}=\begin{cases}c, & c\in S,\\ \operatorname{latest}(S), & c\notin S,\end{cases}\qquad \text{session continues}\iff v^{*}\in C .

There is no intersection step. Two programs can share an older version and still fail to connect, because the server proposes its own latest and the rules contain no counter-offer. Over HTTP, the client must then send the negotiated version in an MCP-Protocol-Version header on every later request; a server that receives an invalid or unsupported value must answer with HTTP 400, and a server that receives no header and has no other way to tell should assume 2025-03-26. Lifecycle; Transports

Capability negotiation decides which optional features exist in the session. Examples on the server side are tools, resources, prompts, logging, completions and tasks; on the client side roots, sampling, elicitation and tasks. Sub-capabilities include listChanged and subscribe. During operation both parties must use only negotiated capabilities and respect the negotiated version. Lifecycle; Architecture A method for an undeclared feature is therefore not a tool error; it is outside the session’s agreed vocabulary.

Discovery and change. A server that supports tools must declare the tools capability. Clients discover tools with tools/list, which supports pagination through a cursor parameter, and invoke them with tools/call; a server that declared listChanged should send notifications/tools/list_changed when its tool list changes. Tools For task listing the specification says cursors are opaque tokens; we did not read the separate pagination page and do not generalize further. With N tools and a page size s chosen by the server, a fresh client needs

pages=⌈Ns⌉.\text{pages}=\left\lceil \frac{N}{s}\right\rceil .

round trips. A tool definition has a name, an optional title, a description, an inputSchema that is a JSON Schema object (default dialect 2020-12, never null), and optionally an outputSchema and annotations. For a tool without parameters the specification recommends an object schema that sets additionalProperties to false. Tools; Base protocol Annotations, such as a hint that a tool only reads, must be treated as untrusted unless they come from a trusted server, and the specification says there should always be a human in the loop who can deny a tool invocation. Tools; Specification overview

Two error channels. MCP separates protocol errors, which are JSON-RPC errors for unknown tools, malformed requests or server failures (its example uses −32602), from tool execution errors, which come back inside a normal result with isError set to true: an upstream API failed, the input failed validation, a business rule refused. Clients should pass tool execution errors to the model so it can correct itself. Tools Version 2025-11-25 clarified that input validation errors belong in the second channel. Changelog The split matters because the model never sees the protocol layer directly: a result with isError is information the model can act on (“amount must be positive”), while a protocol error says the conversation itself went wrong.

Transports. MCP defines two standard transports. With stdio, the server is a subprocess; messages are newline-delimited and must not contain embedded newlines; standard output carries only MCP messages, and standard error may carry logs. With Streamable HTTP, one endpoint accepts POST and GET, responses may use Server-Sent Events streams, a server may assign an MCP-Session-Id, and a client can resume a stream with Last-Event-ID. Clients should support stdio whenever possible, and a custom transport must preserve the message format and lifecycle. Transports Streamable HTTP replaced the HTTP-with-SSE transport of version 2024-11-05. Transports On Streamable HTTP a dropped connection should not be read as cancellation; to cancel, the client sends an explicit cancellation notification. Servers must validate the Origin header, answering 403 if it is invalid, to prevent DNS rebinding attacks, and should bind to localhost when running locally. Transports

Timeouts and cancellation. Implementations should set timeouts on all requests they send. On timeout, the sender should issue a cancellation notification and stop waiting; progress notifications may reset the clock, but a maximum timeout should always be enforced. Lifecycle Cancellation is the notification notifications/cancelled with the request id and an optional reason. It may arrive after processing finished, or after the response was sent; the receiver may then ignore it, and the sender should ignore any response that arrives afterwards. Clients must not cancel initialize. Cancellation The specification only says this race exists. To see its shape, take our own synthetic model, not part of the specification: one-way latency ℓ, client timeout T measured from sending, server processing time d. The response arrives at d + 2ℓ; the cancellation, sent at T, reaches the server at T + ℓ, while the work ends at ℓ + d. Then

outcome(d)={answered in time,d≤T−2ℓ,finished, but client already gave up,T−2ℓ<d≤T,cancelled while running,d>T.\text{outcome}(d)=\begin{cases} \text{answered in time}, & d\le T-2\ell,\\ \text{finished, but client already gave up}, & T-2\ell< d\le T,\\ \text{cancelled while running}, & d>T. \end{cases}

The middle zone is the uncomfortable one: the server did the work and any side effect happened, but the client has stopped listening. Retrying safely after that is the subject of agent failure recovery.

Durable tasks (experimental). Version 2025-11-25 added experimental tasks: durable state machines that wrap a request, with a task id generated by the receiver, polling through tasks/get and deferred results through tasks/result. Statuses are working, input_required, completed, failed and cancelled. A task must start in working, may move between working and input_required, and the terminal states completed, failed and cancelled must not change further. Tasks; Changelog

The agent-to-agent contrast. A2A describes itself as an open standard for communication between independent, possibly opaque agent systems that collaborate without access to each other’s internal state, memory or tools; it reuses HTTP, JSON-RPC 2.0 and Server-Sent Events. A2A §1, §1.2 Its unit of work is a Task generated by the server; clients cannot create a task id. In the specification’s prose, messages sent to a task in a terminal state (completed, failed, canceled, rejected) are rejected, while input-required and auth-required are interrupted, non-terminal states. A2A §3.1.1, §3.2.2, §3.4.2 An A2A server must make an Agent Card available, describing its identity, capabilities, skills, endpoint and authentication requirements; one discovery mechanism is a well-known URI under /.well-known/agent-card.json on the server’s domain. A2A §2.2, §8.1–8.2 Versions are Major.Minor; clients must send an A2A-Version header (an empty value is read as 0.3), and a server that does not support the requested version must return VersionNotSupportedError, JSON-RPC code −32009. The same operations are mapped to JSON-RPC, gRPC and HTTP+JSON bindings. A2A §3.6, §5.3–5.4 Its appendix positions MCP as agent-to-tool or agent-to-resource and A2A as agent-to-agent: complementary, since an A2A server agent may itself use MCP to reach its tools. A2A Appendix B Where MCP negotiates a version in one round inside the session, A2A carries the requested version on every request and fails it with a typed error.

What no protocol here guarantees. MCP’s security section lists user consent, data privacy, tool safety and controls on sampling as principles, and states that the protocol itself cannot enforce them; implementors should build consent and authorization flows. Specification overview Isolation between servers is likewise a design principle that the host must implement, not a property the wire format provides.

A scripted session in one process

The program below frames messages as newline-delimited JSON strings, the way stdio does, and passes them between a scripted client and a scripted server in the same process. It checks a subset of MCP 2025-11-25 rules: the narrowed request id, no batches, one-of result or error, stdio framing, the initialize/initialized handshake, one-round version negotiation, paginated tools/list, the two error channels and the experimental task statuses. It also classifies the timeout race with the three-zone model above. Two error codes are our own choices, not the specification’s: the specification says a client should not send a request before initialize and that ids must not be reused, but it does not prescribe the reply, so the toy answers both with −32600 and its own wording. The server supports versions 2025-11-25, 2025-06-18 and 2025-03-26, exposes five tools named tool_0 to tool_4, pages them two at a time, and tool_3 squares a non-negative integer 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))

The first block runs four handshakes. Every session also sends one tools/list before initialize, which the toy rejects with −32600 “initialize first”.

Client requestsClient supportsServer answersOutcome
2025-11-252025-11-252025-11-25operating
2026-01-01 (fictitious)2026-01-01, 2025-11-252025-11-25operating
2026-01-01 (fictitious)2026-01-01, 2025-06-182025-11-25client disconnects
2025-03-262025-03-262025-03-26operating

The third row is the boundary case of the negotiation rule: both sides support 2025-06-18, yet the session does not start, because the server proposes its own latest version and there is no second round.

The second block runs a complete session at 2025-11-25. Listing five tools at two per page takes 3 tools/list requests, matching ⌈5/2⌉ = 3. Then:

RequestChannelResult
tools/call tool_3, n = 7normal resultisError false, text 49
tools/call tool_3, n = −1tool execution errorisError true, “n must be a non-negative integer”
tools/call tool_9protocol error−32602, Unknown tool: tool_9
resources/listprotocol error−32601, method not found (resources capability not declared)

The trace holds 9 client requests (the early tools/list, initialize, three list pages, three calls and resources/list), 9 server responses and 1 client notification, 19 messages in total. A negative n is an input the model can fix, so it travels as data; an unknown tool name is a broken request, so it travels as a JSON-RPC error.

The third block feeds six malformed lines to the same server, and each is caught: a null id (allowed but discouraged in JSON-RPC, forbidden in MCP); a batch array (removed in 2025-06-18); a response carrying both result and error; a message with an embedded newline, which would split into two broken lines on stdio; a message declaring jsonrpc 1.0; and a reuse of request id 2 within the session, which the toy answers with −32600.

The fourth block takes ℓ = 0.2 and T = 3.0, so the zone boundaries are T − 2ℓ = 2.6 and T = 3.0. Of the ten processing times 0.5, 1.0, 2.0, 2.5, 2.7, 2.9, 3.2, 4.0, 6.0 and 9.0, four are answered in time, two (2.7 and 2.9) finish after the client gave up, and four are cancelled while running.

The fifth block checks task paths against the experimental 2025-11-25 rules. working → input_required → working → completed and working → cancelled are valid. completed → working is invalid because completed is terminal; a path starting in input_required is invalid because tasks must start in working; failed → cancelled is invalid because failed is terminal.

What the toy, and the protocols, leave out

The simulation has no real transport, no concurrency, no HTTP headers, no session ids and no authorization. It validates only the n argument rather than a full JSON Schema, implements neither resources nor prompts, and its server never sends requests to the client, so sampling, roots and elicitation are not exercised. Its timeout model assumes fixed, symmetric latency and a server that honours cancellation immediately; the specification allows a receiver to ignore a cancellation for a request that cannot be cancelled. Only the 2025-11-25 rules are modelled; the specification repository also holds earlier dated versions and a draft, which are not described here.

The larger limits belong to the protocols themselves. A well-formed session says nothing about whether a tool description is truthful, whether the annotations are honest, or whether the user agreed to a call; MCP states that it cannot enforce consent, privacy or tool safety, and leaves them to the host. Specification overview Server isolation holds only if the host keeps it: a host that pastes one server’s output into a request to another has leaked it, whatever the wire format says. A2A’s mention that messages may be made idempotent through a message id is a permission, not a de-duplication guarantee. A2A §3.3.1 And a shared wire format does not make agents cooperate correctly: misunderstanding, premature termination and missing verification happen above the protocol, which is why permissions, sandboxing and failure recovery are separate subjects.

Negotiate, page, route the error

  1. A host runs three MCP servers: files, a database and web search. How many MCP clients does it hold, and why can the web-search server not read the database server’s results directly?

    Answer: Three clients, one per server, because each client holds one session with exactly one server. The full conversation and any routing between servers stay in the host, so the search server sees only what the host chooses to send it. This is a stated design principle, not something the protocol enforces: a host that copies database output into a search query has leaked it, so isolation is the host’s job.

  2. A server exposes 23 tools and pages them 10 at a time. (a) How many tools/list round trips does a fresh client need? (b) Counting the initialize request and response and the initialized notification, how many messages are exchanged before the first tools/call? (c) The server then sends notifications/tools/list_changed and the list grows to 31 tools. How many more messages does a full re-listing take?

    Answer: (a) ⌈23/10⌉ = 3 pages. (b) 2 for initialize and its response, plus 1 initialized notification, plus 3 × 2 for the list requests and responses: 9 messages. (c) 1 notification plus ⌈31/10⌉ = 4 pages × 2 = 8 messages, so 9 more.

  3. A client requests 2026-01-01 and supports 2026-01-01 and 2025-06-18. The server supports 2025-11-25 and 2025-06-18. Does the session start, and what would fix it within the rules?

    Answer: No. The server does not support 2026-01-01, so it answers with its latest, 2025-11-25; the client does not support that and should disconnect, which is the third case in the example. The rules contain no counter-offer. Fixes: the client opens a new session whose initialize asks for 2025-06-18; the server implements 2026-01-01; or the server answers 2025-06-18, which is allowed, because choosing the latest is a SHOULD and any supported version satisfies the MUST.

  4. A tool create_invoice receives an amount of −5. Should the server return a JSON-RPC error or a result with isError true? And what if the client calls create_invoce, misspelled?

    Answer: A negative amount is an input validation or business problem, so the server returns a normal result with isError true and an explanation; version 2025-11-25 says input validation errors are tool execution errors, which reach the model and let it correct the call. The misspelled name is an unknown tool, a protocol error such as −32602. The asymmetry is deliberate: the model can act on “amount must be positive”, while a protocol error says the request itself was broken.

  5. You must connect (a) a coding assistant to a local git repository and (b) a travel-booking agent run by another company that needs hours and may ask the user to log in. Which protocol and features fit each?

    Answer: (a) MCP over stdio: a local server subprocess exposing tools and resources, with credentials taken from the environment rather than the HTTP authorization framework. (b) A2A: the remote agent is opaque, its work is a long-running task owned by the server, it can pause in input-required or auth-required, and the client finds it through its Agent Card. MCP’s experimental tasks also allow polling for long tool calls, but MCP is designed for a host to use a server’s capabilities, not for delegating to a peer agent.

  6. With ℓ = 0.1 s and T = 2.0 s in the toy timing model, classify processing times of 1.7, 1.85 and 2.5 s.

    Answer: T − 2ℓ = 1.8. 1.7 ≤ 1.8, so it is answered in time. 1.8 < 1.85 ≤ 2.0, so it finishes but the client has already given up; the work, and any side effect, happened. 2.5 > 2.0, so it is cancelled while running, provided the server honours the cancellation; the specification lets a receiver ignore it if the request cannot be cancelled.

Reading the specifications

We read the MCP 2025-11-25 specification as raw source files at a pinned repository commit dated before the fact cutoff: the overview, architecture, base protocol, lifecycle, transports, tools, cancellation, ping and tasks pages and the changelog. The authorization, resources, prompts, sampling, roots, elicitation, pagination, progress and logging pages and the TypeScript schema were not read, so nothing here describes them beyond the one-line definitions in the overview. MCP 2025-11-25 From the 2025-06-18 changelog we used the removal of batching and the version header. 2025-06-18 changes For A2A we read the v1.0.1 specification’s introduction, core concepts, error entries, task cancellation, blocking behaviour, idempotency, task and versioning sections, binding mappings, Agent Card discovery and its appendix on MCP; the generated data tables were not read, and A2A state names here come only from the prose. Older A2A versions differ in names and should not be mixed with v1.0.1. A2A v1.0.1 JSON-RPC 2.0 is used only for contrast. JSON-RPC 2.0

Open questions are practical. How should a host present annotations and tool descriptions it cannot trust? How should version negotiation evolve when one round leaves compatible programs unable to talk? How do experimental durable tasks interact with timeouts, cancellation and retries? And how should anyone test that two implementations agree beyond the happy path? A useful report on an integration states the negotiated version and capabilities, which error channel each failure used, the timeout and maximum timeout, and what the host does to obtain consent.

Make a prediction, then check

A client requests protocol version 2026-01-01 and also supports 2025-06-18; the server supports 2025-11-25 and 2025-06-18. Under the MCP 2025-11-25 rules, what happens?

Choose one answer

Learning objectives

  • Explain what a session protocol adds on top of the JSON-RPC envelope: lifecycle, one-round version negotiation, capability negotiation, paginated discovery, change notifications, timeouts and cancellation.
  • Distinguish protocol errors from tool execution errors and MCP's host–client–server model from A2A's agent-to-agent tasks, and state what consent and authorization a protocol cannot guarantee.

Prerequisites & connections

Explore related knowledge →

References

  1. Model Context Protocol Specification, version 2025-11-25 (pinned repository commit)
    Model Context Protocol contributors · 2025
  2. Model Context Protocol Specification 2025-06-18 — Key Changes (pinned repository commit)
    Model Context Protocol contributors · 2025
  3. Agent2Agent (A2A) Protocol Specification, tag v1.0.1
    A2A Project contributors · 2026
  4. JSON-RPC 2.0 Specification
    JSON-RPC Working Group · 2013

Version1 · Editorial status: Recorded technical checks completed

View technical check record (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.

  • Program output matches example.stdout.txt, both code blocks are byte-identical to example.py, and every quoted number matches the output.
  • Re-checked MCP 2025-11-25 at the pinned commit: one-round version negotiation, request-id rules, pagination, the two error channels, the cancellation race, tasks marked experimental; batching removed in 2025-06-18.
  • Re-checked A2A v1.0.1: server-generated task ids, terminal and interrupted state names from prose, empty A2A-Version read as 0.3, VersionNotSupportedError −32009, the Agent Card well-known URI, Appendix B.
  • The three-zone timeout model and the −32600 replies for pre-initialize requests and reused ids are clearly labelled as our own design choices, not the specification's; derivations and exercise answers are correct.
  • Gemini style edits changed wording only, not facts, hedges or attributions; zh and en still agree.

Source locations checked:

  • 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.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.