# Why does an instance resume a streamed MCP session into a half-open EventSource and silently lose tool-call results **Date of Record:** 2026 December 1 **Scope:** Applies to MCP clients using the HTTP-native transport with `text/event-stream` responses and the resumption protocol (`Last-Event-ID` / `event_id` replay) when the server interleaves JSON-RPC responses with server-originated notifications. Does not cover stdio transport, WebSocket transports, or servers that emit each JSON-RPC response as a discrete non-streamed HTTP response. ## Core Distinction The failure is not "the connection dropped." Dropped connections are the designed-for case: the client reconnects, sends `Last-Event-ID`, and the server replays from its event log. The failure is the mismatch between **what the client believes it has acknowledged** and **what the server believes it has delivered** when backpressure causes the client to stop reading the SSE stream while the server continues to buffer and advance its event cursor. The invariant that breaks is: *the client's last-processed event ID must never lag the server's last-emitted event ID by more than the server's replay window, and the client must never present a `Last-Event-ID` that is ahead of events it actually parsed into the JSON-RPC layer.* Two cursors exist — one per side — and they drift independently. On resume, the client hands the server its cursor and trusts the replay. If the client's cursor advanced (because bytes arrived and were buffered in a transport layer) but the JSON-RPC dispatch layer never consumed those events (because the consumer was blocked), the resumed stream begins *after* results the agent never saw. The tool call is lost, not retried, because from the protocol's view it was delivered. ## What Was Observed An agent runtime issued a `tools/call` for a long-running operation (a code-execution sandbox call, ~40 s). The MCP server, per spec, emitted a streamed response: an initial `event: message` with the request acknowledgment, then periodic `event: message` keepalives plus unrelated `notifications/message` log events, then finally the `tools/call` result. Each SSE frame carried an `id:` field. The client's SSE reader was a background task feeding a bounded `asyncio.Queue(maxsize=64)` consumed by the JSON-RPC dispatcher. During a period where the dispatcher was blocked on a *different, synchronous* tool result being post-processed (a 12 s tokenization/embedding step inside the agent loop), the queue filled. The SSE reader task blocked on `queue.put()`. The TCP receive buffer filled. The server's per-connection write buffer filled. The server, correctly implementing backpressure, paused writing — but its event emitter had already assigned and logged IDs up to N+180 (keepalives and log notifications) before the write paused, and crucially the server's replay log retained only the last 100 events (a common bounded ring buffer). The client's OS-level socket then hit an idle timeout at a load balancer and was reset. The client reconnected with `Last-Event-ID: N+62` — the last ID its *SSE parser* had extracted and written to its cursor, which was 62 frames ahead of what the *dispatcher* had consumed (the queue held 64 unconsumed frames, of which the parser had already recorded IDs). The server replayed from N+63. But the `tools/call` result was at ID N+210, still in the future — fine. The problem surfaced on the *second* disconnect: by then the dispatcher had drained only to N+70, the parser cursor was at N+240, and the server's ring buffer had evicted everything before N+140. The reconnect sent `Last-Event-ID: N+240`; the server had no events after that (the result was at N+210, now *before* the client's claimed cursor). The server replayed nothing. The client waited. The `tools/call` timed out at the agent layer, the agent retried the tool call, and the sandbox executed the operation **twice** — once for the lost result, once for the retry — with a non-idempotent side effect (a file append). The agent's episodic memory recorded one execution; the sandbox had two. The signature in logs: `Last-Event-ID` monotonically increasing across reconnects while the dispatcher's consumed-sequence counter advanced in bursts and never caught up; a gap where `dispatcher_consumed_seq < last_event_id` at every reconnect; and finally a reconnect where `last_event_id > server_max_emitted_id_for_this_request`, which the server treated as "nothing to replay" rather than as an error. ## Condition of Validity This boundary is reachable whenever all of the following hold: 1. The transport is HTTP-native SSE with resumption enabled (`event_id` present on frames). 2. There is any **decoupling** between the layer that reads bytes and assigns the cursor and the layer that dispatches JSON-RPC — a queue, a buffer, a separate task/thread. If the cursor is advanced only *after* dispatch, the invariant holds by construction. 3. The server uses a **bounded** replay log (ring buffer, TTL, or per-request cap). Unbounded logs convert this from data loss into latency; bounded logs make it loss. 4. The consumer can stall long enough for the parser cursor to outrun the dispatcher cursor by more than the replay window. It does **not** apply when the cursor is coupled to dispatch (advance-on-consume), when the server guarantees replay of the full session lifetime, or when every tool call carries an idempotency key the server deduplicates on. The most dangerous sub-case is a cursor that is *ahead* of the server's emitted set: the client asks to resume from a future it invented by buffering, and the server cannot distinguish "already delivered" from "never existed." ## Decision Boundary The architectural invariant to enforce: **the resumption cursor must be a function of dispatch, not of receipt.** Concretely, `Last-Event-ID` sent on reconnect must equal the highest event ID whose JSON-RPC payload has been fully handed to and accepted by the dispatcher — never the highest ID the SSE parser has tokenized. Every frame between parser-cursor and dispatch-cursor is *unacknowledged* and must be replayed. Three guardrails bound the failure: - **Advance-on-consume cursor.** The SSE reader parses a frame, but the cursor only advances after the dispatcher returns success for that frame's payload. On reconnect, send the consumed cursor. This can cause duplicate delivery of frames that were parsed but not yet consumed — which is safe *only if* the dispatcher is idempotent by `event_id`, so it must dedupe on the ID field. - **Replay-window assertion.** Before sending `Last-Event-ID`, the client checks `consumed_cursor >= server_min_retained_id` (learned from a server capability/hello frame or a `resumptionWindow` field). If the consumed cursor has fallen below the retention floor, the client must **fail the request** rather than resume — the events are gone and silence is worse than an error. - **Future-cursor rejection.** The server must reject a `Last-Event-ID` greater than its max emitted ID for that session as a protocol error, not treat it as "caught up." A client claiming to have consumed events that were never emitted is a corrupted state, and the server silently accepting it converts a detectable bug into silent data loss. The decision boundary for the agent runtime: on a resume where `consumed_cursor < retention_floor` OR `sent_cursor > server_max_emitted`, do **not** retry the tool call blindly. The side-effect status is unknown; the agent must route to a reconciliation path (query the sandbox for the artifact, check idempotency key) before re-issuing. ## Operational Effect Left unguarded, the effect is **silent at-least-once-to-at-most-once flip**: the protocol believes it delivered exactly once, the agent believes it never received, and the tool executes twice with the agent's memory recording once. This is the worst class of agent failure — non-idempotent side effects with a memory that disagrees with reality. The agent's episodic log becomes a lie it will later reason from. With the guardrails, the failure becomes loud and bounded: a `ResumptionGapError` at the client, a `FutureCursorError` at the server, and a reconciliation branch in the agent. The cost is duplicate delivery of a bounded number of frames (deduped by `event_id`) and an occasional hard failure on retention overflow — both preferable to a doubled file append. The deeper lesson: in streamed agent transports, **receipt is not acknowledgment, and a cursor that advances on receipt is a cursor that lies.** Couple the cursor to the consumer's acceptance, keep the replay window's floor visible to the client, and make a future cursor a hard error. ```python from __future__ import annotations from dataclasses import dataclass class ResumptionGapError(RuntimeError): """Raised when the client's consumed cursor has fallen below the server's replay-retention floor, or when the client is asked to resume from an event the server never emitted. Both mean the tool-call result may have been lost and the side-effect status is unknown; the caller must reconcile, not blindly retry.""" @dataclass(frozen=True) class ResumeState: consumed_cursor: int # highest event_id handed to dispatcher (NOT parsed) parsed_cursor: int # highest event_id tokenized by the SSE reader server_min_retained: int # oldest event_id the server can still replay server_max_emitted: int # newest event_id the server has assigned def build_resume_header(state: ResumeState, *, dedupe_floor: int) -> str: """Compute the Last-Event-ID to send on reconnect. Invariant: the cursor is a function of *dispatch*, never of *receipt*. Any frame parsed-but-not-dispatched is unacknowledged and must be replayed. """ if state.consumed_cursor > state.parsed_cursor: # Impossible: you cannot dispatch a frame you have not parsed. raise ResumptionGapError( f"consumed_cursor {state.consumed_cursor} exceeds parsed_cursor " f"{state.parsed_cursor}; cursor bookkeeping is corrupted" ) if state.parsed_cursor != state.consumed_cursor: # Backpressure drift: parser ran ahead of dispatcher. This is the # dangerous window. We resume from the *consumed* cursor so the # server replays everything the dispatcher never accepted. pass if state.consumed_cursor + 1 < state.server_min_retained: raise ResumptionGapError( f"consumed_cursor {state.consumed_cursor} is below server retention " f"floor {state.server_min_retained}; events are irrecoverably evicted " f"and the tool-call result cannot be replayed" ) if state.consumed_cursor > state.server_max_emitted: # The future-cursor bug: we claim to have consumed events that were # never emitted (classic symptom of a receipt-advanced cursor). raise ResumptionGapError( f"consumed_cursor {state.consumed_cursor} exceeds server_max_emitted " f"{state.server_max_emitted}; refusing to resume from a fabricated future" ) if state.consumed_cursor < dedupe_floor: raise ResumptionGapError( f"consumed_cursor {state.consumed_cursor} precedes dedupe_floor " f"{dedupe_floor}; dispatcher cannot guarantee event_id deduplication" ) return str(state.consumed_cursor) def dispatch_frame(frame_event_id: int, dispatcher_consumed: int) -> int: """Advance the consumed cursor ONLY after the dispatcher accepts a frame. Called from the SSE reader after the dispatcher returns for the payload carrying frame_event_id. Returns the new consumed cursor. """ if frame_event_id <= dispatcher_consumed: # Duplicate replay; dispatcher already handled it. Do not re-dispatch. return dispatcher_consumed if frame_event_id != dispatcher_consumed + 1: raise ResumptionGapError( f"non-contiguous dispatch: got event_id {frame_event_id} after " f"{dispatcher_consumed}; a frame was skipped and its result is lost" ) return frame_event_id ```