# Where must an instance reject a resumed MCP stream when the server's `Last-Event-ID` replay window has already been compacted: the silent event-gap invariant in HTTP-native transport **Date of Record:** 2026 December 1 **Scope:** Applies to MCP clients that consume server-sent-event (SSE) streams over HTTP-native transport and attempt session resumption via `Last-Event-ID` after a transport drop, where the server maintains a bounded replay buffer. Does not apply to stdio transport, nor to servers that guarantee unbounded replay or require full session re-initialization on every reconnect. ## Core Distinction There are two ways an SSE stream can "resume," and they are not equivalent: 1. **Replay-contiguous resumption** — the client reconnects with `Last-Event-ID: N`, and the server replays every event `N+1, N+2, …` before switching to live tailing. The client's event sequence is gap-free. 2. **Cursor-acknowledged resumption** — the client reconnects with `Last-Event-ID: N`, but the server's ring buffer has already evicted events `N+1 … M` (compaction). The server either (a) silently begins live tailing at `M+1`, or (b) returns a fresh stream whose first event has an ID far ahead of `N`. The boundary failure lives in case (2a): the server accepts the resume, returns `200 OK`, opens the stream, and the client has no protocol-level signal that events `N+1 … M` were dropped. The stream is *syntactically* valid and *semantically* lossy. Because MCP tool-call results, resource-update notifications, and progress events are all carried as discrete SSE events with monotonic IDs, a gap in the ID sequence is the *only* in-band evidence of loss — and only if the client is checking. ## What Was Observed A client agent held a long-running MCP session against a server exposing a `run_pipeline` tool that emits progress notifications (`notifications/progress`) and a terminal `notifications/tools/result` event. Each event carried an `id:` field assigned by a monotonic counter persisted in the server's session record. Trigger sequence: 1. Client received event `id: 4102` (progress 62%). 2. Network partition for ~90s (NAT rebind on the client side; TCP RST not observed by client). 3. Client's SSE reader raised a transport error; client's resumption logic reconnected with `Last-Event-ID: 4102` and the same `Mcp-Session-Id`. 4. Server's replay ring buffer is capped at 256 events. During the 90s partition the pipeline emitted 900+ events (high-frequency progress ticks plus a fan-out of sub-tool notifications). Events `4103 … 4990` had been evicted. 5. Server accepted the resume, emitted `: keepalive`, then began live tailing at `id: 4991` (a `notifications/progress` at 98%). 6. Client parsed `id: 4991`, saw a valid event, updated its `last_event_id` to 4991, and continued. **No error was raised.** The client's state machine believed progress went 62% → 98% and then to completion. The terminal `notifications/tools/result` for the pipeline had been in the evicted window (it was emitted at `id: 4780` because the pipeline completed *during* the partition and a subsequent sub-tool cleanup emitted further notifications). The client never saw the result. It waited on a `tools/call` future that would never resolve, until its own 300s call timeout fired — at which point it reported a *timeout*, not a *loss*, and retried the entire `run_pipeline` invocation, producing a duplicate side effect on the server. The failure is not the eviction. Eviction is a legitimate bounded-memory policy. The failure is that the server's resume handler treated `Last-Event-ID: 4102` as satisfiable when it was not, and emitted no `id` discontinuity signal, and the client treated the first post-resume event as contiguous without verifying `first_id == last_event_id + 1`. ## Condition of Validity The replay-contiguous invariant holds only under the conjunction: - **Server-side:** the replay buffer has not evicted any event with ID in `(last_event_id, current_head]` at the moment the resume request is processed. Equivalently: `buffer.min_id ≤ last_event_id + 1`. - **Transport-side:** the server, on inability to satisfy contiguity, MUST either (i) return `409 Conflict` with a machine-readable `replay_gap` body indicating the earliest available ID, or (ii) open the stream with a synthetic control event (e.g. `event: replay-gap` carrying `{requested: 4102, earliest: 4991}`) *before* any live event. - **Client-side:** on resume, the client MUST assert `first_received_id == last_event_id + 1` (or handle the explicit gap signal) before applying any event to its state machine. The invariant is *invalid* — and the client MUST NOT assume contiguity — whenever any of these is unverifiable. In particular, a `200 OK` on resume is not evidence of contiguity; it is only evidence that the session ID was accepted. ## Decision Boundary The precise decision the client must make on the first event after a resume: ``` let expected = last_event_id + 1 let observed = first_event.id if observed == expected: accept, contiguity holds elif observed > expected: GAP — events [expected, observed) lost → do NOT apply observed to state → escalate: re-initialize session or request explicit replay from server elif observed < expected: server replayed overlapping events → dedupe by id, accept idempotently ``` The dangerous branch is `observed > expected`, because it is the branch where a naive client does the *wrong* thing silently: it accepts, advances its cursor, and loses the semantic content of the gap. The gap may contain the very terminal event the agent is blocked on. There is no way for the client to distinguish "gap contained only progress ticks" from "gap contained the terminal result" without asking the server — and the server, having evicted, cannot answer from the buffer. Two secondary boundaries: - **Gap-vs-keepalive:** SSE comment lines (`: keepalive`) carry no `id` and MUST NOT be used to advance the cursor. A client that treats any received byte as evidence of liveness will mask the gap. - **Gap-vs-reconnect-budget:** a client that caps reconnects (e.g. 3 attempts) and treats a gap as "just reconnect again" will, on a fast-producing server, re-enter the same eviction window and exhaust its budget without ever achieving contiguity. The correct response to a gap is *not* another `Last-Event-ID` resume against the same buffer; it is a session-level re-initialization or an explicit `tools/call` status query. ## Operational Effect The observable consequence of violating this invariant is **phantom blocking followed by duplicate execution**: the agent's call future never resolves because its terminal event was in the evicted window, the call-level timeout fires, and the agent's retry policy re-invokes a non-idempotent tool. The server sees two `run_pipeline` invocations for one logical intent. Downstream, this manifests as duplicated side effects (double writes, double charges, double deploys) that are *correlated with network partitions of duration greater than `buffer_size / event_rate`* — a threshold the client cannot compute because it does not know the server's buffer size or event rate. The required guardrail is a **contiguity assertion at the resume seam**: the client treats the first event after any resume as untrusted until `id == last_event_id + 1`, and on a forward gap refuses to advance state, marks the session `RESUME_GAP`, and escalates to full re-initialization (new `Mcp-Session-Id`, re-query tool state) rather than retrying the call. The server-side counterpart is to *never* silently satisfy an unsatisfiable `Last-Event-ID`: return an explicit gap signal or a non-2xx status. Both halves are required; either alone leaves a silent-loss path. ```python import dataclasses from typing import Optional class McpResumeGapError(RuntimeError): """Raised when a resumed MCP SSE stream cannot prove contiguity.""" @dataclasses.dataclass class ResumeState: last_event_id: int session_id: str def validate_resume_seam( state: ResumeState, first_event_id: Optional[int], first_event_is_keepalive: bool, ) -> int: """ Called on the first non-comment SSE frame after a resume. Returns the new cursor if contiguity holds; raises otherwise. """ if first_event_is_keepalive: # A keepalive proves liveness, not contiguity. Do not advance. raise McpResumeGapError( f"resume for session {state.session_id}: first frame is keepalive; " f"cannot prove contiguity past last_event_id={state.last_event_id}" ) if first_event_id is None: raise McpResumeGapError( f"resume for session {state.session_id}: first event carries no id; " f"server did not honor Last-Event-ID={state.last_event_id}" ) expected = state.last_event_id + 1 if first_event_id == expected: return first_event_id if first_event_id < expected: # Overlapping replay: idempotent dedupe is safe, cursor does not regress. return state.last_event_id # first_event_id > expected: forward gap. Events [expected, first_event_id) # were evicted from the server's replay buffer. The stream is semantically # lossy; the terminal event for an in-flight call may be inside the gap. raise McpResumeGapError( f"resume for session {state.session_id}: forward gap detected, " f"expected id {expected} but observed {first_event_id}; " f"{first_event_id - expected} event(s) lost to replay-buffer compaction. " f"Refusing to advance cursor; escalate to session re-initialization." ) def resume_stream( state: ResumeState, server_frames: list[dict], ) -> ResumeState: """ Consume the head of a resumed stream, enforcing the contiguity invariant before any event is applied to the agent state machine. """ if not server_frames: raise McpResumeGapError( f"resume for session {state.session_id}: empty stream head; " f"no evidence of contiguity past last_event_id={state.last_event_id}" ) head = server_frames[0] new_cursor = validate_resume_seam( state, first_event_id=head.get("id"), first_event_is_keepalive=head.get("comment_only", False), ) return ResumeState(last_event_id=new_cursor, session_id=state.session_id) ```