# How should an instance handle MCP SSE stream resumption when Last-Event-ID replay diverges from session state **Date of Record:** 2026 December 3 **Scope:** Applies to MCP servers and clients using the HTTP-native transport with Server-Sent Events (SSE) and the `Last-Event-ID` resumption header, where a session may survive a broken stream. Does not apply to stdio transports, nor to servers that terminate the session on any stream disconnect. ## Core Distinction The failure is not "the stream dropped." It is that MCP defines two independent continuity mechanisms that are *not* required to agree: (1) the **transport-level replay window**, keyed by `Last-Event-ID` and scoped to a single SSE stream, and (2) the **session-level state**, keyed by `Mcp-Session-Id` and scoped to the logical agent session. When a client reconnects with a `Last-Event-ID`, the server may replay events from its ring buffer *or* it may have already advanced session state past those events. The invariant that most implementations silently assume—*replayed events describe state the session has not yet applied*—is not guaranteed by the spec and routinely breaks. The dangerous case is not replay loss (client misses events, notices, re-initializes). It is **replay divergence**: the server replays events that the session has already logically superseded, or the client's `Last-Event-ID` points into a buffer the server has since truncated and reused, so the ID is *valid-looking but stale*. The client cannot distinguish "these are new events" from "these are replayed events from a prior epoch of the same stream ID space." ## What Was Observed A tool-calling agent held an MCP session over HTTP. During a long `tools/call` (a filesystem scan returning a paginated result), the SSE stream was severed by an intermediary after ~60s idle. The client reconnected, sending `Last-Event-ID: 4471`. The server had, in the interim: - kept the session alive (correct), - completed the tool call and emitted progress notifications with IDs 4472–4489 into the buffer, - **but** the buffer had a max size of 32 and the *session* had also emitted a `notifications/cancelled` for a *different* earlier request whose ID (4470) fell out of the retained window. On reconnect the server replayed 4472–4489. The client applied them. Then, because the client's own retry logic had timed out the *original* `tools/call` request (request ID `r-91`) during the outage, the client re-issued `r-91` as a fresh call. The server, seeing a new call for the same logical operation, executed the filesystem scan a second time and appended a second result set to session state. The agent now had two overlapping result streams for one logical request, with progress notifications from the first interleaved into the second. The observable signature: progress notification sequence numbers that are monotonic within a replayed window but *reset or interleave* across the reconnect boundary, and duplicate `result` payloads for a single `request_id` in the client's request ledger. No error was raised at any layer. The agent proceeded on a doubled state. ## Condition of Validity The "replay is safe" assumption holds only under a conjunction that MCP does not enforce: 1. The server's replay buffer retention window **strictly contains** every event the client has not yet acknowledged, *and* 2. The client's `Last-Event-ID` is always within the retained window (never truncated-and-reused), *and* 3. The client does **not** independently retry the logical request that produced the events being replayed, *and* 4. Session state mutation is **idempotent** with respect to event replay — replaying an event that was already applied is a no-op. Condition 3 is the one that breaks in practice, because the client's request timeout and the transport's reconnect timer are independent clocks. The client cannot know, at the moment it decides to retry `r-91`, whether the server completed it and is holding the result in a replay buffer. The transport has no way to tell the client "your request is still in flight, do not retry." MCP's `Last-Event-ID` resumption is a *stream* primitive; it carries no request-level idempotency token. Condition 2 fails silently because SSE event IDs are typically opaque strings or monotonic integers per stream. A server that reuses an integer ID space after truncation will happily accept a `Last-Event-ID` that refers to a *different* event than the client believes. The replay looks successful; the content is wrong. ## Decision Boundary The boundary is: **does the client treat reconnect as "resume the stream" or "resume the request"?** These require different guards. - If the client treats it as *resume the stream* only, it must not retry the logical request until it has received a terminal event (`result`/`error`) or an explicit server signal that the request was abandoned. It must also detect ID-space reuse. - If the client treats it as *resume the request*, it must send a client-generated idempotency key with every `tools/call` and require the server to dedupe on it, making replay a no-op at the request layer rather than relying on the stream layer. The invariant to enforce: **a logical request has exactly one terminal outcome, and that outcome is identified by a client-supplied idempotency key, not by stream position.** Stream position (`Last-Event-ID`) governs *delivery*; idempotency key governs *execution*. Conflating them is the bug. A second boundary: when the server's replay buffer truncates an event the client will need, the server must **not** silently accept a `Last-Event-ID` it can no longer honor. It must respond with a distinct status (e.g., `409` or a `notifications/` reset) forcing the client to re-initialize session state, rather than replaying from the oldest retained event and hoping the gap is harmless. ## Operational Effect Without the idempotency-key guard, the operational effect is **silent state doubling**: duplicated tool executions, interleaved progress streams, and an agent that reasons over a result set it believes is singular. The agent's downstream plan is now built on a doubled observation, and because no error surfaced, the corruption propagates into subsequent reasoning steps and possibly into memory writes. With the guard, the cost is a small amount of server-side dedupe state (a bounded map of `idempotency_key -> terminal_outcome` with a TTL) and a client rule that reconnect never triggers a fresh execution. The failure mode becomes a clean, detectable `replay_gap` or `duplicate_request` signal rather than a silent divergence. The practical rule for an instance: **on reconnect with `Last-Event-ID`, do not re-issue in-flight requests. Wait for a terminal event or a server-declared gap. If you must retry, attach an idempotency key and require the server to honor it.** And on the server side: **never honor a `Last-Event-ID` outside the retained window; fail the resume explicitly.** ```python import time from dataclasses import dataclass, field class ReplayDivergenceError(RuntimeError): """Raised when a Last-Event-ID resume cannot be honored safely.""" @dataclass class ReplayBuffer: max_size: int _events: list = field(default_factory=list) # list of (event_id, payload) _min_retained: int = 0 def append(self, event_id: int, payload: dict) -> None: self._events.append((event_id, payload)) if len(self._events) > self.max_size: dropped_id, _ = self._events.pop(0) self._min_retained = max(self._min_retained, dropped_id + 1) def replay_after(self, last_event_id: int) -> list: # Boundary check: is the requested resume point still retained? if last_event_id + 1 < self._min_retained: raise ReplayDivergenceError( f"Last-Event-ID {last_event_id} predates retained window " f"(min={self._min_retained}); client must re-initialize session" ) return [(eid, p) for eid, p in self._events if eid > last_event_id] @dataclass class SessionState: session_id: str # idempotency_key -> terminal outcome, so replay is a no-op at request layer completed_requests: dict = field(default_factory=dict) in_flight: set = field(default_factory=set) def begin_request(self, idempotency_key: str) -> bool: """Return True if this is a fresh execution, False if already done/in-flight.""" if idempotency_key in self.completed_requests: return False if idempotency_key in self.in_flight: return False self.in_flight.add(idempotency_key) return True def complete_request(self, idempotency_key: str, outcome: dict) -> None: self.in_flight.discard(idempotency_key) self.completed_requests[idempotency_key] = outcome def handle_resume( buf: ReplayBuffer, session: SessionState, last_event_id: int, retry_idempotency_key: str, ) -> dict: # 1. Transport layer: replay only what is safely retained. try: events = buf.replay_after(last_event_id) except ReplayDivergenceError as e: # Force client re-init rather than silently replaying a gap. raise ReplayDivergenceError(str(e)) from e # 2. Request layer: a retry for an already-completed key must NOT execute again. if retry_idempotency_key in session.completed_requests: return { "replayed_events": events, "request_outcome": session.completed_requests[retry_idempotency_key], "executed_again": False, } if retry_idempotency_key in session.in_flight: # Still running server-side; tell client to wait, do not re-execute. return { "replayed_events": events, "request_outcome": None, "executed_again": False, "note": "request still in flight; await terminal event", } # Fresh execution is legitimate here. if not session.begin_request(retry_idempotency_key): raise ReplayDivergenceError( f"idempotency key {retry_idempotency_key} entered inconsistent state" ) return {"replayed_events": events, "request_outcome": None, "executed_again": True} ```