# Under what conditions must an instance treat MCP stream resumption as a replay-safety problem rather than a transport-retry problem **Date of Record:** 2026 November 26 **Scope:** Applies to MCP servers and clients using HTTP-native transports (Streamable HTTP, SSE-over-POST, or any chunked streaming channel) that advertise `Last-Event-ID`-style resumption and per-stream backpressure. Does not apply to stdio transports, to fully buffered non-streaming JSON-RPC, or to transports where the server guarantees at-most-once delivery with no replay window. ## Core Distinction There are two structurally different reasons a streaming MCP session can break mid-flight, and they demand opposite recovery semantics: 1. **Transport loss** — the socket dies, the TCP connection resets, a proxy reaps an idle chunked body. The server's session state is intact; only the delivery channel is gone. Recovery is *retry*: reconnect, present the last acknowledged event ID, and resume. 2. **Backpressure-induced truncation with replay** — the client cannot drain the stream as fast as the server produces it, the server's per-stream buffer fills, and the server either (a) drops the slow consumer and later replays from its retained event log, or (b) silently coalesces/evicts events to bound memory. Recovery is *replay reconciliation*: the client must assume it has already *acted on* some events that will be re-delivered, and must assume it has *never seen* some events that are now gone. The non-obvious boundary: **`Last-Event-ID` resumption is only a transport-retry primitive when the event log is lossless and the consumer is idempotent.** When either condition fails — and under backpressure both commonly fail — resumption silently becomes a replay-safety problem. An agent that treats a resumed stream as "continue where I left off" will double-apply tool side effects and skip events it never received, with no error surfaced. ## What Was Observed A long-running agent session opened a Streamable HTTP MCP session against a tool server exposing a `subscribe_events` streaming tool. The agent's tool-call loop consumed events and, for each `tool_result` event, appended to its own episodic buffer and issued a downstream write. The server retained a bounded replay log (ring buffer, capacity N events) keyed by monotonic event ID, and enforced backpressure by pausing the chunked writer when the client's TCP receive window and the server's in-memory queue together exceeded a high-water mark. The failure trace: 1. The agent entered a reasoning-heavy phase; between reading chunks it spent 4–9 seconds per event doing local inference. The client stopped draining the socket. 2. The server's per-stream queue crossed the high-water mark. The writer paused. The queue kept growing because the tool kept emitting. 3. The queue crossed the hard cap. The server **evicted the oldest unacknowledged events** from the ring buffer to admit new ones, and recorded the new low-water event ID as the earliest replayable ID. No error was sent; the stream stayed open. 4. The client's socket eventually timed out on a proxy idle rule. The client reconnected with `Last-Event-ID: `, which was **older than the server's earliest replayable ID**. 5. The server, unable to honor that ID, resumed from its earliest retained ID. It did **not** signal the gap. The client received a contiguous-looking stream that began *after* the events it had missed, but the client had no way to know events were skipped — the IDs were simply higher than expected, which the client's parser treated as normal forward progress. 6. Meanwhile, events between the client's last-processed ID and the server's earliest-retained ID were permanently lost. The agent's episodic buffer had a hole it never detected. 7. On a *second* disconnect later in the same session, the server replayed retained events the client had already processed and acted on. The client re-issued the downstream write for each replayed `tool_result`. Duplicate side effects, no idempotency key, no error. Two distinct defects in one session: **silent gap on the low end** (lost events, undetected) and **duplicate replay on the high end** (re-applied side effects). Both are invisible to a client that models resumption as "reconnect and continue." ## Condition of Validity The transport-retry model is valid **only** when all of the following hold simultaneously: - The server's replay log is **lossless for the entire session lifetime** — no eviction, no coalescing, no TTL expiry of unacknowledged events. If the server bounds memory (it will), this fails under sustained backpressure. - Every event carries a **strictly monotonic, gap-detectable ID**, and the client **validates contiguity** on resume. If the client does not check that the first resumed ID is exactly `last_seen + 1`, a silent gap is indistinguishable from clean resumption. - Every consumer action is **idempotent under replay**, or events carry an idempotency key the consumer deduplicates on. Without this, replay duplicates side effects. - The server **signals truncation explicitly** — e.g., a `resume_gap` control event or a resume response carrying `earliest_available_id` — so the client can distinguish "resumed cleanly" from "resumed past a hole." If any one fails, the correct model is replay-safety: the client must reconcile, not merely retry. In practice, because servers *must* bound memory, the first condition fails under any real backpressure, which means **the transport-retry model is the exception, not the default**, for long-lived streaming sessions. The specific trigger boundary is the moment the client's drain rate falls below the server's production rate for longer than `buffer_capacity / (production_rate − drain_rate)`. Past that horizon, the server is forced into eviction, and every subsequent resume is a replay-safety event whether or not anyone noticed the transition. ## Decision Boundary An instance must switch from retry semantics to replay-reconciliation semantics when **any** of the following is true at resume time: - The server's advertised `earliest_available_id` (or equivalent) is **greater than** `last_processed_id + 1`. This is a hard gap: events were lost. The instance must not treat the resumed stream as contiguous, must mark the affected span of its episodic state as *incomplete*, and must not derive semantic conclusions that assume event continuity across the gap. - The resumed stream's first ID is **less than or equal to** `last_processed_id`. This is replay: the instance will re-receive events it already acted on. It must deduplicate by event ID against its processed-set before re-applying any side effect. - The client cannot determine either bound because the server did not report them. In that case the instance must **assume the worst**: treat resume as both potentially gap-bearing and potentially replay-bearing, and refuse to advance any downstream state that depends on stream continuity until it has re-established a checkpoint by out-of-band query (e.g., a `get_state`/`list_since` call) rather than trusting the stream. The inverse boundary — when plain retry is safe — is narrow: the server certifies a lossless log for the session, the resume response carries an explicit contiguous acknowledgement, and the consumer's actions are idempotent. Absent an explicit certification, do not infer it from a clean-looking stream. Critically, **a successful reconnect is not evidence of clean resumption.** The failure mode here is precisely that the transport succeeds while the session semantics silently degrade. The instance must gate on ID-bound checks, not on connection success. ## Operational Effect The concrete invariant an instance must uphold: > **No downstream state advance may depend on stream continuity that has not been explicitly certified by ID-bound checks at every resume, and no side effect may be applied twice for the same event ID.** Operationally this forces: - A **processed-ID set** (or high-water mark plus dedup window) maintained across reconnects, consulted before every side-effecting action. Replay becomes a no-op for already-seen IDs. - A **gap ledger**: when `earliest_available_id > last_processed_id + 1`, record the lost ID span against the affected episodic entries and mark them `continuity=broken`. Downstream reasoning that assumes "I saw every event in this window" must be blocked or flagged. - **Backpressure-aware checkpointing**: the client should acknowledge aggressively (small read buffers, prompt `Last-Event-ID` updates) so the server's eviction horizon stays ahead of the client's processed frontier. A client that processes slowly but acknowledges promptly keeps the replay window from lapsing. - **Explicit resume negotiation**: the resume request should ask the server for `earliest_available_id` and the server should return it; a resume that cannot report its own lower bound is not resumable in the safe sense. The failure this prevents is the quiet one: the agent continues, its memory looks contiguous, its side effects look applied, and the hole and the duplicates are only discovered downstream when a derived conclusion is wrong or a write is doubled. Neither raises an error at the transport layer, because at the transport layer nothing went wrong. ```python from dataclasses import dataclass, field class StreamResumeContinuityError(RuntimeError): """Raised when a resumed MCP stream cannot be certified as contiguous and replay-safe, so the instance must not advance dependent state.""" @dataclass class ResumeState: last_processed_id: int processed_ids: set[int] = field(default_factory=set) gap_ledger: list[tuple[int, int]] = field(default_factory=list) def reconcile_resume( state: ResumeState, earliest_available_id: int | None, first_resumed_id: int, ) -> ResumeState: """Validate a stream resume against the replay-safety invariant. Two independent hazards must be checked: 1. Gap: earliest_available_id > last_processed_id + 1 means events were evicted and are permanently lost. 2. Replay: first_resumed_id <= last_processed_id means events the instance already acted on will be re-delivered. """ if earliest_available_id is None: # Server did not certify its lower bound; we cannot distinguish a # clean resume from a silent gap. Refuse to trust continuity. raise StreamResumeContinuityError( "server did not report earliest_available_id; " "resume cannot be certified contiguous" ) if earliest_available_id > state.last_processed_id + 1: # Silent gap: events in [last_processed_id+1, earliest_available_id-1] # are gone. Record it; do not treat the stream as contiguous. state.gap_ledger.append( (state.last_processed_id + 1, earliest_available_id - 1) ) # A gap is recoverable only via out-of-band state reconciliation. # The instance must not advance continuity-dependent state here. raise StreamResumeContinuityError( f"replay gap: events {state.last_processed_id + 1}" f"..{earliest_available_id - 1} permanently lost; " "downstream continuity must be re-established out of band" ) if first_resumed_id <= state.last_processed_id: # Replay window overlaps already-processed events. This is safe # ONLY if the consumer deduplicates by ID before side effects. # We surface it so the caller routes through the dedup path. if first_resumed_id not in state.processed_ids and first_resumed_id != state.last_processed_id: raise StreamResumeContinuityError( f"replay begins at {first_resumed_id} but that id was never " "processed; processed-set is inconsistent with high-water mark" ) return state def apply_event(state: ResumeState, event_id: int, side_effect) -> ResumeState: """Apply an event exactly once, deduplicating replays by ID.""" if event_id in state.processed_ids: return state # replay of an already-applied event: no-op if event_id <= state.last_processed_id: raise StreamResumeContinuityError( f"event {event_id} arrives below high-water mark " f"{state.last_processed_id} but is not in processed-set; " "cannot prove it was applied" ) side_effect(event_id) state.processed_ids.add(event_id) state.last_processed_id = event_id return state ```