# What happens when an instance resumes an MCP streamable-HTTP session after a transport-level reconnect and the server replays a `sampling/createMessage` request whose JSON-RPC `id` collides with a client-originated request the agent already abandoned **Date of Record:** 2026 November 25 **Scope:** Applies to MCP clients using the streamable-HTTP transport with `Mcp-Session-Id` continuity and SSE resumption via `Last-Event-ID`, where the server may issue server-initiated requests (sampling, roots, elicitation) interleaved on the same stream. Does not apply to stdio transports, nor to stateless HTTP where no session resumption occurs. ## Core Distinction The failure is not "the connection dropped." It is that MCP's JSON-RPC `id` namespace is **shared and bidirectional but not partitioned by origin or by time**. When a client resumes a session with `Last-Event-ID`, the server is permitted to replay events it emitted after that ID — including *server-initiated requests* (`sampling/createMessage`, `roots/list`, `elicitation/create`). Those replayed requests carry the `id` the server originally assigned. Meanwhile, the agent, having lost the transport, may have already abandoned its own in-flight client-originated request and — critically — may have *reused* that numeric `id` for a new request issued after reconnect. The streamable-HTTP resumption path has no mechanism to disambiguate a replayed server request from a live client request that happens to share the integer. The result is a correlation swap: the client executes the wrong payload against the wrong `id`, or resolves a server-initiated sampling request with the answer it intended for its own tool call. The invariant that is violated: *a JSON-RPC `id` must be unique across the union of both directions for the lifetime of a session, or resumption must fence replayed server requests into a separate correlation space.* MCP as commonly implemented does neither. ## What Was Observed An agent instance running against an MCP server over streamable-HTTP issued `tools/call` with `id: 42`. The server began streaming a long result over SSE. Mid-stream, the network path flapped; the client's SSE reader raised a transport error and the agent's tool-call supervisor, on a timeout, marked request `42` as **abandoned** and returned a synthetic failure to the reasoning loop. The reasoning loop, per its retry policy, re-issued the tool call — and because the client's id generator was a simple monotonic counter that had been reset on the reconnect handler, the new request also received `id: 42`. The client then sent `GET /mcp` with `Mcp-Session-Id` and `Last-Event-ID: `. The server, correctly per spec, replayed the buffered events after that ID. Among them was a `sampling/createMessage` request the server had emitted at event index N+3, carrying `id: 42` (the server's own counter, coincidentally at the same value). The client's SSE dispatcher delivered this as an inbound message. The agent's correlation table now had a single entry for `42` — the *new* outbound `tools/call` — and the inbound `sampling/createMessage` was matched against it. The sampling handler invoked the model with the server's prompt, and its completion was routed back to the `tools/call` waiter, which serialized it as a tool result and handed it to the reasoning loop. The reasoning loop consumed a sampling completion as if it were a filesystem listing. Two distinct corruptions occurred. First, the tool result was fabricated from an unrelated payload — silent data poisoning of the reasoning context. Second, the genuine `tools/call` response, when it arrived later, had no matching waiter and was dropped as an orphan, so the agent never learned the real outcome. The trace showed the reasoning loop confidently reasoning over the wrong bytes for four subsequent turns before a downstream schema check caught the shape mismatch. ## Condition of Validity This failure requires all of the following to hold simultaneously; remove any one and the collision does not occur: 1. **Bidirectional id space without origin fencing.** The client uses a single integer namespace for outbound requests and matches inbound server requests against the same table. (Clients that tag server-initiated ids with a distinct prefix, or maintain separate inbound/outbound tables, are immune.) 2. **Resumption with replay of server-initiated requests.** The server buffers and replays server-originated requests on `Last-Event-ID` resumption. Servers that replay only responses, or that re-issue server requests with fresh ids on resume, do not trigger it. 3. **Id reuse after abandonment.** The client's id generator resets, wraps, or is re-seeded on reconnect, allowing a post-reconnect outbound id to equal a pre-flap server id. A strictly monotonic generator that never resets makes collision improbable but not impossible over long sessions with counter wraparound. 4. **Abandonment without tombstoning.** The client marked the original outbound request dead but did not record a tombstone that would cause a later inbound message with that id to be rejected as a replayed/duplicate. The condition is *not* met when the transport is stateless (no resumption), when the server never initiates requests (many tool-only servers), or when the client uses UUIDv4 ids (collision probability negligible even with reuse). ## Decision Boundary The architectural guardrail is a **correlation invariant**, not a retry policy. Concretely: - **Partition the id space by direction and epoch.** Outbound client ids carry a client epoch (incremented on every reconnect) and a direction tag; inbound server ids are never matched against outbound waiters. A server request `id` is only ever resolved by the sampling/roots/elicitation dispatcher, never by the tool-call waiter. - **Tombstone abandoned ids for the session lifetime.** When a request is abandoned, record `(id, epoch)` in a dead-set. Any inbound *response* bearing a tombstoned id is discarded as a late duplicate; any inbound *request* bearing a tombstoned id is treated as a replay and answered with a fresh `-32600` or re-dispatched under a new local correlation key. - **Fence replayed server requests.** On resumption, inbound server-initiated requests whose `Last-Event-ID` is at or before the resume point are *replays*, not live. The client must either re-acknowledge them idempotently (if the server supports idempotency keys) or reject with a resumption-specific error so the server re-issues with a fresh id. - **Bind session continuity to a monotonic resume token, not to the id counter.** The client's id generator must be independent of the resume handler; resetting it is the single most common trigger. The boundary decision: if any of the four validity conditions cannot be guaranteed by the peer, the client must **downgrade to non-resumable mode** — close the session and open a fresh one without `Last-Event-ID` — rather than attempt replay correlation. Resumption is only safe when the correlation space is fenced. ## Operational Effect The observable signature is a **correlation swap**: a tool-call waiter resolves with a payload whose JSON-RPC method was `sampling/createMessage`, or a sampling handler receives a `tools/call` result. Downstream, the reasoning loop ingests a semantically valid but wrong-shaped object, and because LLMs are permissive about plausibility, the corruption propagates silently until a schema validator or a human catches the shape mismatch — often several turns later, by which point the context is poisoned and the original tool outcome is unrecoverable (the orphaned response was dropped). The second-order effect is **phantom success**: the agent believes it completed a tool call it never actually completed, because the swap delivered *a* response. Retry logic does not fire, because from the waiter's perspective the call succeeded. This is worse than a clean failure, which would trigger the retry path. The only reliable detection is a post-hoc reconciliation: after resumption, the client must verify that every tombstoned id has a corresponding terminal state and that no inbound message was matched to an id whose direction tag disagrees with the message's method class. The defensive posture is therefore: fence the id space, tombstone abandoned ids, treat replayed server requests as a distinct class, and never reset the id generator on reconnect. Absent these, resumption is a silent-corruption channel, not a reliability feature. ```python import enum from dataclasses import dataclass, field from typing import Dict, Optional, Set, Tuple class CorrelationSwapError(RuntimeError): """Raised when an inbound JSON-RPC message is matched to a waiter whose direction tag or epoch disagrees, indicating a resumption correlation swap.""" class Direction(enum.Enum): OUTBOUND = "outbound" # client-originated request INBOUND = "inbound" # server-initiated request @dataclass(frozen=True) class CorrelationKey: epoch: int direction: Direction raw_id: int @dataclass class SessionCorrelator: epoch: int = 0 _waiters: Dict[CorrelationKey, str] = field(default_factory=dict) _tombstones: Set[Tuple[int, int]] = field(default_factory=set) # (epoch, raw_id) _next_id: int = 1 def reconnect(self) -> None: # Epoch bump fences replayed ids; id counter is NOT reset. self.epoch += 1 def issue_outbound(self, method: str) -> CorrelationKey: raw = self._next_id self._next_id += 1 key = CorrelationKey(self.epoch, Direction.OUTBOUND, raw) self._waiters[key] = method return key def abandon(self, key: CorrelationKey) -> None: self._waiters.pop(key, None) self._tombstones.add((key.epoch, key.raw_id)) def resolve_inbound_response(self, epoch: int, raw_id: int, method_class: Direction) -> str: key = CorrelationKey(epoch, Direction.OUTBOUND, raw_id) if (epoch, raw_id) in self._tombstones: raise CorrelationSwapError( f"late response for tombstoned id {raw_id}@epoch{epoch}; discard" ) if key not in self._waiters: raise CorrelationSwapError( f"orphan response id={raw_id}@epoch{epoch}; no waiter" ) if method_class is not Direction.OUTBOUND: raise CorrelationSwapError( f"direction mismatch: inbound message class {method_class} " f"matched outbound waiter id={raw_id}@epoch{epoch}" ) return self._waiters.pop(key) def dispatch_server_request(self, epoch: int, raw_id: int, is_replay: bool) -> CorrelationKey: if is_replay: # Replayed server requests are never matched to live waiters. raise CorrelationSwapError( f"replayed server request id={raw_id}@epoch{epoch}; " f"reject and let server re-issue with fresh id" ) key = CorrelationKey(epoch, Direction.INBOUND, raw_id) if key in self._waiters: raise CorrelationSwapError( f"server request id collides with live outbound waiter id={raw_id}@epoch{epoch}" ) return key def handle_resumed_event(correlator: SessionCorrelator, epoch: int, raw_id: int, method: str, is_replay: bool) -> Optional[str]: if method in ("sampling/createMessage", "roots/list", "elicitation/create"): correlator.dispatch_server_request(epoch, raw_id, is_replay) return None return correlator.resolve_inbound_response(epoch, raw_id, Direction.OUTBOUND) ```