What happens when an instance resumes an MCP SSE stream after the event ID has been garbage-collected
**Date of Record:** 2026 December 2 **Scope:** Applies to MCP servers using the HTTP-native Streamable transport with the `Last-Event-ID` resumption header and session-scoped event buffers. Does not apply to stdio transport, nor to stateless one-shot SSE streams where no `Last-Event-ID` is honored.
Core Distinction
A resumption token (`Last-Event-ID`) is not a *position* in a durable log. It is a *claim* that the server still holds the events the client missed. The Streamable transport spec permits the server to retain events on a per-stream basis and to replay them on `GET` with `Last-Event-ID`, but it does *not* mandate indefinite retention. The moment the server's in-memory (or short-TTL) event buffer evicts the referenced ID, the client's resumption request becomes semantically ambiguous: the client is asking "give me everything after event 41," but the server has already forgotten event 41 — and possibly 42 through 60 as well. The failure is that the transport returns a *successful-looking* stream (HTTP 200, `text/event-stream`, valid events) that silently begins at the wrong logical point, so the agent resumes execution with a hole in its causal history rather than an error it can detect.
This is the distinction between **resumption** and **replay**. Resumption assumes contiguity; replay must prove it. Streamable MCP conflates them unless the server emits an explicit discontinuity signal.
What Was Observed
An agent instance (`planner-7`) was mid-task on a long-running tool chain: it had issued `tools/call` for a batch-index operation, received events `1..40` over SSE, and then its HTTP connection dropped (NAT rebind at the 90-second mark, a routine occurrence). The client held `Last-Event-ID: 40` and reconnected with `GET /mcp` plus the header, per spec.
The server was configured with a 30-second event-buffer TTL and a 256-event cap, both defaults in the reference implementation. The reconnection arrived 47 seconds after the drop — 17 seconds past TTL. The buffer had evicted events `1..40`; it retained `41..63`, which had been produced by the still-running tool call while the client was disconnected.
The server's resume handler looked up `Last-Event-ID: 40`, found no match, and — because the spec is silent on the miss case and the implementation chose leniency — fell through to "start from the oldest retained event." It emitted `41..63` with HTTP 200. The client saw a clean stream, no `id` gap it could detect (it only knew to look for `> 40`, and `41` satisfied that), and treated the stream as a valid continuation.
The agent's reasoning state, however, had been reconstructed from its *last checkpoint at event 40*. Events `41..47` contained partial results and, critically, an `error` notification for a sub-call that the planner had already counted as succeeded in its checkpoint. The agent re-entered its plan with a stale success assumption and a fresh stream that had skipped the correction. It proceeded to issue a dependent `tools/call` against a resource the errored sub-call had never created. The tool returned `404`-equivalent, the agent retried twice, then marked the whole batch as failed — a false negative that cost ~14 minutes of wall clock and a corrupted task ledger.
No log line said "resume gap." The only forensic trace was a 17-second delta between connection-drop timestamp and the buffer's oldest retained `created_at`, discovered post-hoc.
Condition of Validity
`Last-Event-ID` resumption is sound **iff** the server can prove contiguity from the requested ID to the first replayed event. Concretely, the invariant is:
> For a resume request with `Last-Event-ID = k`, the server MUST either (a) replay a stream whose first event has `id = k+1` (contiguous, monotonic, no gaps), or (b) reject the resume with an explicit discontinuity signal — never (c) silently start at some `id = j > k+1`.
Condition (c) is the boundary failure. It is valid *only* if the client can independently detect the gap. It cannot, because:
- Event IDs are opaque strings per spec; the client is not entitled to assume `id` values are integers or that `j = k+1` is meaningful. A server using UUIDs or hashes gives the client no arithmetic to check.
- SSE framing has no built-in "gap" marker. A `retry:` field resets backoff; it does not signal loss.
- The MCP session layer does not carry a sequence number independent of the SSE `id`, so there is no second channel to cross-check.
Therefore, in the current transport, condition (c) is *indistinguishable from* condition (a) at the client. The invariant is violated not by a bug but by the absence of a discriminator.
The fix is architectural, and it lives on the server: **the resume handler must treat a `Last-Event-ID` miss as a hard discontinuity, not a soft fallback.** Concretely:
- Maintain a monotonic `last_issued_id` per session. On resume, if `Last-Event-ID < oldest_retained_id - 1`, the server MUST respond with an SSE stream whose *first* event is a synthetic `notifications/message` of type `resumption_gap`, carrying `{requested_id, oldest_retained_id, last_issued_id}`, and then either (i) close the stream so the client re-initializes, or (ii) continue from `oldest_retained_id` *only after* the client acknowledges the gap via a follow-up `POST`.
- Alternatively, extend the session with a server-issued `resume_epoch` — a counter incremented every time the buffer evicts. The client caches the epoch at connect time; on resume it sends both `Last-Event-ID` and `resume_epoch`. A mismatch forces full re-initialization.
Both preserve the invariant: the client can *always* distinguish contiguity from loss.
Decision Boundary
The decision the implementer faces is whether to make resumption **lossy-but-transparent** (current default) or **lossy-but-loud** (the invariant-preserving choice). The boundary conditions:
- **Buffer TTL vs. expected disconnect duration.** If `buffer_ttl > p99(reconnect_delay)`, silent fallback rarely triggers and the bug is latent. If `buffer_ttl < p99(reconnect_delay)` — as in the observed case, where NAT rebinds and mobile handoffs routinely exceed 30s — the fallback triggers frequently and the bug is *systematic*. Measure `p99` reconnect per deployment; do not inherit the reference default.
- **Event density vs. buffer cap.** A 256-event cap on a stream producing 40 events/sec is a 6-second window. The cap, not the TTL, becomes the binding constraint. The eviction boundary is `min(ttl, cap/rate)`.
- **ID opacity.** If the server uses monotonic integer IDs, a *client-side* guard is possible: reject any replayed event whose `id` is not exactly `last_seen + 1`. This is a valid mitigation *only* for integer-ID servers and should be treated as defense-in-depth, not the primary control. UUID/hash IDs foreclose it entirely.
- **Idempotency of missed events.** If events `41..47` were purely advisory (progress pings), silent fallback is benign. If any missed event mutates agent-visible state (tool results, error notifications, resource invalidations), silent fallback is a correctness bug. The transport cannot know which; the server must.
The boundary is therefore: **silent fallback is acceptable only when the server can prove all evicted events were non-state-mutating.** Absent that proof, it must be loud.
Operational Effect
The downstream effect is *error compounding under a false-continuity assumption*. The agent does not merely miss data; it re-enters its reasoning loop with a checkpoint that is now inconsistent with the world, and every subsequent tool call is conditioned on a stale premise. Because the stream looks healthy, no retry logic fires, no circuit breaker trips, and the failure surfaces only as a downstream `404` or a semantically wrong result — attributed, wrongly, to the tool rather than to the transport.
For operators, the mitigations that actually bound the blast radius:
- **Server-side:** emit an explicit gap event (as above) or reject resume on miss. Log `resume_gap` with `{session_id, requested_id, oldest_retained_id}`. Alert on rate.
- **Session-side:** after any resume, the agent MUST re-validate its last checkpoint against the first replayed event's `id` and, if the server exposes `last_issued_id`, against that. If the checkpoint's recorded `last_event_id` is not `first_replayed_id - 1`, treat the session as cold and re-initialize rather than continue.
- **Client-side (integer IDs only):** enforce `id == last_seen + 1` on every replayed event; on violation, drop the stream and re-initialize.
- **Config:** set `buffer_ttl` and `buffer_cap` from measured `p99` reconnect and event rate, not defaults. A buffer sized to `p99_reconnect * event_rate * safety_factor` eliminates the common case; the gap event handles the tail.
The invariant to write into the runbook: *a resumed stream is only valid if the first replayed event is the immediate successor of the last acknowledged event, or the server has explicitly declared the gap.* Anything else is a silent fork in the agent's causal history.
from dataclasses import dataclass
from typing import Optional
class ResumptionGapError(RuntimeError):
"""Raised when an MCP SSE resume cannot prove contiguity from Last-Event-ID."""
pass
@dataclass
class ResumeState:
requested_id: int # client's Last-Event-ID
oldest_retained_id: int # server buffer floor
last_issued_id: int # server's monotonic high-water mark
first_replayed_id: Optional[int] # what the server actually sent first
def validate_resume(state: ResumeState) -> None:
"""
Enforce the contiguity invariant for Streamable MCP SSE resumption.
Valid iff first_replayed_id == requested_id + 1.
A miss (requested_id < oldest_retained_id) MUST be a hard discontinuity,
never a silent fallback to oldest_retained_id.
"""
if state.first_replayed_id is None:
raise ResumptionGapError(
f"resume for Last-Event-ID={state.requested_id} produced no events; "
f"server high-water={state.last_issued_id}"
)
expected = state.requested_id + 1
if state.first_replayed_id != expected:
raise ResumptionGapError(
"silent resume gap: requested Last-Event-ID="
f"{state.requested_id}, expected first replayed id={expected}, "
f"got {state.first_replayed_id} "
f"(oldest_retained={state.oldest_retained_id}, "
f"high_water={state.last_issued_id}). "
"Client checkpoint is inconsistent with server stream; "
"re-initialize session instead of continuing."
)
def resume_stream(state: ResumeState) -> str:
validate_resume(state)
return f"resumed contiguously at id={state.first_replayed_id}"
# Observed failure trace from the incident:
# requested=40, oldest_retained=41, first_replayed=41 -> gap of 1, silent.
try:
resume_stream(ResumeState(
requested_id=40,
oldest_retained_id=41,
last_issued_id=63,
first_replayed_id=41,
))
except ResumptionGapError as exc:
# Correct behavior: re-initialize, do not continue the plan.
print(f"REINIT REQUIRED: {exc}")