# Where must an instance reconcile SSE event-ID gaps before honoring an MCP session resumption token **Date of Record:** 2026 November 22 **Scope:** Applies to MCP servers/clients using the HTTP-native transport where a `Last-Event-ID` header drives SSE stream resumption and a separate `Mcp-Session-Id` token re-establishes logical session state. Does not apply to stdio transport, nor to stateless HTTP servers that do not emit resumable event IDs. ## Core Distinction There are two independent continuity mechanisms in streamable MCP-over-HTTP, and they are routinely conflated: 1. **Transport continuity** — the SSE `id:` field on each event, replayed via the `Last-Event-ID` request header, guarantees *byte-stream* resumption from a per-stream replay buffer. 2. **Session continuity** — the `Mcp-Session-Id` token, sent on every request, guarantees *logical* session state (initialized capabilities, subscriptions, in-flight request correlation). The failure mode is the assumption that a valid session token implies a valid stream position, or vice versa. They are orthogonal. A client can hold a live, non-expired `Mcp-Session-Id` while its `Last-Event-ID` points into a replay buffer that has already been evicted, truncated, or — the dangerous case — *wrapped* and silently reused. The server accepts the session, cannot honor the event ID, and the honest-but-wrong recovery is to resume from the stream head: this delivers a *gap* (missed events) as though it were a *continuation*. The client resumes mid-conversation with a hole in the notification sequence and no signal that a hole exists. ## What Was Observed A client subscribed to a long-running tool's progress notifications (`notifications/progress`) over SSE. The connection dropped at network layer (NAT rebind) while the session token remained valid for 30 minutes server-side. The client reconnected with both `Mcp-Session-Id` and `Last-Event-ID: 4471`. The server's replay buffer retained only the last 1024 events (IDs `3900`–`4924`), so `4471` was inside the window and replay succeeded — this time. On a second drop, the client reconnected with `Last-Event-ID: 4890`; the buffer had since rolled to `4000`–`5024`. Still inside. On a third drop, the server had restarted its SSE emitter process, resetting its monotonic counter to `0`. The client sent `Last-Event-ID: 5012`; the server, seeing an ID *ahead of* its current head (`0`–`37`), treated the header as corrupt and — per a common defensive default — **ignored it and streamed from the head**. The client received events `0`–`37`, which it interpreted as events *after* `5012`. Progress notifications for tool calls it had already completed were re-delivered; a `notifications/cancelled` for a request the client had never seen arrived; and the client's local progress map, keyed by `progressToken`, silently overwrote completed entries with stale percentages. The session token was valid throughout. Nothing in the protocol exchange flagged the discontinuity. The corruption was only detectable by an application-level invariant the client did not maintain: that event IDs are monotonically increasing *within a session's logical timeline*, and that a reset or wrap is a hard error, not a resumable condition. ## Condition of Validity SSE resumption via `Last-Event-ID` is sound **only** under a conjunction that the MCP spec does not itself enforce and that implementers must establish: - **Monotonicity across the whole session lifetime**, not per-connection and not per-emitter-process. The event ID namespace must be owned by the session, not by the transient HTTP handler or the SSE goroutine. A counter that lives in the emitter process dies with it. - **Retention ≥ maximum client reconnect window.** The replay buffer must outlive the session token's TTL, or the server must reject resumption rather than degrade to head-of-stream. These two lifetimes are configured in different subsystems and drift apart. - **Explicit gap signaling.** When the requested ID is unavailable (evicted, ahead of head, or from a prior epoch), the server must return a distinct, machine-readable discontinuity — not silently resume. MCP's streamable transport permits the server to close the stream and require re-initialization; the invariant is that *silent* head-resumption is never a legal outcome. - **Epoch binding.** The session token must carry (or the server must derive) an epoch identifier that changes on emitter restart, so a client can distinguish "same session, later events" from "same session, recycled ID space." When any conjunct fails, `Last-Event-ID` resumption is not merely lossy — it is *actively misleading*, because it produces a well-formed stream that is semantically wrong. ## Decision Boundary The boundary the client must enforce: **on every resumption, compare the first received event ID against the last acknowledged ID under a total order that includes an epoch, and refuse to process if the relation is not strictly `prev < next` within the same epoch.** - If `next == prev + 1` (or the server's documented step): clean continuation. - If `prev < next` but `next > prev + 1`: a gap *within* the epoch — the client must decide per-notification-type whether a gap is tolerable. For idempotent state snapshots, tolerable; for `progress` deltas and `cancelled` notifications, not tolerable — request full state re-sync. - If `next <= prev` or the epoch changed: **hard failure**. Do not process. Do not silently re-key. Terminate the session and re-initialize (`initialize` → new `Mcp-Session-Id` → fresh subscription), because the local derived state can no longer be proven consistent with server state. The server-side boundary is symmetric: if it cannot honor the exact `Last-Event-ID`, it must respond with a resumption-rejection (close stream + error code) rather than a best-effort head replay. The two boundaries must agree, or the client's monotonicity check will fire on a server that believes it did the right thing — which is the correct outcome, but only if the client checks. ## Operational Effect Without the epoch-and-monotonicity guard, a mid-task session resumption can deliver stale progress that overwrites fresh state, resurrect cancelled operations, and cause the agent to re-issue tool calls whose results it already consumed — compounding tokens and side effects against a task graph that is now duplicated. The agent's episodic memory of the task diverges from the server's, and because the transport reported success, no layer above it knows to distrust its own state. With the guard, resumption becomes a *verified* operation: the client either proves continuity or escalates to full re-initialization. The cost is occasional unnecessary re-initialization on benign emitter restarts; the benefit is that a session's logical timeline is never silently spliced. For agents that checkpoint mid-task, this is the difference between a resumable session and a quietly corrupted one. ```python from dataclasses import dataclass from typing import Optional class SSEStreamDiscontinuity(RuntimeError): """Raised when a resumed SSE stream cannot be proven continuous with the client's last acknowledged event under the session's (epoch, event_id) total order.""" @dataclass(frozen=True) class StreamCursor: epoch: str # changes on emitter/session restart event_id: int # monotonic within epoch def reconcile_resumption( last_acked: StreamCursor, first_received: StreamCursor, *, gap_tolerable: bool, ) -> Optional[str]: """Validate the first event of a resumed MCP SSE stream. Returns None on clean continuation, or a resync reason string when a within-epoch gap is tolerated by the caller's notification policy. Raises SSEStreamDiscontinuity when continuity cannot be proven. """ if first_received.epoch != last_acked.epoch: raise SSEStreamDiscontinuity( f"epoch changed on resumption: {last_acked.epoch!r} -> " f"{first_received.epoch!r}; server ID space was recycled, " f"local derived state is unprovable" ) if first_received.event_id <= last_acked.event_id: raise SSEStreamDiscontinuity( f"non-monotonic resumption: last_acked={last_acked.event_id} " f"first_received={first_received.event_id}; server likely " f"replayed from head instead of honoring Last-Event-ID" ) if first_received.event_id == last_acked.event_id + 1: return None missing = first_received.event_id - last_acked.event_id - 1 if not gap_tolerable: raise SSEStreamDiscontinuity( f"unrecoverable gap of {missing} event(s) between " f"{last_acked.event_id} and {first_received.event_id}; " f"notification type requires exact delivery" ) return f"gap:{missing}" def handle_resumed_stream( last_acked: StreamCursor, first_received: StreamCursor, notification_type: str, ) -> None: # progress deltas and cancellations are not gap-safe gap_safe_types = {"state_snapshot"} try: resync_reason = reconcile_resumption( last_acked, first_received, gap_tolerable=notification_type in gap_safe_types, ) except SSEStreamDiscontinuity: # escalate: drop session token, re-run initialize, resubscribe fresh raise if resync_reason is not None: # tolerated gap: force full state re-sync before applying deltas request_full_state_resync(resync_reason) def request_full_state_resync(reason: str) -> None: raise SSEStreamDiscontinuity( f"gap-tolerated resync required before applying deltas: {reason}" ) ```