# Which invariants prevent SSE resumption from silently forking a tool-call stream across MCP HTTP transports **Date of Record:** 2026 December 3 **Scope:** Applies to MCP servers exposing HTTP-native streaming transport with `Last-Event-ID`-based SSE resumption and a server-initiated request channel (sampling, elicitation, roots). Does not apply to stdio transports or to pure request/response HTTP without server push. ## Core Distinction The failure is not "the SSE connection dropped." Connections drop constantly and recovery is well-understood. The failure is that **resumption replays a stream segment whose server-initiated requests were already consumed and answered on the prior connection, but whose responses the client cannot prove were delivered** — so the client either re-answers them (duplicate side effects) or drops them (orphaned server state). The distinguishing question is not *did the stream resume* but *can both ends agree on which server-initiated request IDs have been committed*. Event IDs resume the byte stream; they do not resume the request/response ledger. Those are two different monotonic sequences and conflating them is the boundary. A second, subtler distinction: the server's replay buffer is bounded and keyed by event ID, but server-initiated requests are *out-of-band* relative to that buffer. A replay that looks byte-identical can carry a `sampling/createMessage` request whose lifetime is independent of the SSE cursor. Resumption is only sound when the invariant "every replayed event ID maps to an event whose downstream obligations are either idempotent or already acknowledged" holds. Nothing in the transport spec enforces that; it must be constructed. ## What Was Observed A client agent held a long-running MCP session against a server that emits progress notifications over SSE and, mid-stream, issues a `sampling/createMessage` server-initiated request to have the client run an LLM completion. Sequence: 1. Client opens SSE stream, receives events `id=100..140`. At `id=137` the server emits a server-initiated request `req-7` (sampling). Client reads it, dispatches the completion, and posts the response out-of-band via `POST /messages`. 2. The POST for `req-7`'s response times out at the client's HTTP layer (30s) while the server actually received and *processed* it, then the server's SSE connection to the client is torn down by an intermediary (idle timeout at a proxy). 3. Client reconnects with `Last-Event-ID: 136` (its last *acknowledged* event; it never advanced the cursor past 137 because it treats 137 as uncommitted until the sampling round-trip succeeds). 4. Server replays from 137. Event 137 re-emits the `sampling/createMessage` request as `req-7` again — same ID, same payload, because the server keys the replay buffer by event ID and does not consult its own request ledger. 5. Client, having no record that its `POST` was received, re-runs the sampling completion and posts the response again. The server now has two responses for `req-7`, applies the second over the first, and — because the sampling result feeds a subsequent tool call the server was going to make — executes the downstream tool invocation twice. The trace shows the split: the client's cursor (`Last-Event-ID`) and the server's request ledger (`req-7` answered) advanced independently and disagreed. The client was *correct* not to advance past 137 (it had no ack), and the server was *correct* to replay from 137 (its buffer says so). Both correct, jointly wrong. That is the boundary condition: a resumption protocol with two independent progress variables and no joint commit. A second observed variant: when the server's replay buffer was configured small (retain last 20 events), a client resuming at `Last-Event-ID: 136` after a 45-event gap received a `410 Gone` and — because the MCP client library treated 410 as "stream ended normally" — silently continued with a truncated view, having missed `req-8` entirely. The server blocked forever waiting for a response that no one knew to send. ## Condition of Validity Resumption is sound only when all of the following hold simultaneously. Each is an invariant the transport spec leaves to the implementation: - **Ledger-cursor coupling.** The server must not re-emit a server-initiated request on replay unless it can prove the prior response was not applied. Operationally: the server records `req-id → {dispatched, applied}` and, on replay, suppresses re-emission of any request in `applied` state, substituting a tombstone event (`request_settled: req-7`) so the client's cursor can advance past 137 without re-running. Without this, replay is not idempotent with respect to side effects. - **Client-side commit acknowledgment.** The client must advance `Last-Event-ID` past an event only when the event carries no unresolved server-initiated obligation, *or* when it has received positive acknowledgment that its response was applied. A bare HTTP 200 on the response POST is insufficient if the POST can time out after server-side application — which is exactly the observed case. The response endpoint must return an idempotency token the client can use to query "was `req-7` applied?" before re-posting. - **Bounded-replay honesty.** A `410 Gone` (or equivalent) on resumption must be surfaced as a *fatal session error*, not a clean stream end. The invariant: a client that cannot resume from its cursor must be told the session is unrecoverable, because a truncated view of a server-initiated channel means orphaned server state, not a shorter stream. - **Monotonic event IDs across reconnects.** Event IDs must never be reused for semantically different events. A server that restarts its counter after a process restart will hand the client an `id=137` that is not the 137 the client remembers. This is the same class of bug one layer down and must be guarded by a session epoch embedded in the ID space. ## Decision Boundary The decision the implementer must make is where the commit point lives. Two coherent designs, one incoherent: - **At-least-once with idempotent obligations (chosen when server-initiated requests are side-effect-free or idempotency-keyed).** Server may re-emit; client may re-answer; every server-initiated request carries an idempotency key and the server deduplicates on apply. Resumption cursor and request ledger are allowed to diverge because convergence is guaranteed by dedup. This is the cheap design and is correct *only* if every server-initiated request type is genuinely idempotent — sampling and elicitation usually are not, because the client's LLM completion is non-deterministic and the second completion may differ from the first, so "dedup by request ID, keep first" is required and the server must discard the duplicate completion rather than apply it. - **Exactly-once with coupled ledger (chosen when server-initiated requests trigger irreversible tool calls).** Server suppresses re-emission of applied requests and emits settlement tombstones; client advances cursor only past settled or obligation-free events. This is the expensive design and is the only one that bounds the observed double-execution. The incoherent middle — re-emit on replay *and* apply every response — is what produced the trace above. The boundary is crossed the moment a server-initiated request's downstream effect is non-idempotent and the server's replay path does not consult the ledger. ## Operational Effect Concretely, an agent operating on this transport must treat the SSE cursor and the server-initiated request ledger as two variables and never let a resumption advance the cursor past an unsettled request. In practice this means: - The client keeps a local `pending_requests` set. On reconnect, it does not set `Last-Event-ID` past the lowest event ID that dispatched a still-pending request; it resumes *at or before* that point and relies on the server's settlement tombstones to advance. - Before re-posting a response after a timeout, the client queries the server's idempotency token. If applied, it synthesizes the settlement locally and advances. If not, it re-posts. - A `410` or any replay-window miss is escalated to a session-fatal error; the agent does not proceed with a truncated server-initiated channel, because a missed `sampling/createMessage` means the server is blocked on a response that will never come, and the agent will hang at the next tool call with no diagnostic. - Event IDs are namespaced by session epoch; a client that sees an event ID lower than its cursor treats it as a new epoch and refuses to resume, forcing a fresh handshake. The invariant that prevents the fork is: **no resumption may advance a cursor past an event whose server-initiated obligation is unresolved, and no server may re-emit a server-initiated request whose response it has already applied.** Both halves are required; either alone leaves the double-execution window open. ```python class ResumptionForkError(RuntimeError): """Raised when SSE resumption would fork a server-initiated request ledger.""" pass class ResumableStream: def __init__(self, server): self.server = server self.cursor = 0 # last committed event ID self.pending = {} # req_id -> event_id that dispatched it self.settled = set() # req_ids confirmed applied def on_event(self, event): if event.id <= self.cursor and event.epoch != self.server.epoch: raise ResumptionForkError( f"event id {event.id} reuses a prior ID under new epoch " f"{self.server.epoch}; cursor {self.cursor} is not comparable" ) if event.kind == "server_request": self.pending[event.req_id] = event.id elif event.kind == "request_settled": self.pending.pop(event.req_id, None) self.settled.add(event.req_id) self._advance() def _advance(self): # Never advance past an event that dispatched an unsettled request. floor = min(self.pending.values(), default=self.cursor + 1) self.cursor = max(self.cursor, floor - 1) def resume(self): resp = self.server.reopen_sse(last_event_id=self.cursor) if resp.status == 410: raise ResumptionForkError( f"replay window missed at cursor {self.cursor}; " f"server-initiated channel is truncated, session is unrecoverable" ) for event in resp.events: self.on_event(event) def respond(self, req_id, payload, idem_token): if req_id in self.settled: return # already applied; do not re-run the completion status = self.server.query_applied(req_id, idem_token) if status == "applied": self.settled.add(req_id) self.pending.pop(req_id, None) self._advance() return try: self.server.post_response(req_id, payload, idem_token) except TimeoutError: # Do NOT clear pending; the response may have been applied. # Re-check on next resume; cursor stays pinned below this event. if self.server.query_applied(req_id, idem_token) != "applied": raise ResumptionForkError( f"req {req_id} response unconfirmed after timeout; " f"cursor pinned at {self.cursor} to prevent ledger fork" ) self.settled.add(req_id) self.pending.pop(req_id, None) self._advance() ```