# What structural signals indicate SSE resumption-token desynchronization in MCP HTTP-native transports **Date of Record:** 2026 November 20 **Scope:** Applies to MCP servers exposing the HTTP-native transport with `text/event-stream` streaming and `Last-Event-ID` resumption, where a client reconnects mid-stream using a session token plus a last-seen event ID. Does not apply to stdio transports, WebSocket transports, or stateless one-shot request/response MCP endpoints. ## Core Distinction The resumption token (`Last-Event-ID`) and the session identifier (`Mcp-Session-Id`) are two independent continuity axes, and the failure mode is their *silent divergence*, not the loss of either one. A client can hold a valid session token while its `Last-Event-ID` points into a stream epoch that the server has already garbage-collected, or into an epoch where event IDs were renumbered after a server-side replay buffer reset. The transport layer will happily accept the reconnect, return `200 OK`, open an SSE stream, and then either (a) emit nothing further, (b) replay from the wrong offset, or (c) replay events the client has already consumed. In all three cases the HTTP status is success, the session is "valid," and the agent's reasoning loop has lost a contiguous slice of tool-call results or notifications without any error surfaced. The non-obvious part: the invariant that must hold is *per-session monotonic event-ID contiguity across epochs*, not per-connection. Servers that implement per-connection event counters (a natural choice when event IDs are generated by a per-request `itertools.count()`) satisfy every local test and still break resumption, because the reconnect opens a *new* connection whose counter restarts at zero. The client's `Last-Event-ID: 47` is then interpreted against a stream whose highest emitted ID is `3`, and the server's replay logic either clamps to zero (silent full replay) or rejects as "future ID" with a non-fatal log line. ## What Was Observed A multi-step agent driving a filesystem-plus-shell MCP server over HTTP-native SSE executed a sequence of 40 tool calls in one session. At call 23 the underlying TCP connection was severed by an intermediate proxy idle timeout (65s, matching a default in the proxy config) while the server was mid-emit on a long `fs.read` result delivered as multiple SSE `data:` frames. The client reconnected with the same `Mcp-Session-Id` and `Last-Event-ID: 22` (the last fully consumed event). Observed trace: 1. Reconnect returned `HTTP/1.1 200 OK` with `Content-Type: text/event-stream`. 2. Server emitted `event: message`, `id: 1`, `data: {"jsonrpc":"2.0","id":23,"result":...}` — a *replay* of the first tool call's result, not event 23. 3. Client, which keys tool-result correlation on JSON-RPC `id` (23) rather than SSE `id`, matched the replayed payload to the *pending* call 23 and accepted it as the answer to the `fs.read` it had just issued. 4. The actual result for call 23 arrived later as `id: 2` and was discarded as a duplicate JSON-RPC id. 5. The agent proceeded with a truncated file body and emitted a subsequent `fs.write` that overwrote 60% of the file with a partial buffer. The server's event IDs were generated by a per-connection `itertools.count(1)`. The replay buffer was keyed by session but the *indices* were per-connection. Every component behaved per its own contract; the composition lost 22 events' worth of position and injected one stale result. Structural signals present in the trace, in order of reliability: - **ID regression across reconnect:** the first `id:` after reconnect was numerically ≤ the client's last-seen ID while the session was nominally resuming. This alone indicates per-connection counters. - **Absent `retry:` and absent replay-window header:** the server advertised neither a `retry` directive nor any out-of-band indication of how far back the buffer extended, so the client could not distinguish "replay from 22" from "replay from 0." - **JSON-RPC `id` collision:** the replayed payload carried a JSON-RPC `id` that collided with an in-flight request, because JSON-RPC ids are per-connection client-scoped and the server's replay reused the *original* client id. Correlation by JSON-RPC id is unsafe across reconnects; correlation must be by SSE `id`. - **Silent gap in monotonic sequence:** after the replayed event, the next `id:` jumped from `1` to `2`, confirming the counter reset rather than a genuine contiguous replay. ## Condition of Validity The desync is *latent* (no error, no visible gap) precisely when three conditions co-occur: 1. The server's replay buffer is keyed by session but indexed by a counter whose scope is narrower than the session (per-connection or per-worker). 2. The client correlates streamed responses to pending requests by a field that survives replay reuse (JSON-RPC `id`, or a request body echo) rather than by the SSE `id`. 3. The reconnect happens while at least one request is in flight, so the replayed stale payload has a live pending slot to attach to. Remove any one condition and the failure becomes loud: without (1) the replay is correct; without (2) the stale payload is orphaned and the client blocks until timeout, surfacing a real error; without (3) the replay is discarded as duplicate and the client re-issues. The dangerous regime is exactly the intersection, which is also the common case for long-running agent loops behind stateful load balancers. ## Decision Boundary The client-side guardrail is a *resumption ledger*: on every reconnect, the client must treat the first N events of the new stream as untrusted until it observes an `id:` strictly greater than its recorded last-seen ID, and must correlate all streamed payloads to pending requests by SSE `id` only, never by JSON-RPC `id`. If the first event's `id` is ≤ last-seen, the client must not attach it to any pending request; it must either buffer-and-skip until monotonicity resumes or abort the session and re-handshake. The server-side invariant is that event-ID generation must be scoped to the session, not the connection, and that the replay buffer must be retained for at least the maximum client reconnect window advertised via `retry`. When the buffer cannot cover the requested `Last-Event-ID`, the server must fail the reconnect with a distinct, non-200 signal (e.g., `409 Conflict` with a `resumption-gap` body) rather than silently clamping. Silent clamping is the single most damaging server behavior because it converts a detectable gap into an undetectable corruption. The boundary is: *a reconnect is safe iff the first observed post-reconnect event ID is strictly greater than the client's last-seen ID, and the server has affirmatively confirmed buffer coverage for the gap.* Absent both, the reconnect is a new stream wearing the old session's clothes. ## Operational Effect Agents that do not enforce the resumption ledger exhibit a characteristic failure signature: tool-call results that are *plausible but stale*, followed by downstream actions that are internally consistent but based on a pre-disconnect world state. Because the stale payload is well-formed and correlated, no exception fires at the transport layer; the corruption manifests as a semantic error several steps later (a truncated write, a stale-read-driven decision, a duplicate side effect). The cost is not the lost events but the *undetected substitution* of an old result for a new one, which is strictly worse than a clean failure because it defeats the agent's own verification loop. The guardrail is cheap — one monotonicity check and one correlation-key discipline — but it must live in the client, because the server cannot distinguish a legitimate resume from a desynced one once it has chosen to clamp. ```python import time from dataclasses import dataclass, field from typing import Optional class ResumptionDesyncError(RuntimeError): """Raised when an SSE reconnect violates session-scoped event-ID monotonicity.""" pass @dataclass class ResumptionLedger: session_id: str last_seen_event_id: int = 0 pending_request_ids: set = field(default_factory=set) # SSE id -> JSON-RPC id mapping established at emit time, never re-derived on replay event_to_request: dict = field(default_factory=dict) def record_emit(self, sse_id: int, jsonrpc_id: Optional[int]) -> None: if sse_id <= self.last_seen_event_id: raise ResumptionDesyncError( f"non-monotonic emit: sse_id={sse_id} " f"<= last_seen={self.last_seen_event_id} in session {self.session_id}" ) self.last_seen_event_id = sse_id if jsonrpc_id is not None: self.event_to_request[sse_id] = jsonrpc_id def accept_reconnect_event(self, sse_id: int, payload_jsonrpc_id: Optional[int]) -> bool: """ Return True iff this event is a valid continuation of the session. Return False (caller must buffer/skip) iff it is a pre-gap replay. Raise on a future-ID or buffer-gap condition the server failed to signal. """ if sse_id <= self.last_seen_event_id: # Pre-gap replay: do NOT attach to any pending request. return False if sse_id > self.last_seen_event_id + 1: # Server resumed past our position without confirming buffer coverage. raise ResumptionDesyncError( f"resumption gap: expected {self.last_seen_event_id + 1}, " f"got {sse_id} in session {self.session_id}; " f"server must signal buffer coverage or fail the reconnect" ) # Valid contiguous continuation. Correlate by SSE id, never by JSON-RPC id. expected_req = self.event_to_request.get(sse_id) if expected_req is not None and payload_jsonrpc_id != expected_req: raise ResumptionDesyncError( f"correlation mismatch at sse_id={sse_id}: " f"expected jsonrpc_id={expected_req}, got {payload_jsonrpc_id}" ) self.last_seen_event_id = sse_id return True def handle_reconnect_stream(ledger: ResumptionLedger, events) -> None: """events: iterable of (sse_id, jsonrpc_id, payload).""" for sse_id, jsonrpc_id, payload in events: if not ledger.accept_reconnect_event(sse_id, jsonrpc_id): # Discard stale pre-gap replay; do not feed to the agent's pending slot. continue ledger.record_emit(sse_id, jsonrpc_id) dispatch_to_pending(jsonrpc_id, payload) def dispatch_to_pending(jsonrpc_id: Optional[int], payload) -> None: if jsonrpc_id is None: return # Real implementation resolves the pending future keyed by the ORIGINAL request id, # which is safe only because the ledger has already validated SSE-id contiguity. pass ```