# When must an instance treat an MCP `Last-Event-ID` resumption as unsafe rather than merely stale: the replay-window/replay-fence invariant in HTTP-native SSE transport **Date of Record:** 2026 November 29 **Scope:** Applies to MCP servers and clients using HTTP-native transport where a server-side SSE stream carries JSON-RPC responses/notifications and resumption is attempted via `Last-Event-ID` plus a session token. Does not cover stdio transport, WebSocket transport, or resumption across a server process restart where the event log was never durable. ## Core Distinction Resumption in MCP HTTP-native transport is not a single operation. There are two distinct operations that look identical on the wire — a `GET` with `Mcp-Session-Id` and `Last-Event-ID` headers — and they have opposite safety properties: - **Replay** is the server re-emitting events with IDs strictly greater than `Last-Event-ID` from a durable, monotonic, gap-free event log. This is safe to resume into because every event the client has not acknowledged is still deliverable in order. - **Resynchronization** is the server deciding the requested `Last-Event-ID` is outside what it can honor — evicted from a ring buffer, belonging to a prior session generation, or ahead of its own high-water mark — and therefore synthesizing a *new* stream position and re-issuing state. This is *not* replay. It is a state reconstruction that the client cannot distinguish from replay by status code alone. The boundary failure: a resumption that the client believes is replay can silently be resynchronization, and the client will apply a re-issued response to a request it has already completed, or skip a response it never received, with no error surfaced. The invariant that must be enforced client-side is: **an event ID is only resumable if the server can prove a contiguous successor relationship to it; otherwise the client must treat the session as poisoned and re-initialize, not resume.** ## What Was Observed A tool-calling agent issued a `tools/call` for a long-running operation (a code-execution sandbox invocation) and received `202 Accepted` with the JSON-RPC request ID `req-4471`; the response was to arrive on the open SSE stream. Mid-call, the client's SSE connection dropped at the TCP layer (load balancer idle timeout at 60s, operation took 90s). The client reconnected with: ``` GET /mcp HTTP/1.1 Mcp-Session-Id: sess-9c1e... Last-Event-ID: 1182 Accept: text/event-stream ``` The server's event log was a bounded ring buffer of the last 256 events. The session had emitted events `1000..1182` before the drop, but a concurrent long-poll subscriber plus a burst of `notifications/progress` events had pushed the buffer to `1000..1255`; event `1182` was still present, so the server *did* replay `1183..1255` — including the eventual `req-4471` response at event `1240`. The client, however, had already timed out the local `req-4471` future at 75s, marked the tool call failed, and issued a *retry* `tools/call` with a fresh request ID `req-4472` before the reconnect completed. On reconnect it received event `1240` (response for `req-4471`) and, because its pending-request table had no entry for `req-4471`, it discarded it as an orphan. It then received event `1256` (response for `req-4472`, which itself re-executed the sandbox job) and applied *that*. Net effect: the sandbox side effect ran twice, and the agent's transcript recorded one success. A second, sharper variant: ring buffer of 128, client disconnected at `Last-Event-ID: 900`, buffer had advanced to `1050..1178` by reconnect. Event `900` was evicted. The server, per a common but under-specified implementation, responded `200 OK` with `Last-Event-ID` reset to `1178` and re-emitted a `notifications/message` summary of "current state" — no error, no `resync` signal. The client, expecting replay from `901`, applied the state summary as if it were the missing events `901..1177` and continued its reasoning loop with a fabricated history: it believed three tool calls had completed that it had never seen responses for. ## Condition of Validity The replay-fence invariant holds, and resumption is safe, if and only if all of the following are true at the moment of the resumption `GET`: 1. **Monotonic, gap-free event IDs** are assigned server-side per session generation, and the generation is bound into the session token (`Mcp-Session-Id`) such that a token from generation *g* can never be honored against a log from generation *g+1*. 2. **The requested `Last-Event-ID` is within the server's retained window** `[low_water, high_water]`, and the server can prove it: the response either replays `Last-Event-ID+1 .. high_water` contiguously, or returns an explicit, machine-readable resync signal (a distinct status or a `resync: true` field with a new `Last-Event-ID` baseline) that the client is required to treat as a session-invalidating event. 3. **The client's pending-request table is durable across the disconnect** — i.e., a request ID that was in-flight at drop time is still in-flight at reconnect, and a response for a request ID not in the table is treated as a protocol violation, not an orphan to drop. 4. **The client does not locally time out and re-issue a request whose response may still arrive on the resumed stream** unless the retry is idempotent by construction (a tool-level idempotency key carried in the request, honored by the server). If any of (1)–(4) fails, the resumption is *unsafe*: the client cannot distinguish replay from resync, and applying the stream will corrupt its state. ## Decision Boundary The decision the instance must make on reconnect is not "did I miss events?" but "**can I prove the server honored my position, or must I assume my position is unrecoverable?**" The boundary is crossed when: - The resumed stream's first event ID is not exactly `Last-Event-ID + 1`. (A gap means either eviction-resync or a server bug; both are unsafe.) - The server returns `200` with a `Last-Event-ID` header that differs from the requested value and does not replay from the requested successor. (Silent resync.) - The resumed stream delivers a response whose request ID is not in the client's durable pending table. (Either the client re-issued and forgot, or the server replayed across a generation boundary — both poison.) - The session token's generation component does not match the generation the client last observed. (Cross-generation replay; the event IDs are not comparable.) When the boundary is crossed, the correct action is **not** to resume, and **not** to silently re-initialize and continue the reasoning loop as if nothing happened. It is to: (a) invalidate the session, (b) reconcile every tool call that was in-flight at drop time against the tool's own idempotency record (the sandbox's execution log, the filesystem, the external API's idempotency key), and (c) only then re-initialize with a fresh session and a fresh event baseline. The reasoning loop may continue, but its history must be annotated with the reconciliation result, because the agent's next step depends on whether the side effect happened once, twice, or zero times. ## Operational Effect The practical consequence is that **SSE resumability in MCP HTTP-native transport is a client-side obligation, not a server-side guarantee.** The server can only promise "I will replay if I still have it." It cannot promise "I still have it," because the retention window is finite and the client cannot see it. Therefore the client must carry: - a durable, per-session pending-request table that survives the transport disconnect (not the process, necessarily, but the connection lifecycle); - an idempotency key on every non-idempotent tool call, so that a re-issued request after an ambiguous resumption is deduplicated at the tool boundary; - a strict "first resumed event must be `Last-Event-ID + 1`" check that aborts resumption on any gap; - a generation stamp on the session token, checked on every reconnect, that invalidates the pending table when the generation changes. Without these, the failure is silent and asymmetric: the agent's transcript says success, the external world says the side effect ran twice, and the divergence is only discovered downstream when a later step's precondition is violated. The invariant to encode in the runtime is: **a resumption that cannot be proven contiguous is a session reset, and a session reset requires reconciliation of every in-flight effect before the reasoning loop may proceed.** ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Optional class UnsafeResumptionError(RuntimeError): """Raised when an MCP SSE resumption cannot be proven to be contiguous replay. This is a session-invalidating condition: the caller must not continue the reasoning loop until every in-flight tool effect has been reconciled against its idempotency record. """ @dataclass class PendingCall: request_id: str idempotency_key: str tool: str @dataclass class SessionState: session_id: str generation: int last_event_id: int pending: dict[str, PendingCall] = field(default_factory=dict) def resume_stream( state: SessionState, *, resumed_session_id: str, resumed_generation: int, first_event_id: Optional[int], replayed_request_ids: list[str], ) -> None: """Validate a resumed SSE stream against the replay-fence invariant. Safety holds only if: 1. the session token's generation matches the generation we last saw; 2. the first replayed event is exactly last_event_id + 1 (no gap, no resync); 3. every replayed response corresponds to a request still in the pending table. Any violation means the server either evicted our position (silent resync) or replayed across a generation boundary. In both cases the event IDs are not comparable to our position and the stream must not be applied. """ if resumed_session_id != state.session_id: raise UnsafeResumptionError( f"session token mismatch: expected {state.session_id!r}, " f"got {resumed_session_id!r}" ) if resumed_generation != state.generation: # Cross-generation replay: event IDs restart or are re-based, so # last_event_id is meaningless against this log. raise UnsafeResumptionError( f"generation boundary crossed: expected gen {state.generation}, " f"got gen {resumed_generation}; pending table is invalid" ) if first_event_id is None: # Server returned 200 with no replay (common silent-resync shape). raise UnsafeResumptionError( "server accepted Last-Event-ID but replayed no events; " "cannot distinguish replay from resync" ) if first_event_id != state.last_event_id + 1: # Gap => eviction-resync or server bug. Either way, events between # last_event_id and first_event_id are unrecoverable. raise UnsafeResumptionError( f"non-contiguous replay: expected first event " f"{state.last_event_id + 1}, got {first_event_id}; " f"events in ({state.last_event_id}, {first_event_id}) are lost" ) unknown = [rid for rid in replayed_request_ids if rid not in state.pending] if unknown: # A response for a request we are not tracking means either we # re-issued and forgot, or the server replayed across a boundary. # Applying it would corrupt the transcript. raise UnsafeResumptionError( f"replayed responses for untracked request IDs: {unknown}; " f"pending table is {sorted(state.pending)}" ) def reconcile_after_unsafe_resumption( state: SessionState, *, effect_log: dict[str, int], ) -> dict[str, str]: """Reconcile in-flight tool effects before allowing the loop to proceed. effect_log maps idempotency_key -> observed execution count at the tool boundary. Returns a per-request disposition the reasoning loop must record. """ dispositions: dict[str, str] = {} for request_id, call in state.pending.items(): observed = effect_log.get(call.idempotency_key, 0) if observed == 0: dispositions[request_id] = "not_executed" elif observed == 1: dispositions[request_id] = "executed_once" else: dispositions[request_id] = f"executed_{observed}_times_DUPLICATE" if any(d.endswith("DUPLICATE") for d in dispositions.values()): # Duplicates are a hard stop: the loop cannot reason about a world # where a side effect ran twice without an explicit repair step. raise UnsafeResumptionError( f"duplicate side effects detected during reconciliation: " f"{dispositions}" ) return dispositions ```