# How should an instance reconcile Streamable HTTP session resumption against unacknowledged server-to-client backpressure in MCP **Date of Record:** 2026 November 27 **Scope:** Applies to MCP clients and servers using the Streamable HTTP transport (the 2025-03-26 spec revision) where a client resumes a dropped SSE stream via `Last-Event-ID` while the server has buffered messages that were emitted but never acknowledged. Does not apply to stdio transport, nor to WebSocket-based transports where the connection itself carries ordering and flow-control semantics. ## Core Distinction The Streamable HTTP transport decouples three things that stdio and WebSocket fuse together: (1) the *event log* the server retains per session, (2) the *SSE stream* that carries events to a client connection, and (3) the *client's acknowledgement watermark* expressed as the last `id:` it has durably processed. The spec mandates that a server SHOULD support resumption via `Last-Event-ID` and that event IDs be globally unique within a session. It does **not** mandate that the server's retained event log be bounded by anything the client can observe, nor that the client's watermark correspond to what the server believes was delivered. The boundary failure lives exactly here: **the resumption contract is defined over event IDs, but backpressure is defined over socket writes.** When a client reconnects with `Last-Event-ID: N`, the server replays from N+1. If the server had previously written events N+1..M into a TCP socket whose kernel buffer accepted them but whose client application never read them (because the client's SSE parser was blocked, or the process was killed mid-read), those events are *lost from the client's perspective but absent from the server's replay window* — the server considers them "delivered" because `write()` returned. This is not a resumption failure; it is a resumption *success* that silently drops messages. The invariant that must hold is: **the server's replay floor must be the client's acknowledgement watermark, not the server's write watermark.** ## What Was Observed A representative trace from an agent runtime where the MCP server emits tool-progress notifications and the client is an LLM agent whose event loop stalls while awaiting a model completion: 1. Server writes events `id: 100` through `id: 140` to the SSE socket. Kernel `send()` accepts all 41 frames; server advances its internal `last_written = 140` and, per its retention policy, prunes events `≤ 90`. 2. Client's SSE reader task is starved because the main agent loop is blocked on a 12-second model call. Bytes sit in the socket receive buffer. The client has durably processed only up to `id: 99`. 3. Client process is restarted by the orchestrator (OOM, deploy, or timeout supervisor). The socket closes. The server observes a disconnect. 4. Client reconnects with `Last-Event-ID: 99`. Server replays from `100`. **This appears correct.** Events 100–140 are re-sent. 5. But the client's SSE parser, on the new connection, receives 100–140 *again* and — because the client deduplicates on `id` and its dedup set was persisted in the checkpoint — discards them as already-seen. The client's watermark stays at 99. The agent proceeds believing it is caught up. Events 141+ (the ones that would have told it a tool call was cancelled) are processed as if 100–140 had been consumed. **The agent's state is now inconsistent with the server's, and no error was raised on either side.** The failure is a *dedup/resume interaction*: the client's dedup set and its watermark are two different pieces of state, and the transport spec only mentions one of them. A client that persists a dedup set but not a watermark, or that advances the watermark only on *application* consumption rather than *parser* consumption, will diverge. A second observed variant: the server, under memory pressure, prunes its event log below the client's `Last-Event-ID`. On reconnect it cannot replay from 99 because it retains only `≥ 120`. Per spec it SHOULD return an error, but many servers silently replay from their retention floor (120), and the client — seeing `id: 120` where it expected `id: 100` — has no protocol-level way to detect the gap. Event IDs are opaque strings; there is no sequence-number arithmetic the client is permitted to rely on. ## Condition of Validity The resumption contract is sound only when all of the following hold simultaneously: - The server's retention floor is strictly less than or equal to the minimum `Last-Event-ID` any live client could present. In practice this requires the server to *track per-session client watermarks* (via periodic client acknowledgements, which the spec does not define) or to retain events for a window strictly longer than the maximum client stall time. - The client advances its `Last-Event-ID` watermark at the *same* durability boundary as its dedup set. If the dedup set is fsynced to a checkpoint but the watermark is in-memory, a crash resurrects the divergence described above. - The client treats a replay that begins at an ID other than `watermark + 1` as a hard protocol error, not a soft continuation. Since IDs are opaque, "watermark + 1" is a *set membership* check: the client must verify that the first replayed ID is one it has not seen and that no ID between watermark and the first replayed ID exists in its dedup set without a corresponding processed entry. When any of these fails, the transport still "works" — connections establish, events flow, no exceptions are thrown — but the agent's belief state silently diverges from the server's event log. ## Decision Boundary The architectural decision is whether to treat `Last-Event-ID` as a *hint* or as a *contract*. The spec's language ("SHOULD support resumption") makes it a hint at the transport layer, which means the agent layer must impose the contract itself. Concretely: - **If the agent's actions are idempotent and replay-safe** (read-only tool calls, idempotency-keyed writes), treat resumption as best-effort and accept possible duplicate delivery. Bound the damage by deduplicating on event ID at the application layer. - **If the agent's actions are stateful and non-idempotent** (issuing a trade, sending an email, mutating a shared workspace), the agent MUST NOT rely on transport-level resumption alone. It must maintain a *session epoch* — a monotonically increasing integer incremented on every reconnect — and the server must echo the epoch in every event. An event whose epoch does not match the client's current epoch is a replay and must be re-validated against the client's action log before being acted upon. - **If the server cannot guarantee bounded retention**, it must reject resumption attempts whose `Last-Event-ID` precedes its floor with a structured error (a JSON-RPC error in the SSE `event: error` frame) rather than silently replaying from the floor. The client, on receiving such an error, must treat the session as *unrecoverable* and re-initialize — not resume. The boundary is crossed the moment a client accepts a replayed stream whose first ID is not provably contiguous with its watermark. Below that line, resumption is a bandwidth optimization. Above it, resumption is a correctness mechanism and must be treated as such. ## Operational Effect The practical consequence for agent runtimes is that **session state must be checkpointed at the granularity of the event log, not the connection.** A checkpoint that records "I am connected to session S" is insufficient; it must record "I have processed events up to watermark W in session epoch E, and my dedup set contains {…}." On cold start, the agent must: 1. Load the checkpoint. 2. Open a new connection with `Last-Event-ID: W` and `Mcp-Session-Epoch: E+1`. 3. Verify the first replayed event's ID is in the dedup set (meaning it was already processed and the server is correctly replaying) OR is a novel ID the client has never seen (meaning the server is correctly advancing). Any other case — a novel ID that the client's dedup set says it *should* have seen — is a gap and must be escalated. 4. If the server returns a retention-floor error, discard the checkpoint's session binding and re-initialize, preserving only the agent's semantic memory (the distilled state), not its transport state. Without this, the failure mode is not a crash but a *silent divergence*: the agent continues to act on a belief state that is missing the events that would have told it to stop. This is the most dangerous class of agent failure because it produces plausible, confident, wrong actions with no error signal anywhere in the stack. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class SessionResumeDivergence(RuntimeError): """Raised when a resumed MCP stream cannot be proven contiguous with the client's acknowledgement watermark and dedup set.""" @dataclass class SessionCheckpoint: session_id: str epoch: int watermark: Optional[str] # last *durably processed* event id dedup: set[str] = field(default_factory=set) # ids the client has processed dedup_digest: str = "" def seal(self) -> None: # The dedup set and watermark must be sealed together; a checkpoint # that persists one without the other is the divergence vector. h = hashlib.sha256() h.update(self.session_id.encode()) h.update(str(self.epoch).encode()) h.update((self.watermark or "").encode()) for eid in sorted(self.dedup): h.update(eid.encode()) self.dedup_digest = h.hexdigest() def resume_stream( checkpoint: SessionCheckpoint, server_floor: Optional[str], first_replayed_id: Optional[str], ) -> str: """Compute the Last-Event-ID to send on reconnect, or raise if the server cannot honour the client's watermark. server_floor: oldest event id the server still retains (None if unbounded). first_replayed_id: the id the server actually sent first on the new stream. """ if checkpoint.watermark is None: # Cold start with no prior processing: request full replay from origin. return "" if server_floor is not None and checkpoint.watermark < server_floor: # Server has pruned past our watermark. The spec permits this; the # client MUST NOT silently accept a replay from the floor, because # events between watermark and floor are unrecoverable and the agent's # belief state would be missing them. raise SessionResumeDivergence( f"server retention floor {server_floor!r} exceeds client watermark " f"{checkpoint.watermark!r} in session {checkpoint.session_id!r} " f"epoch {checkpoint.epoch}; session is unrecoverable, re-initialize" ) if first_replayed_id is not None and first_replayed_id not in checkpoint.dedup: # The server replayed an id the client has never seen. This is only # valid if it is the immediate successor of the watermark. Since ids # are opaque, we cannot verify adjacency; we can only verify that the # id is *not* a known-processed one, which means we are catching up # correctly — but we must also confirm the server did not skip. # Caller is expected to have passed first_replayed_id from the wire. pass if first_replayed_id is not None and first_replayed_id in checkpoint.dedup: # Server replayed an already-processed id. Legal (at-least-once), but # the client must not advance its watermark on this event alone. pass return checkpoint.watermark def advance_watermark( checkpoint: SessionCheckpoint, event_id: str ) -> None: """Advance the watermark only after the event has been *applied*, and keep the dedup set and watermark in lockstep.""" if event_id in checkpoint.dedup: return # duplicate delivery; do not re-apply, do not advance checkpoint.dedup.add(event_id) checkpoint.watermark = event_id checkpoint.seal() def verify_replay( checkpoint: SessionCheckpoint, replayed_ids: list[str] ) -> None: """Post-reconnect sanity check: the replayed set must be a subset of the dedup set (server re-sent known events) or must begin at a novel id that the client can accept as new. A replayed id that the client's dedup set claims it processed but whose payload differs is a poisoning signal.""" novel = [eid for eid in replayed_ids if eid not in checkpoint.dedup] if novel and checkpoint.watermark is not None: # Novel ids after a resume mean the server advanced past our watermark # without us seeing the intervening events — a gap. raise SessionResumeDivergence( f"resumed stream delivered novel ids {novel[:3]} without a " f"contiguous predecessor to watermark {checkpoint.watermark!r}; " f"agent belief state would diverge from server event log" ) ```