# What happens when an instance resumes an MCP stream after `Last-Event-ID` has been garbage-collected: the resumption-silence gap and the replay-identity invariant **Date of Record:** 2026 November 28 **Scope:** Applies to MCP servers using the HTTP-native transport with SSE-style streaming (`text/event-stream` with `id:` fields) and client-side session resumption via `Last-Event-ID` on reconnect. Does not apply to stdio transports, nor to servers that never emit event IDs, nor to stateless request/response MCP servers with no resumable stream. ## Core Distinction The distinction that matters here is between **resumption being refused** and **resumption being silently truncated**. An MCP server that has garbage-collected the event IDs referenced by a client's `Last-Event-ID` MUST either (a) reject the resume with an explicit error so the client knows its view of the session is invalid, or (b) replay from the beginning of the retained buffer *with a signal that events were lost*. What actually happens in many implementations is a third, undocumented behavior: the server accepts the connection, opens a fresh event stream, begins emitting *new* events from the current head, and never acknowledges that the gap between `Last-Event-ID` and the current head contained events the client will never see. The stream looks healthy. The session ID is unchanged. The connection is 200 OK. And the agent has silently lost a window of tool results, capability updates, or handoff notifications that it will now reason over as if they never existed. This is not a transport error. It is a **continuity invariant violation that presents as a successful operation** — the most dangerous class of failure for an autonomous agent, because every layer above the transport (retry logic, health checks, the agent's own self-assessment of state) reports green. ## What Was Observed A long-running agent (call it the *consumer*) maintains an MCP session against a server that fans out tool-call results and asynchronous notifications over an SSE stream. The consumer persists `Last-Event-ID` after each processed event. The server retains a bounded ring buffer of recent events — say 1,000 entries or 15 minutes, whichever expires first — keyed by monotonically increasing event IDs. The failure trace: 1. The consumer processes events up to ID `48211`, persists `Last-Event-ID: 48211`, then blocks on a long `tools/call` whose result is delivered *as a stream event* (ID `48212`) rather than as a synchronous response body. 2. The consumer's network path blips. TCP connection drops. The consumer's reconnect logic fires after a backoff of, say, 40 seconds. 3. During the gap, the server emits 1,400 events (a burst of peer-agent notifications, capability-change announcements, and the pending tool result). The ring buffer evicts IDs `48212` through `48611`. The current head is `49612`. 4. The consumer reconnects with `Last-Event-ID: 48211`. The server's resume handler looks up `48211` in the buffer, finds it absent, and — because the handler was written to "resume from the last known point or fall back to live" — falls back to **live-only streaming**. It emits a `200 OK` with a fresh `text/event-stream`, sets no `id:` cursor backfill, and immediately streams event `49613` onward. 5. The consumer receives `49613`, sees a monotonically increasing ID greater than its stored `48211`, and its (naive) continuity check passes: *"the stream advanced, therefore I am caught up."* It overwrites `Last-Event-ID` with `49613`. 6. The tool result that was supposed to arrive as `48212` never arrives. The `tools/call` the consumer is blocked on has no completion event. Depending on the consumer's timeout policy, it either hangs until a wall-clock timeout, or — worse — a *different* later event (`49650`, an unrelated notification) is misattributed by a sloppy demultiplexer as the completion of the pending call. The observable symptom is not "connection failed." It is "the agent proceeded with a plausible but wrong belief about the world," typically surfacing much later as a duplicated side effect (it re-issues the tool call because it never saw the result) or as a state divergence from peer agents (it missed a capability-change announcement and now calls a method the peer no longer exposes). A second, quieter variant: the server *does* retain `48211` but the buffer is per-connection rather than per-session. On reconnect, the server allocates a new connection-scoped buffer, and `Last-Event-ID: 48211` resolves against an empty buffer — same silent-truncation outcome, but the server believes it is behaving correctly because the ID was "not found and not an error." ## Condition of Validity The silent-truncation failure requires all of the following to hold simultaneously; if any one is absent, the failure does not manifest in this form: - **Event IDs are treated as a monotonic cursor, not as an identity.** The consumer's continuity check is `new_id > stored_id`, which cannot distinguish "caught up" from "skipped a window." The invariant that would save it — *contiguity* of the ID sequence — is not checked because the protocol does not require IDs to be contiguous, only ordered. - **The server's resume semantics on a missing ID are unspecified or default to live-fallback.** The MCP HTTP transport spec mandates that a server *may* support resumption and that `Last-Event-ID` be honored, but does not mandate a specific behavior when the referenced ID has been evicted. Implementations diverge: some 400, some start fresh silently, some replay from buffer start. - **The pending operation's completion is delivered as a stream event, not a request-correlated response.** If the tool result came back on the original HTTP response body or via a correlation ID the consumer tracks independently, the loss of `48212` would be caught by the pending-call timeout. When completion is *only* signaled by stream position, the stream is the sole source of truth and its silent gap is unrecoverable. - **The consumer persists `Last-Event-ID` optimistically** — writing the new cursor before confirming that no gap occurred, or without an independent check that all outstanding requests have been resolved. The invariant that must hold for correctness, and which none of the above enforces: > **For any resumption, the consumer must be able to prove that the set of events between its persisted cursor and the first event of the resumed stream is empty — or must be told explicitly that it is not.** ## Decision Boundary The boundary is between **cursor-as-position** and **cursor-as-identity-with-gap-detection**. Concretely, an implementation is on the safe side of the boundary if and only if it satisfies at least one of: 1. **Server-side explicit gap signaling.** On a resume where `Last-Event-ID` is not in the retained buffer, the server MUST emit a distinguished control event (e.g., `event: resync-required` with the evicted range, or an HTTP `409`/`412` before opening the stream) rather than silently falling back to live. The consumer MUST treat any resume that does not begin with either the exact successor ID or an explicit gap notice as a hard session-invalidation. 2. **Consumer-side contiguity or sequence-completeness check.** If the protocol emits a per-session sequence number or a "no gaps since" marker, the consumer verifies it. Absent that, the consumer treats *any* reconnect as requiring a full state re-synchronization (re-issue outstanding calls, re-fetch capability manifests) rather than trusting the stream to have been continuous. 3. **Completion decoupled from stream position.** Pending operations are correlated by request ID in a side table with their own timeouts, so that a missing completion event is detected by the operation's timeout rather than inferred from stream advance. The stream becomes a *notification* channel, not the *authority* on whether work completed. The decision the operator faces: **is the cost of a false-positive resync (re-fetching state after every reconnect) lower than the cost of a false-negative (silently reasoning over a gap)?** For agents whose actions have side effects — issuing payments, mutating shared state, sending messages to peers — the answer is almost always yes, and the boundary should be drawn at option 1 or 3. For read-only observers, option 2's coarser resync may be acceptable. What is *not* on the safe side, and is the common default: trusting `200 OK` + increasing event IDs as proof of continuity. That is the boundary violation. ## Operational Effect When the silent-truncation gap occurs, the operational consequences are downstream and delayed, which is why it is under-instrumented: - **Duplicate side effects.** The consumer, never seeing the tool result, retries the call. If the tool is not idempotent, the effect happens twice. The retry succeeds (the second call's result *is* delivered on the live stream), so the agent's logs show a clean success and the duplicate is invisible until reconciliation. - **Capability drift.** A missed `notifications/tools/list_changed` or peer capability announcement means the agent operates on a stale schema. It calls a method the peer removed; the peer returns an error the agent interprets as a transient fault and retries, compounding. - **False consensus in multi-agent setups.** If the lost events were peer votes or auditor attestations, the agent proceeds believing consensus was reached on a smaller quorum than actually required — or the reverse, believing a proposal failed when it passed. - **Unrecoverable cursor corruption.** Once the consumer overwrites `Last-Event-ID` with the post-gap head (`49613`), the evidence of the gap is destroyed. Post-mortem cannot distinguish "no events in the window" from "events evicted and skipped," because the persisted cursor now points past the gap. The guardrail is not a retry policy — retries make it worse by destroying the cursor faster. The guardrail is the **resume-handshake invariant**: a resumed stream is only trusted if its first event is either (a) the immediate successor of the persisted cursor, or (b) preceded by an explicit, machine-readable gap declaration. Anything else invalidates the session and forces a full resync. This must be enforced at the transport adapter, below the agent's reasoning loop, because a probabilistic reasoner will always find a narrative in which "the stream advanced, so I'm fine" is true. The following reference implementation encodes the invariant as a hard failure rather than a soft fallback, and refuses to advance the persisted cursor until continuity is proven. ```python from __future__ import annotations import dataclasses from typing import Iterable, Optional class StreamContinuityError(RuntimeError): """Raised when a resumed MCP SSE stream cannot prove continuity with the consumer's persisted Last-Event-ID cursor. This is a hard session-invalidating condition: the consumer must NOT advance its cursor or trust the stream.""" @dataclasses.dataclass(frozen=True) class StreamEvent: event_id: int # monotonically increasing per session kind: str # "notification" | "result" | "gap-notice" | ... payload: dict @dataclasses.dataclass class ResumeState: last_event_id: Optional[int] = None # persisted cursor; None = fresh session pending_requests: set[str] = dataclasses.field(default_factory=set) def resume_stream( server_events: Iterable[StreamEvent], state: ResumeState, *, gap_notice_kinds: frozenset[str] = frozenset({"gap-notice", "resync-required"}), ) -> Iterable[StreamEvent]: """ Consume a resumed server event stream, enforcing the continuity invariant: A resumed stream is trusted iff its first event is either (a) the immediate successor of state.last_event_id, or (b) preceded by an explicit gap-notice declaring the lost range. On violation, raise StreamContinuityError WITHOUT mutating state.last_event_id, so the caller can force a full resync rather than silently reasoning over a gap. """ events = iter(server_events) try: first = next(events) except StopIteration: # A resumed stream that immediately closes is suspicious but not proof of a gap; # treat as an empty no-op only if we had no pending work. if state.pending_requests: raise StreamContinuityError( f"resumed stream closed immediately with {len(state.pending_requests)} " f"pending request(s); continuity unverifiable" ) return if state.last_event_id is None: # Fresh session: accept whatever head the server offers. yield first yield from events return expected_successor = state.last_event_id + 1 if first.kind in gap_notice_kinds: # Explicit gap declaration: server told us what we lost. Accept, but # force the caller to reconcile (it sees the gap-notice payload). yield first for ev in events: yield ev return if first.event_id != expected_successor: # Silent truncation: the server fell back to live streaming past an # evicted window. This is the failure this guard exists to catch. raise StreamContinuityError( "resumed stream is not contiguous with persisted cursor: " f"last_event_id={state.last_event_id}, expected first id=" f"{expected_successor}, got {first.event_id} " f"(kind={first.kind!r}). Server likely evicted the retained buffer " "and fell back to live-only streaming without a gap notice. " "Cursor NOT advanced; full resync required." ) # Contiguous: safe to advance. yield first state.last_event_id = first.event_id for ev in events: if ev.event_id != state.last_event_id + 1 and ev.kind not in gap_notice_kinds: raise StreamContinuityError( f"mid-stream discontinuity: expected id={state.last_event_id + 1}, " f"got {ev.event_id} (kind={ev.kind!r})" ) yield ev state.last_event_id = ev.event_id def handle_resume(server_events: Iterable[StreamEvent], state: ResumeState) -> None: """Adapter entry point: on continuity failure, invalidate the session and force a full resync instead of trusting the (possibly gapped) stream.""" try: for ev in resume_stream(server_events, state): if ev.kind == "result": state.pending_requests.discard(ev.payload.get("request_id", "")) except StreamContinuityError: # Do NOT retry the same resume with the same cursor: that destroys evidence. # Invalidate, re-fetch capability manifests, and re-issue outstanding calls. state.pending_requests.clear() raise ```