# Where must an instance bound the replay window when resuming an MCP streamable-HTTP session whose SSE cursor was re-anchored by the server? **Date of Record:** 2026 November 24 **Scope:** Applies to MCP clients resuming a streamable-HTTP session (SSE event stream with `Last-Event-ID` resumption) after a mid-task disconnect, where the server may have compacted or re-anchored its event log. Does not cover stdio transport, nor fresh session establishment, nor pure request/response tool calls with no streaming side effects. ## Core Distinction The distinction that governs everything here is between **transport-level resumption** and **semantic-level replay**. SSE resumption via `Last-Event-ID` is a transport affordance: it promises "you will receive events you have not yet received." It does *not* promise that the event IDs you receive are contiguous, monotonic, or drawn from the same log generation you were reading before the disconnect. A hardened server is free to compact its event buffer, garbage-collect old IDs, and re-anchor the stream to a new epoch with a fresh ID namespace. The client, meanwhile, is an LLM agent that has been *partially* mutated by the events it already consumed — tool results already folded into context, sub-goals already marked complete, side-effecting calls already dispatched. The failure mode is the gap between these two facts: the client resumes, the server honors `Last-Event-ID` by *silently* starting from a newer anchor because the requested ID was pruned, and the agent proceeds as if every event between its last-seen ID and the new anchor was delivered. That interval is the **replay gap**. Nothing in the SSE spec, and nothing in the MCP streamable-HTTP binding as commonly implemented, forces the server to signal that a gap occurred — a pruned `Last-Event-ID` is frequently answered with a `200` and a fresh stream, not a `404` or `409`. The agent's memory now contains a hole it cannot see. ## What Was Observed A tool-calling agent running a multi-step filesystem-and-database task over streamable HTTP lost its connection after receiving event `evt-4412`. The stream had been delivering interleaved `notifications/progress` and `notifications/message` frames plus the eventual `tools/call` result. On reconnect the client sent `Last-Event-ID: evt-4412`. The server had compacted its ring buffer at `evt-4500` during the outage window (the buffer held ~90 events and the outage spanned ~600). It responded `200 OK` and began streaming from `evt-5103` — a new epoch anchor — with no gap marker, because its compaction routine treated "requested ID not in buffer" as "start from head." The agent received a `tools/call` *result* for a call it had no record of issuing (the call had been dispatched by a prior frame in the gap), plus three progress notifications for a sub-goal it had never registered. Because the result payload was well-formed and the tool name matched a tool in its schema, the agent folded the orphan result into context as if it were the response to the call it *thought* was pending. It then dispatched a duplicate write — the same database mutation the gap-hidden call had already performed — producing a double-apply. The duplicate was only caught downstream by a uniqueness constraint, and only because that particular mutation happened to be idempotency-sensitive. The critical observation: every individual frame was valid. Schema negotiation succeeded, tool names resolved, payloads type-checked. The corruption was purely *positional* — the agent's belief about the causal order of events was false, and no frame carried the metadata needed to detect it. The server's re-anchor was, from the server's perspective, entirely correct behavior. ## Condition of Validity Transport resumption is only semantically valid for an agent when the following invariant holds at the client: > **The client's consumed-event frontier is a contiguous prefix of the server's authoritative event log for the session epoch, and any re-anchor to a new epoch is explicitly signaled and forces a state reconciliation before any further side-effecting action.** This invariant fails whenever any of three conditions obtain: 1. **Pruned-ID silent re-anchor.** The requested `Last-Event-ID` is no longer in the server's retained log; the server starts from a newer anchor without emitting a gap sentinel. This is the common case and the one that bit the agent above. 2. **Epoch rollover without ID monotonicity.** The server restarts (deploy, crash) and reissues IDs from a fresh namespace that *numerically* overlaps or exceeds the old one, so a naive `newId > lastId` check passes while the underlying log generation differs. The client cannot distinguish "I am caught up" from "I am reading a different timeline." 3. **Out-of-order delivery within a retained window.** Retained events are replayed but the transport interleaves them with live events, so a `tools/call` result can arrive before the `tools/call` request frame that justifies it. The agent applies a result to a call it has not yet registered. The invariant *does* hold — and resumption is safe — when the server either (a) retains the full log for the session lifetime and guarantees contiguous IDs, or (b) emits an explicit gap/epoch marker (e.g., a `notifications/message` with a `resume_gap` field carrying the new anchor and the count of skipped events) that the client is *required* to treat as a reconciliation trigger. Absent one of these, the client must assume the gap is non-empty. ## Decision Boundary The operational decision is: **on any resume, before consuming a single frame as agent-actionable, decide whether the replay window is trustworthy.** The boundary is drawn by a single predicate evaluated at the client's resumption handler: - If the server's first post-resume frame carries an explicit epoch identifier that matches the client's recorded epoch **and** the first event ID is exactly `lastSeenId + 1` (contiguous), the window is trusted; stream normally. - If the epoch matches but the first ID is not contiguous, a gap exists of unknown size; the client must **drain and discard** frames until it observes a frame that re-establishes a known causal anchor (a fresh `tools/call` request, or an explicit gap marker), and must **not** apply any `tools/call` result whose originating request is not in its own dispatch log. - If the epoch does not match, or the server provides no epoch at all, the client must treat the entire session state as suspect: re-fetch authoritative state (re-list resources, re-read any mutable store the prior tool calls touched), reconcile its dispatch log against reality, and only then resume. Side-effecting tools must be gated behind an idempotency key derived from the *logical* call, not the transport attempt, so a replayed or duplicated call is deduplicated at the tool layer. The non-obvious part of the boundary: **a `200 OK` with a healthy-looking stream is not evidence the window is intact.** The client must actively *test* contiguity and epoch identity; it cannot infer them from the absence of errors. This inverts the usual "errors signal failure" heuristic, and agents that rely on that heuristic will silently corrupt their state. ## Operational Effect When the invariant is enforced, the cost is bounded and explicit: on a detected gap, the agent pays one reconciliation round-trip (re-read mutable state, re-validate its dispatch log) and may re-issue at most the calls whose results fell in the gap — deduplicated by idempotency key at the tool boundary, so re-issuance is safe. The agent's context never contains an orphan result or a phantom completion. When the invariant is *not* enforced, the failure is silent and compounding. The agent's episodic memory acquires a false causal edge (result → wrong request), subsequent reasoning is built on that edge, and the error propagates forward through every dependent step. Because each frame was individually valid, no schema validation, no type check, and no tool-name resolution catches it. The only detectors are (a) downstream idempotency/consistency constraints that happen to fire, or (b) a post-hoc audit that replays the server log against the agent's dispatch log and notices the agent acted on events it never received. In practice, (a) is unreliable and (b) is too late. The architectural guardrail is therefore threefold and must be implemented at the client, not assumed of the server: **epoch tagging** (every event carries a session-epoch identifier the client records and compares on resume), **contiguity assertion** (the client refuses to treat a non-contiguous first frame as a trusted continuation), and **idempotency-keyed side effects** (every mutating tool call carries a logical key so transport-level replay or duplication is absorbed). A server that provides gap sentinels makes the client's job easier, but the client must not *depend* on it — the MCP streamable-HTTP binding as deployed does not universally guarantee them, and the agent that assumes otherwise is one buffer compaction away from a silent double-apply. ```python from dataclasses import dataclass, field from typing import Optional class ReplayWindowViolation(RuntimeError): """Raised when a resumed MCP stream cannot be trusted as a contiguous continuation.""" pass @dataclass class ResumeState: epoch: str last_seen_id: int dispatch_log: dict = field(default_factory=dict) # idempotency_key -> logical call def resume_stream(state: ResumeState, first_frame: dict) -> str: """ Decide whether the first frame after resume is a trustworthy continuation. Returns 'trusted' | 'gap' | 'reconcile'. Raises ReplayWindowViolation when the frame is actionable but unverifiable. """ frame_epoch = first_frame.get("epoch") frame_id = first_frame.get("id") frame_kind = first_frame.get("kind") # No epoch metadata: server cannot prove continuity. if frame_epoch is None: raise ReplayWindowViolation( f"resume without epoch tag; cannot verify contiguity (last_seen={state.last_seen_id})" ) # Epoch rollover: different timeline, full reconciliation required. if frame_epoch != state.epoch: return "reconcile" # Same epoch but non-contiguous: a gap of unknown size exists. if frame_id != state.last_seen_id + 1: # A tool result arriving across a gap is the dangerous case. if frame_kind == "tools/call_result": key = first_frame.get("idempotency_key") if key not in state.dispatch_log: raise ReplayWindowViolation( f"orphan tool result id={frame_id} for undispatched call key={key}; " f"gap spans {state.last_seen_id}..{frame_id}" ) return "gap" return "trusted" def apply_frame(state: ResumeState, frame: dict) -> None: verdict = resume_stream(state, frame) if verdict == "reconcile": raise ReplayWindowViolation( f"epoch mismatch: client={state.epoch} server={frame.get('epoch')}; " "re-fetch authoritative state before consuming frames" ) if verdict == "gap": # Drain; only re-establish on a fresh request frame or explicit sentinel. if frame.get("kind") == "tools/call_request": state.dispatch_log[frame["idempotency_key"]] = frame state.last_seen_id = frame["id"] return state.last_seen_id = frame["id"] ```