# Which invariants prevent SSE stream resurrection from corrupting resumable MCP sessions across transport reconnect **Date of Record:** 2026 November 27 **Scope:** Applies to MCP servers exposing the HTTP-native transport with `Last-Event-ID` resumption and SSE multiplexing of multiple in-flight JSON-RPC requests over a single session. Does not cover stdio transport, WebSocket transports, or stateless request/response MCP deployments. ## Core Distinction The failure here is not "reconnect loses messages." The failure is that a *successfully resumed* SSE stream can silently deliver events belonging to a request whose logical lifetime already terminated on the server, because the event log and the session-request registry are two independent pieces of state with independent garbage-collection clocks. Resumption is governed by `Last-Event-ID` (a monotonic cursor into the event ring buffer); request validity is governed by the session's in-flight request table (a map from JSON-RPC `id` to a live handler/cancellation token). When these two clocks diverge — specifically when the event buffer retains events past the point where the corresponding request was cancelled, timed out, or completed — a client that reconnects with an older `Last-Event-ID` will replay events for a request the client (or the server) already considers dead. The client, trusting the resume contract, treats the replayed `result`/`error` frame as authoritative and merges it into a request slot that was already resolved or is now occupied by a *different* request reusing the same `id`. The invariant that prevents this is: **the set of event IDs replayable for a session must be a subset of the event IDs whose originating request is still resolvable in that session's request registry, OR the replay must be tagged with a request-generation epoch that the client validates before applying.** Event-buffer retention and request-registry retention must be co-terminous, or the resume path must carry an epoch discriminator. Neither is true by default in most MCP HTTP transport implementations. ## What Was Observed A tool-calling agent issued `tools/call` with JSON-RPC `id: 7` against an MCP server over HTTP+SSE. The tool handler was slow (a browser automation tool with a 30s internal timeout). The agent's HTTP client had a 12s read timeout on the SSE connection and reconnected with `Last-Event-ID: 41`. On the server, the session's request registry had already expired `id: 7` at 10s (a per-request TTL shorter than the tool's own timeout), emitted an `error` frame at event 44, and *then* the underlying tool completed at 28s and the server emitted a late `result` frame at event 47 — because the tool handler's completion callback wrote to the event log without checking whether the request was still registered. The event ring buffer retained all 60 events (buffer size 512, no time-based expiry). The client reconnected at 12s with `Last-Event-ID: 41` and received events 42–47 in order: a `progress` notification (42), a partial log (43), the `error` frame for `id: 7` (44), a heartbeat (45), an unrelated `notifications/message` (46), and the late `result` for `id: 7` (47). The client's request-slot state machine had already resolved `id: 7` on the `error` at 44 and *reused* `id: 7` for a new `tools/call` (a common client-side ID-pool optimization). The replayed `result` at 47 was applied to the new request's slot, producing a type-mismatched result object (the old tool's output schema) delivered as the answer to a different tool invocation. The agent then reasoned over a `browser.navigate` result as if it were the output of `filesystem.read`, and emitted a downstream action against the wrong resource. The trigger condition is a conjunction: 1. Per-request TTL in the session registry < tool execution wall-clock (server-side). 2. Event buffer retention window > request registry retention window (server-side). 3. Client reuses JSON-RPC `id` values after resolution (client-side). 4. Client replays from a `Last-Event-ID` that predates the request's terminal event. Any one of these being false masks the failure. All four are common defaults. ## Condition of Validity The resume contract is only sound under the following condition, which must be enforced server-side and *checked* client-side: For every event `e` in the replayable buffer with `e.request_id = r`, either (a) `r` is present in the session request registry at reconnect time with the same generation epoch recorded at event emission, or (b) `e` is a terminal frame (`result` or `error`) and the client has not yet observed any terminal frame for `r` in this session. Condition (b) is the client-side guard; condition (a) is the server-side guard. A conforming server must, on reconnect, either drop events failing (a) or annotate them with `request_epoch` so the client can apply (b) deterministically. The invariant is violated the moment the server writes a late completion to the event log after the request has been deregistered. The write path must be gated: `emit_event(session, request_id, frame)` must check `request_id ∈ session.registry` and `session.registry[request_id].epoch == frame.epoch` before appending to the buffer. If the request is gone, the frame is dropped (or routed to a dead-letter sink), never appended. This is the single-line guard most implementations omit, because the tool completion callback holds a closure over the event emitter and not over the registry. A second, independent invariant is required on the client: **a JSON-RPC `id` must not be reused within a session while any event with that `id` remains replayable.** The client cannot know the server's buffer depth, so the safe rule is to never reuse `id` values within a session, or to namespace them with a client-side monotonic counter that is never reset. ID reuse is the amplifier that converts a benign duplicate-delivery into a cross-request type confusion. ## Decision Boundary The boundary is whether to treat `Last-Event-ID` resumption as *at-least-once delivery of opaque events* or as *exactly-once delivery of request-scoped frames*. These require different guards: - **At-least-once (opaque):** the client must deduplicate by event ID and must not assume any frame maps to a live request. Late frames for dead requests are expected and must be discarded on the basis of a client-side terminal-frame-already-seen set. This is robust but pushes all correctness onto the client and requires unbounded client-side tracking of terminal IDs (bounded by session length). - **Exactly-once (request-scoped):** the server must guarantee that the replayable set is closed under request liveness — i.e., the emit guard above plus co-terminous retention. This is the stronger contract and the one MCP HTTP transport *should* specify but currently leaves implicit. The decision boundary for an operator is: if your server's tool handlers can outlive your request TTL (any long-running tool, any tool with an internal timeout > the request TTL, any tool that retries), you are in the exactly-once regime whether you intended it or not, and you must implement the emit guard. If you cannot, you must downgrade to at-least-once and force clients to never reuse IDs and to track terminal frames. There is no safe middle: the current default (server retains events past request death, client reuses IDs) is the unsafe corner. ## Operational Effect The observable effect of the violation is *silent cross-request result substitution*: the agent's reasoning layer receives a well-formed JSON-RPC `result` whose `id` matches an outstanding request but whose payload belongs to a different tool invocation. Because the transport layer reports success (the frame parsed, the ID matched, the slot was open), no error surfaces at the protocol layer. The corruption manifests downstream as a schema mismatch, a semantic mismatch, or — worst case — a plausible-but-wrong value that passes the agent's own output validation. In the observed incident, the substitution was only detected because the downstream action targeted a path that did not exist under the wrong tool's semantics. The mitigation that holds under all four trigger conditions is the emit guard on the server plus a client-side `terminal_seen` set keyed by `(session_id, request_id, epoch)`, with `epoch` a server-assigned monotonic counter incremented on every request registration. The epoch is the discriminator that makes replay safe even when the buffer and registry retention diverge, because a replayed frame for a dead epoch is rejected by the client regardless of ID reuse. ```python import time from dataclasses import dataclass, field from typing import Any class StaleEventReplayError(RuntimeError): """Raised when a replayed SSE frame belongs to a request generation that is no longer live.""" @dataclass class RequestEntry: request_id: str epoch: int registered_at: float ttl_s: float def alive(self, now: float) -> bool: return (now - self.registered_at) < self.ttl_s @dataclass class EventFrame: event_id: int request_id: str epoch: int payload: dict[str, Any] @dataclass class Session: session_id: str registry: dict[str, RequestEntry] = field(default_factory=dict) event_buffer: list[EventFrame] = field(default_factory=list) epoch_counter: int = 0 terminal_seen: set[tuple[str, int]] = field(default_factory=set) def register(self, request_id: str, ttl_s: float) -> RequestEntry: self.epoch_counter += 1 entry = RequestEntry(request_id, self.epoch_counter, time.monotonic(), ttl_s) self.registry[request_id] = entry return entry def emit(self, request_id: str, epoch: int, payload: dict[str, Any]) -> None: """Guarded emit: refuse to append frames for deregistered or superseded requests.""" entry = self.registry.get(request_id) now = time.monotonic() if entry is None or not entry.alive(now) or entry.epoch != epoch: # Late completion from a tool handler whose request died: drop, do not buffer. return self.event_buffer.append(EventFrame(len(self.event_buffer) + 1, request_id, epoch, payload)) def resume(self, last_event_id: int) -> list[EventFrame]: """Return replayable frames, rejecting stale-epoch frames the client must not apply.""" out: list[EventFrame] = [] for frame in self.event_buffer: if frame.event_id <= last_event_id: continue entry = self.registry.get(frame.request_id) if entry is None or entry.epoch != frame.epoch: # Stale generation: surface to caller, never hand to the reasoning layer. raise StaleEventReplayError( f"session={self.session_id} event={frame.event_id} " f"request={frame.request_id} epoch={frame.epoch} has no live registry entry" ) key = (frame.request_id, frame.epoch) if key in self.terminal_seen: continue if frame.payload.get("type") in ("result", "error"): self.terminal_seen.add(key) out.append(frame) return out def apply_resumed_frames(session: Session, last_event_id: int, slot_id: str) -> list[dict[str, Any]]: """Client-side application path; enforces epoch match against the open slot.""" frames = session.resume(last_event_id) applied: list[dict[str, Any]] = [] for frame in frames: if frame.request_id != slot_id: continue entry = session.registry.get(frame.request_id) if entry is None or entry.epoch != frame.epoch: raise StaleEventReplayError( f"refusing to apply stale frame {frame.event_id} to slot {slot_id}" ) applied.append(frame.payload) return applied ```