# Which invariants prevent silent tool-call loss when an MCP streamable-SSE session resumes across a `Last-Event-ID` gap **Date of Record:** 2026 November 24 **Scope:** Applies to MCP servers exposing the streamable HTTP transport where a single POST/GET SSE stream carries JSON-RPC responses, progress notifications, and server-initiated requests, and where resumption is negotiated via `Last-Event-ID` plus an `Mcp-Session-Id`. Does not apply to stdio transports, to stateless one-shot HTTP transports with no event IDs, or to servers that never emit `id:` fields on SSE frames. ## Core Distinction There are two different things an agent means when it says "resume the session": 1. **Session resumption** — the *logical* conversation and negotiated capabilities survive a transport drop. This is keyed by `Mcp-Session-Id` and is about identity and negotiated state. 2. **Stream resumption** — the *byte/event position* within one SSE response stream survives a TCP reset. This is keyed by `Last-Event-ID` and is about cursor position. The failure mode lives in the seam between them. A client can successfully resume the *session* (server accepts the `Mcp-Session-Id`, capabilities still valid) while silently failing to resume the *stream* (the event with the next expected `id` was never buffered, or was buffered under a different session's replay log). When that happens, the server believes it delivered a tool-call result; the client believes it is caught up because the SSE connection is healthy and heartbeats are flowing. The result is a **tool call that has no observable response and no error** — a hole in the event sequence that both sides route around. The invariant that matters is not "the stream reconnects." It is: **the set of JSON-RPC request IDs the client has outstanding must be reconstructible from the replay log after any `Last-Event-ID` gap, or the client must fail closed.** Most implementations preserve the former and violate the latter. ## What Was Observed A representative trace from an agent runtime driving an MCP server over streamable HTTP. The agent had issued a long-running `tools/call` (a filesystem scan returning ~40 KB) and was reading the response from an SSE stream. ``` POST /mcp Mcp-Session-Id: s_7f3a Accept: text/event-stream -> 200 OK, Content-Type: text/event-stream -> id: 100 event: message data: {"jsonrpc":"2.0","method":"notifications/progress",...} -> id: 101 event: message data: {"jsonrpc":"2.0","method":"notifications/progress",...} -> [TCP RST — mobile network handoff] ``` Client reconnects with the resume cursor: ``` GET /mcp Mcp-Session-Id: s_7f3a Last-Event-ID: 101 -> 200 OK, text/event-stream -> id: 103 event: message data: {"jsonrpc":"2.0","id":42,"result":{...}} -> : keepalive ``` Event `102` is missing. In this trace `102` was a `notifications/progress` frame — harmless. But the identical mechanism drops `id: 102` when it is the `tools/call` *result* for request `42`, and the client has no way to distinguish the two cases because the frame is simply absent. The client sees `103` arrive, treats the stream as live, and never learns that `42`'s result was skipped. The agent's execution loop then either (a) blocks forever waiting on `42` with a healthy-looking connection, or (b) times out on `42`, retries the tool call, and now the tool has executed twice. The root cause is almost always one of three concrete server-side conditions, none of which are visible to the client: - **Replay-log eviction under backpressure.** The server buffers emitted events per session in a bounded ring (commonly 1k–10k frames). When the client is slow or disconnected, the ring wraps and early unacked frames — including the result frame — are evicted. On resume, the server replays from the oldest surviving ID, which is *greater* than `Last-Event-ID + 1`. The gap is real and permanent. - **Per-connection vs per-session event ID space.** Some implementations assign `id` monotonically per *connection* rather than per *session*. A reconnect starts a new counter, so `Last-Event-ID: 101` is interpreted against a fresh sequence and the server either rejects it or silently restarts at `id: 0`. The client's cursor is now meaningless. - **Result delivered on a different stream than the one resumed.** A `tools/call` may emit progress on the POST response stream but the final result on a server-initiated GET stream (or vice versa). If the client resumes only one of them, the result frame is on the stream it did not resume. ## Condition of Validity The "reconnect and continue" behavior is only sound under a conjunction that clients rarely check and servers rarely advertise: 1. **Contiguous, session-scoped event IDs.** Event IDs must be monotonically increasing integers scoped to the session (not the connection), with no reuse across reconnects, and the server must guarantee that `Last-Event-ID: N` yields either the frame with `N+1` or an explicit `400`/`409` indicating the cursor is unreplayable. A server that silently starts at `N+k` violates the precondition. 2. **Replay depth ≥ max in-flight window.** The replay buffer must hold at least as many frames as the client can have outstanding-and-unacked. If the agent allows 8 concurrent tool calls and each can emit 50 progress frames, the buffer must retain ~400 frames *beyond* the last acked ID, not 400 total. 3. **Terminal-frame durability.** The frame carrying a JSON-RPC `result` or `error` for a given `id` must be treated as non-evictable until the client acknowledges it (via a subsequent request referencing that `id`, or an explicit ack) or the session ends. Progress frames are evictable; terminal frames are not. 4. **Gap detection is mandatory.** The client must verify `received_id == last_event_id + 1` on every frame. Any skip is a hard failure, not a warning. When any of these is false — which is the default for most streamable-HTTP MCP servers today — resumption is best-effort and the client must not assume a healthy SSE connection implies a complete response set. ## Decision Boundary The decision the client must make on reconnect is binary and must be made *before* it starts consuming frames: - **If the server's resume response begins at exactly `Last-Event-ID + 1`** (or the client has no outstanding requests), resume normally and continue. - **If the first frame's `id` is greater than `Last-Event-ID + 1`, or the server returns a resume error, or the server does not echo a resumable cursor at all,** the client must treat every request ID that was outstanding at disconnect time as **indeterminate** and resolve each one explicitly: - If the tool is **idempotent** (read-only queries, list operations), re-issue the call with a fresh JSON-RPC `id` and a client-side dedup key. - If the tool is **non-idempotent** (writes, sends, mutations), do **not** blindly retry. The agent must either query an idempotency endpoint, surface the indeterminate state to the orchestrator, or fail the task. Retrying a non-idempotent call after a stream gap is how an agent sends the same email twice. The boundary is therefore not "did the connection come back" but "**can I prove every outstanding request ID has a terminal frame in the replayed prefix?**" If not, the outstanding set is poisoned and must be reconciled, not resumed. ## Operational Effect Agents that skip this reconciliation exhibit three recurring pathologies: - **Silent hangs.** The execution loop awaits a `result` frame that will never arrive because it was evicted. The SSE connection is healthy, keepalives flow, and no timeout fires if the client's read timeout is per-frame rather than per-request. Token budget and wall-clock both burn while the agent sits idle. - **Double execution.** The client's per-request timeout fires, the agent retries the `tools/call`, and the server executes the side effect a second time. This is the dominant cause of duplicate writes in MCP-backed agents that use streamable HTTP with aggressive retry policies. - **Phantom completion.** The client sees a later frame (`id: 103` carrying some *other* request's result) and, in implementations that key responses by arrival order rather than JSON-RPC `id`, attributes it to the wrong request. The agent proceeds with a result that belongs to a different tool call — a correctness failure that is far worse than a hang. The guardrail is a client-side **resume ledger**: on every disconnect, snapshot the set of outstanding JSON-RPC request IDs and their idempotency class; on every reconnect, require the server's first frame to be contiguous with `Last-Event-ID`; if it is not, mark all snapshotted IDs indeterminate and route each through the idempotency decision above before resuming normal consumption. Servers should additionally pin terminal frames in the replay buffer and advertise their replay depth in the session-init response so the client can size its in-flight window against it. ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum class StreamResumeGapError(RuntimeError): """Raised when an SSE resume cannot prove contiguity for outstanding requests.""" class Idempotency(Enum): IDEMPOTENT = "idempotent" NON_IDEMPOTENT = "non_idempotent" @dataclass class OutstandingCall: jsonrpc_id: int idempotency: Idempotency tool: str @dataclass class ResumeLedger: """Tracks in-flight tool calls across an SSE stream disconnect. The invariant enforced here: on resume, the first replayed frame must be exactly `last_event_id + 1`. If it is not, every outstanding call is indeterminate and must be reconciled by idempotency class -- never silently resumed and never blindly retried. """ session_id: str last_event_id: int = 0 outstanding: dict[int, OutstandingCall] = field(default_factory=dict) def on_disconnect(self, in_flight: list[OutstandingCall]) -> None: # Snapshot the outstanding set at the moment the stream dies. self.outstanding = {c.jsonrpc_id: c for c in in_flight} def on_first_resume_frame(self, first_replayed_id: int) -> list[OutstandingCall]: """Validate contiguity of the resumed stream. Returns the list of calls that must be reconciled (possibly empty). Raises StreamResumeGapError if the gap is unrecoverable AND any outstanding call is non-idempotent -- the caller must not proceed. """ expected = self.last_event_id + 1 if first_replayed_id == expected: return [] # contiguous; outstanding calls remain valid, resume normally # Gap detected. All outstanding calls are now indeterminate. indeterminate = list(self.outstanding.values()) non_idempotent = [ c for c in indeterminate if c.idempotency is Idempotency.NON_IDEMPOTENT ] if non_idempotent: raise StreamResumeGapError( f"session {self.session_id}: resume gap " f"expected id {expected}, got {first_replayed_id}; " f"{len(non_idempotent)} non-idempotent call(s) in indeterminate " f"state: {[c.tool for c in non_idempotent]}. " f"Refusing to resume; reconcile via idempotency endpoint or fail task." ) # Only idempotent calls outstanding: safe to re-issue with fresh IDs. return indeterminate def on_frame(self, event_id: int) -> None: if event_id != self.last_event_id + 1: raise StreamResumeGapError( f"session {self.session_id}: non-contiguous frame " f"(expected {self.last_event_id + 1}, got {event_id})" ) self.last_event_id = event_id def resolve(self, jsonrpc_id: int) -> None: self.outstanding.pop(jsonrpc_id, None) def resume_agent_stream( ledger: ResumeLedger, first_replayed_id: int ) -> list[OutstandingCall]: """Entry point the agent loop calls immediately after SSE reconnect.""" return ledger.on_first_resume_frame(first_replayed_id) ```