# What happens when an instance resumes an MCP SSE stream with a stale `Last-Event-ID` after the server has already garbage-collected the event ring buffer **Date of Record:** 2026 November 29 **Scope:** Applies to MCP servers exposing the HTTP-native streamable transport (POST for JSON-RPC requests, GET for the SSE event stream) with `Last-Event-ID`-based resumability and `Mcp-Session-Id` session resumption. Does not apply to stdio transports, nor to SSE streams where the server replays from durable storage keyed by monotonic event ID with no eviction. ## Core Distinction The distinction that matters is between *session validity* and *event-log continuity*. The `Mcp-Session-Id` header answers "does this logical session still exist?" The `Last-Event-ID` header answers "can I resume the byte stream at exactly event N+1?" These are two independent axes, and the MCP spec treats them as separable — a server may return `200 OK` with a live session while silently failing to honor the resume point. The failure mode is not a rejected request; it is a *successful* response that reconnects the client to a stream whose event cursor has already been evicted, causing the client to believe it has resumed when it has actually forked into a divergent history. The client's replay cursor and the server's ring-buffer head have silently desynchronized, and no status code tells you so. ## What Was Observed An agent worker maintains a long-lived GET SSE stream to an MCP server (`text/event-stream`). On each disconnect (network blip, load-balancer idle timeout at 60s, or server pod restart), the client reconnects with `Last-Event-ID: ` and the same `Mcp-Session-Id`. The server keeps a per-session in-memory ring buffer of the last N=256 emitted events to serve replays. Under normal load this works. The boundary condition: the agent issues a burst of tool calls (e.g., 40 `tools/call` requests in a fan-out), each of which produces multiple SSE events (progress notifications, log messages, the final result). The event count per session exceeds 256 in under 30 seconds. A transient disconnect occurs at event 512. The client reconnects with `Last-Event-ID: 512`. The ring buffer's oldest retained event is now 300 (events 44–299 were evicted). The server, per its implementation, cannot find event 512's successor. Two behaviors are observed across implementations: 1. **Silent reset:** Server opens a fresh stream from the current head (event ~530), emits no error, and the client's SSE parser resumes reading from event 530. Events 513–529 — including at least one `tools/call` result the agent was awaiting — are never delivered. The agent's pending-call table never resolves those futures; the tool call is orphaned. The agent waits on a promise that will never settle until a separate timeout fires, and the reasoning loop stalls or re-issues the call, duplicating side effects. 2. **Cursor-mismatch replay:** Server finds the nearest retained event *before* the requested ID (event 300), replays from 300 forward, and the client — which had already processed 300–512 — receives duplicate events. Duplicate `tools/call` *results* are idempotent to dedupe, but duplicate *progress notifications* with monotonic tokens cause the agent's progress tracker to regress, and duplicate `notifications/message` log entries inflate the agent's scratch context, contributing to context-window saturation on the next turn. Neither behavior is a protocol violation. The spec says the server *should* support resumption, but does not mandate a specific response when the requested event ID is no longer available, nor does it require the server to signal the gap. ## Condition of Validity The invariant that must hold for resumability to be safe is: > For every `Last-Event-ID: K` the client presents, the server either (a) retains event K and all subsequent events, or (b) explicitly signals that resumption is impossible so the client can perform full-state reconciliation. The failure arises precisely when the server satisfies (a) for the session but not for the event, and does not perform (b). The condition of validity for the *client's* assumption — "if I get a 200 and a stream, my cursor is honored" — is that the server's retention window is strictly larger than the maximum event burst the client can generate between reconnects. That bound is unobservable to the client: it depends on server memory pressure, eviction policy, and the fan-out of in-flight tool calls. The client cannot compute it, and the server does not publish it. A second validity condition: resumption is only safe if event IDs are *monotonic and gap-free within a session*. If the server assigns IDs per-connection rather than per-session, or resets the counter on pod restart (session survives via shared store, but the event counter does not), a reconnecting client's `Last-Event-ID` may be *greater* than the new head, causing the server to either block waiting for a future ID that will never arrive or replay from zero. This is the pod-restart variant of the same class. ## Decision Boundary The boundary is drawn at the point where the client must decide: *trust the resumed stream, or treat the session as logically broken and re-synchronize state from scratch?* The decision hinges on information the transport does not carry by default. The operational rule: - If the reconnecting client can observe that the first event ID received after reconnect is **not** exactly `Last-Event-ID + 1`, it must treat the stream as **forked**, not resumed. It must not process the new stream as a continuation. Instead it must (i) cancel all pending tool-call futures whose IDs fall in the gap, (ii) re-issue those calls with an idempotency key, and (iii) discard any partial progress state accumulated before the gap. - If the client cannot observe this (because the server replays from the nearest retained event, producing a first ID *less than* `Last-Event-ID + 1`), it must detect the *regression* — first received ID ≤ last processed ID — and treat it as a duplicate-replay condition, deduping by event ID before applying. - The server-side invariant to enforce: on any `Last-Event-ID` that is not retained, respond with a distinct signal — either `404` on the GET, or a synthetic SSE event (e.g., `event: resync-required`, `data: {"reason":"cursor-evicted","head":}`) as the first frame — so the client's decision is data-driven, not inferred. The hard boundary: an agent that treats "200 + stream" as proof of continuity will, under burst load or pod churn, silently drop tool results and either hang or duplicate side effects. There is no transport-level guarantee that prevents this; it must be enforced at the client's cursor-validation layer. ## Operational Effect In practice, the effect is a class of *silent* agent failures that look like reasoning bugs. The agent appears to "forget" a tool result, or "re-run" a tool it already ran. Root cause is the forked stream. Downstream effects compound: a duplicated `tools/call` with side effects (file write, payment, external API mutation) violates exactly-once semantics; a dropped result leaves a pending future that blocks the reasoning loop until a coarse timeout, wasting token budget and wall-clock; a regressed progress tracker can cause the agent to re-plan from an earlier checkpoint, discarding valid work. Mitigations that hold: 1. **Cursor-gap detection on every reconnect.** Compare first-received event ID to `last_processed + 1`. Any gap → resync. 2. **Idempotency keys on all `tools/call` requests**, keyed by a client-generated UUID stable across retries, so server-side dedupe can absorb re-issued calls after a detected gap. 3. **Bounded event burst per session.** Client-side throttle on fan-out so in-flight events between reconnects stay below a conservative fraction of the server's advertised (or assumed) retention window. 4. **Session-level epoch.** Server includes a monotonically increasing `epoch` in the `Mcp-Session-Id` or a session metadata field; client invalidates its cursor when epoch changes (pod restart). This closes the pod-restart variant. ```python import uuid from dataclasses import dataclass, field from typing import Optional class StreamResumeGapError(RuntimeError): """Raised when an SSE resume produces an event-ID discontinuity that the client cannot safely bridge without full state reconciliation.""" @dataclass class SSEResumeCursor: session_id: str last_processed_event_id: int session_epoch: int pending_calls: dict = field(default_factory=dict) # call_id -> idempotency_key def resume_stream(cursor: SSEResumeCursor, reconnect_epoch: int, first_event_id: Optional[int]) -> None: """Validate that a reconnected SSE stream is a true continuation of `cursor`. Invariant: the first event received after reconnect MUST be exactly last_processed_event_id + 1, and the session epoch MUST be unchanged. Anything else means the server's event ring buffer evicted our cursor (or the session restarted) and the stream has forked. """ if reconnect_epoch != cursor.session_epoch: raise StreamResumeGapError( f"session epoch changed {cursor.session_epoch}->{reconnect_epoch}; " f"event counter reset, cursor invalid, full resync required" ) if first_event_id is None: raise StreamResumeGapError( "server opened stream but sent no event; cannot confirm continuity" ) expected = cursor.last_processed_event_id + 1 if first_event_id > expected: gap = first_event_id - expected orphaned = list(cursor.pending_calls.keys()) raise StreamResumeGapError( f"cursor evicted: expected event {expected}, got {first_event_id} " f"(gap={gap}); {len(orphaned)} pending tool calls orphaned: {orphaned}. " f"Re-issue with idempotency keys and discard partial progress." ) if first_event_id <= cursor.last_processed_event_id: # Duplicate replay from nearest retained event: dedupe, do not apply. raise StreamResumeGapError( f"regressed replay: got event {first_event_id} <= last processed " f"{cursor.last_processed_event_id}; dedupe by event ID before applying" ) def issue_tool_call(cursor: SSEResumeCursor, tool: str, args: dict) -> str: """Issue a tools/call with a stable idempotency key so post-gap re-issues are deduped server-side rather than double-executed.""" call_id = str(uuid.uuid4()) idem_key = f"{cursor.session_id}:{call_id}" cursor.pending_calls[call_id] = idem_key # ... POST JSON-RPC tools/call with idem_key in params._meta ... return call_id ```