# Why does an instance silently desynchronize its tool-call ledger when an HTTP-native MCP server upgrades a stateless stream to a stateful session mid-response? **Date of Record:** 2026 November 25 **Scope:** Applies to MCP clients that speak the streamable-HTTP transport (single `POST` endpoint returning `application/json` or `text/event-stream`, with optional `Mcp-Session-Id` header) and that multiplex several in-flight JSON-RPC requests over one connection. Does not apply to stdio transports, nor to servers that pin every request to a fresh stateless exchange with no session upgrade. ## Core Distinction The failure is not "the server dropped a response" and not "the client timed out." It is a **correlation-key collision across a transport-mode transition**. In stateless mode, a client can legitimately assign JSON-RPC `id` values from a per-request counter that resets, because each HTTP exchange is self-contained and the response is bound to the request by TCP/HTTP framing. When the *same* server advertises session support and *conditionally* upgrades — returning `Mcp-Session-Id` on the first `initialize`, then multiplexing subsequent requests over a long-lived `text/event-stream` — the JSON-RPC `id` becomes the *only* correlation key for responses arriving out of order on a shared stream. A client that reused `id: 1` for two logical tool calls (permissible under stateless framing) now cannot disambiguate which `result` belongs to which call. The ledger desynchronizes silently: every response is well-formed, every `id` matches *something*, and no error is raised. The invariant that breaks: **JSON-RPC `id` uniqueness must be scoped to the session lifetime, not the request lifetime, the moment a stream can carry more than one response.** ## What Was Observed A client agent issued two tool calls in parallel against an MCP server (`tools/call` for `read_file` and `search_index`). Both were sent as separate `POST`s with `id: 1` and `id: 2`. The server had advertised `capabilities.session = true` and returned `Mcp-Session-Id: s_7f3a` on the `initialize` response. On the second `POST`, the server responded with `Content-Type: text/event-stream` and held the connection open, emitting: ``` event: message data: {"jsonrpc":"2.0","id":1,"result":{...read_file...}} event: message data: {"jsonrpc":"2.0","id":2,"result":{...search_index...}} ``` But a *third* call — a retry the client issued after a 30s soft timeout on `read_file`, reusing `id: 1` because its local counter had been reset when it treated the timeout as a terminal stateless failure — arrived on the same session. The server, which had already emitted the original `id: 1` result, now emitted a second `id: 1` result on the stream. The client's demultiplexer, keyed on `id`, overwrote its pending-future map entry for `id: 1` with the retry's result. The original `read_file` future resolved with the *retry's* payload; the `search_index` future (`id: 2`) resolved correctly; the retry's future never resolved at all and was garbage-collected after the agent's step budget expired. The agent proceeded believing `read_file` had returned the retry's (stale, truncated) content, and its next reasoning step was built on a file snapshot that no longer matched disk. The tell was not an exception. It was a **ledger checksum mismatch** discovered two steps later when a write tool rejected a precondition the agent believed it had satisfied. ## Condition of Validity This failure requires the conjunction of four conditions; remove any one and the mechanism does not fire: 1. **Conditional upgrade.** The server returns `application/json` for some requests and `text/event-stream` for others within the same session, so the client cannot statically assume one framing. Servers that *always* stream, or *never* stream, do not exhibit this. 2. **Client-side `id` reuse across a timeout boundary.** The client must treat a timeout as a reason to re-issue with a recycled `id` rather than a monotonic one. This is the load-bearing defect — it is a client bug, but one the stateless framing *invites*. 3. **Server-side non-idempotent retry acceptance.** The server must accept the duplicate `id` and emit a second response rather than rejecting it as a protocol violation (JSON-RPC 2.0 does not forbid duplicate ids on a stream; it is silent). 4. **Out-of-order or duplicate emission on a shared stream.** If responses were strictly serialized and the client drained them in order with a FIFO, the second `id: 1` would be distinguishable by position. Multiplexing removes that crutch. ## Decision Boundary The boundary is **where the client decides whether an in-flight request is "done."** Two regimes: - **Stateless regime:** request completion is bound to HTTP exchange completion. A timeout means the exchange failed; re-issuing with a fresh `id` is safe because the old exchange's response, if it ever arrives, arrives on a *different* connection and is discarded by framing. - **Stateful regime:** request completion is bound to a response *event* on a shared stream. A timeout means "the response has not yet appeared on the stream," not "the exchange failed." Re-issuing here is a **duplicate submission**, and the correct recovery is to *wait* for the original `id` on the stream, or to send a `notifications/cancelled` for that `id` and only then re-issue with a **new** `id`. The client must therefore branch on a single fact it often fails to track: *did this request's response channel get upgraded to a multiplexed stream?* If yes, the timeout handler must switch from "retry with recycled id" to "await-or-cancel-then-retry-with-fresh-id." The architectural guardrail is a **session-scoped monotonic id allocator** plus a **pending-future map that refuses to overwrite an existing key** — the second `id: 1` must raise, not clobber. ## Operational Effect Downstream, the desync is *silent and compounding*. Because the JSON-RPC layer reports success (every response is valid), the agent's tool-result validation passes, and the poisoned result enters the reasoning loop as ground truth. Error compounding then proceeds at the rate of one bad premise per subsequent step: the agent writes against a stale snapshot, the write succeeds (the file existed), and the divergence is only caught by an independent precondition check — if one exists. Agents without post-write read-back verification will persist the corruption into semantic memory, where it becomes indistinguishable from a legitimate observation and survives cold-start. The mitigation is structural, not prompt-level: (a) session-scoped monotonic ids, (b) a demultiplexer that treats duplicate-id-on-stream as a hard protocol error, (c) a client-side timeout classifier that distinguishes "no response yet on stream" from "exchange failed," and (d) a mandatory read-back after any write tool whose precondition was derived from a prior read in the same session. ```python from __future__ import annotations import itertools from dataclasses import dataclass, field from typing import Any class LedgerDesyncError(RuntimeError): """Raised when a response id collides with an already-resolved pending future.""" @dataclass class PendingFuture: call_name: str resolved: bool = False payload: Any = None @dataclass class SessionLedger: session_id: str # Session-scoped monotonic allocator. Never reset within a session. _id_counter: itertools.count = field(default_factory=lambda: itertools.count(1)) pending: dict[int, PendingFuture] = field(default_factory=dict) resolved: dict[int, Any] = field(default_factory=dict) upgraded_to_stream: bool = False def allocate_id(self, call_name: str) -> int: rid = next(self._id_counter) self.pending[rid] = PendingFuture(call_name=call_name) return rid def on_response(self, rid: int, payload: Any) -> None: # The invariant: a response id must resolve exactly once per session. if rid in self.resolved: raise LedgerDesyncError( f"duplicate response for id={rid} on session={self.session_id!r}; " f"previously resolved by {self.resolved[rid]!r}, now {payload!r}. " "Client likely recycled a JSON-RPC id across a stateless->stateful " "upgrade boundary. Treat as protocol violation and re-handshake." ) if rid not in self.pending: raise LedgerDesyncError( f"response for unknown id={rid} on session={self.session_id!r}; " "no matching in-flight call. Response stream is out of sync." ) fut = self.pending.pop(rid) fut.resolved = True fut.payload = payload self.resolved[rid] = payload def on_timeout(self, rid: int) -> int: """Recovery path. Returns the id to use for a retry, or raises.""" if not self.upgraded_to_stream: # Stateless: exchange failed, safe to re-issue with a fresh id. self.pending.pop(rid, None) return self.allocate_id("retry") # Stateful: the original response may still arrive on the stream. # Reusing the id here is the exact bug this record documents. raise LedgerDesyncError( f"timeout on id={rid} while session={self.session_id!r} is in " "stream-upgraded mode. Do not recycle id. Send notifications/cancelled " "for this id, await or discard the late response, then re-issue with a " "fresh allocation." ) ```