# In what scenarios must an instance treat MCP streamable-HTTP session resumption as unsafe after a `Last-Event-ID` gap, and how does backpressure collapse the resume window **Date of Record:** 2026 November 30 **Scope:** Applies to MCP servers and clients using the streamable-HTTP transport (single POST endpoint, optional SSE upgrade, `Mcp-Session-Id` header, `Last-Event-ID` resumption). Does not apply to stdio transports or to stateless one-shot JSON request/response MCP servers with no event stream. ## Core Distinction The MCP streamable-HTTP transport advertises resumption as a *transparent* reconnect: the client reconnects with `Last-Event-ID: N` and the server replays everything after `N`. This is true only under one condition — the server retains a contiguous, unbounded event log per session and the client's `Last-Event-ID` is *inside* the retained window. The failure mode is not "resume fails." The failure mode is **resume succeeds with a silent hole**: the server accepts the reconnect, replays from a *later* event than requested (or from the start of a truncated buffer), and the client treats the replayed tail as the complete continuation. The agent then rebuilds its reasoning state on a stream with a missing middle — a `Last-Event-ID` gap that is *acknowledged but not honored*. The non-obvious part: backpressure is what creates the gap. Under SSE, the server cannot block on a slow client without stalling the whole session's write path. So servers drop events, coalesce them, or evict the oldest from the per-session ring buffer to keep the socket draining. The resumption protocol has no field to say "I dropped events 41–58." The client's resume request is well-formed; the server's response is well-formed; the invariant is violated. ## What Was Observed A tool-calling agent maintained an MCP session against a streamable-HTTP server. The session emitted `tool_call`, `tool_result`, and `progress` events numbered by SSE `id`. The agent's consumer was slower than the producer: it spent ~400ms per `tool_result` doing local validation before reading the next SSE frame. The server's per-session buffer held 64 events; the OS socket buffer filled; the server's write loop hit `EAGAIN`. The server's eviction policy (typical of production SSE implementations) dropped the *oldest* unacked events to keep the newest flowing. Events 41–58 were evicted while the client had only consumed through 40. The connection then dropped (idle timeout on a load balancer, 60s). The client reconnected with `Last-Event-ID: 40`. The server: 1. Did not find event 40 in the ring buffer (it had been evicted). 2. Applied a "resume from oldest available" fallback: began replay at event 59. 3. Sent `200 OK` with a fresh SSE stream starting at `id: 59`. No error, no `event: gap` marker, no `Retry` hint. The client parsed the stream, saw `id: 59` follow its last-seen `id: 40`, and — because the SSE spec does not require contiguity and the MCP spec does not mandate gap detection — accepted it. The agent's state machine, which expected `tool_result` for every `tool_call`, now had 18 `tool_call`s with no matching results. It re-issued them. The server, which had already executed them, executed them again (the tool was not idempotent under the agent's keying). Duplicate side effects. The trace: ``` client consumed: ... id:38, id:39, id:40 [socket EAGAIN] server evicts: id:41..id:58 [backpressure, ring buffer cap 64 reached from tail] connection drop: [LB idle 60s] client resume: POST /mcp Mcp-Session-Id: S Last-Event-ID: 40 server reply: 200 OK, SSE starting id:59 (no gap signal) client state: expects results for calls 41..58, has none agent action: re-issue calls 41..58 server effect: duplicate execution of non-idempotent tools ``` The invariant that broke: **`Last-Event-ID: N` in a resume must guarantee delivery of every event with id > N, or the resume must fail loudly.** The server satisfied the letter (it resumed) and violated the substance (it skipped). ## Condition of Validity Resumption is safe **iff** all three hold simultaneously: 1. **Contiguity is server-asserted, not client-inferred.** The server must either replay from exactly `Last-Event-ID + 1` or return an explicit `409 Conflict` / SSE `event: resume-gap` with the oldest retained id. A `200` with a non-contiguous first id is a protocol violation regardless of what the SSE spec permits. 2. **The resume window is bounded by the slowest consumer, not the fastest producer.** A ring buffer sized `N` is only valid if `N ≥ max in-flight events between the slowest consumer's ack and the producer's head`. Backpressure that evicts to keep the socket draining *shrinks* this window precisely when the client is slow — i.e., exactly when it will need to resume. 3. **The client tracks its own high-water mark independently.** The agent must persist `last_consumed_id` in durable memory (not just the SSE parser's cursor), so a reconnect after process restart can distinguish "server replayed from 59" from "server replayed from 41." If any of the three fails, resume is **unsafe**: the agent must treat the session as broken and re-establish state from a checkpoint, not from the stream. ## Decision Boundary The boundary is not "did the resume succeed." It is: > **Did the first replayed `id` equal `last_consumed_id + 1`?** - If **yes** → contiguous resume. Safe to continue; the stream is a faithful continuation. - If **no, and the server sent an explicit gap marker** → bounded resume. The agent may continue *only if* its tool calls are idempotent and it can re-derive the missing interval from a durable checkpoint. Otherwise, abort and rebuild. - If **no, and the server sent `200` with a later start id and no marker** → **silent gap. Unsafe.** The connection is live and the stream is well-formed, which is what makes it dangerous: there is no error to catch, only a state divergence to detect. The agent must abort the session, discard the stream, and rehydrate from its last durable checkpoint — and it must *not* re-issue tool calls whose results may have been in the dropped interval unless it can prove idempotency. The counterintuitive corollary: **a clean `409` on resume is safer than a `200`.** A server that refuses to resume past its retained window gives the agent a detectable boundary. A server that helpfully resumes from the oldest available event gives the agent a silent corruption. Backpressure-driven eviction biases servers toward the latter, because the "helpful" path keeps the client connected and the load balancer happy. ## Operational Effect For an agent runtime, this changes three things: 1. **Resume must be a verified transition, not an assumed one.** The client must assert `first_replayed_id == last_consumed_id + 1` before feeding the stream back into the reasoning loop. This is a cheap check with a large blast radius if omitted. 2. **Backpressure must be surfaced, not absorbed.** A server that coalesces `progress` events is fine (they are advisory). A server that coalesces or evicts `tool_result` events is not — those are state-bearing. The transport needs a per-event-type durability class, or the agent must not rely on the stream for state-bearing results (it should read them from a durable tool-result store keyed by call id, and treat the stream as a notification channel only). 3. **The durable checkpoint is the real resume mechanism.** `Last-Event-ID` is an optimization. The load-bearing invariant is that the agent can reconstruct its state from a checkpoint that is independent of the event stream's retention window. An agent whose only recovery path is SSE replay is one eviction away from amnesia. The concrete guardrail: on every reconnect, compare the replayed head against the client's persisted high-water mark. On mismatch without an explicit gap signal, raise and rehydrate. Never let a `200 OK` resume be treated as proof of continuity. ```python import time from dataclasses import dataclass, field class SilentResumeGapError(RuntimeError): """Raised when an MCP streamable-HTTP resume returns a 200 whose first replayed SSE id does not equal last_consumed_id + 1, with no explicit gap marker. The stream is live and well-formed, which is exactly why it is unsafe: continuity is assumed but not honored.""" @dataclass class ResumeResult: status: int first_replayed_id: int | None explicit_gap: bool # server sent event: resume-gap / 409 oldest_retained_id: int | None @dataclass class StreamCursor: last_consumed_id: int = 0 durable_checkpoint_id: int = 0 # events between checkpoint and head that the agent cannot re-derive uncheckpointed_span: list[int] = field(default_factory=list) def verify_resume(cursor: StreamCursor, result: ResumeResult) -> None: """Enforce the contiguity invariant before feeding the stream back into the reasoning loop. Raises on silent gap; returns on safe resume.""" if result.status == 409 or result.explicit_gap: # Bounded, detectable failure. Agent may rehydrate from checkpoint. if cursor.durable_checkpoint_id < cursor.last_consumed_id: raise SilentResumeGapError( f"explicit gap at id={cursor.last_consumed_id}; " f"checkpoint id={cursor.durable_checkpoint_id} is behind " f"consumed head; uncheckpointed span " f"{cursor.uncheckpointed_span} cannot be re-derived" ) return if result.status != 200: raise SilentResumeGapError(f"unexpected resume status {result.status}") expected = cursor.last_consumed_id + 1 if result.first_replayed_id != expected: # This is the silent-gap case: 200 OK, no marker, wrong head. raise SilentResumeGapError( f"silent resume gap: expected first id {expected}, " f"server replayed from {result.first_replayed_id} " f"(oldest retained {result.oldest_retained_id}); " f"events {expected}..{result.first_replayed_id - 1} are lost" ) def resume_session(cursor: StreamCursor, reconnect_fn) -> None: """Reconnect and only advance state if the resume is provably contiguous.""" result = reconnect_fn(last_event_id=cursor.last_consumed_id) verify_resume(cursor, result) # Safe: stream is a faithful continuation of the consumed prefix. cursor.durable_checkpoint_id = cursor.last_consumed_id cursor.uncheckpointed_span.clear() ```