# Why does an instance lose tool-call continuity when an MCP Streamable-HTTP SSE channel reconnects between `Last-Event-ID` delivery and the in-flight request being replayed? **Date of Record:** 2026 December 1 **Scope:** Applies to MCP servers using the Streamable HTTP transport where a single session multiplexes client→server JSON-RPC requests against a server→client SSE stream carrying responses and notifications, and where the client resumes via `Last-Event-ID` after transport drop. Does not apply to stateless stdio transports, nor to pure request/response HTTP without an SSE channel. ## Core Distinction The failure is not "the connection dropped." It is that **resumption and replay are two different clocks that the transport spec lets drift apart**. `Last-Event-ID` resumption replays the *notification/response event log* from a cursor, but it does not replay the *inbound request* that was in flight when the stream broke. The server, on reconnect, considers the session alive (it has the session ID) but has no obligation to re-execute the request whose response event was never emitted before the cursor. The client, meanwhile, treats "stream resumed from cursor N" as "no work was lost," because the SSE contract's implicit invariant is *event log is the source of truth for everything the server wanted to tell me*. That invariant is false the moment a request's side effect is committed but its response event is not. The precise boundary: **a tool call whose execution is non-idempotent and whose completion event lands after the disconnect cursor but whose side effect landed before it.** The event log and the effect log diverge by exactly one request, and neither the client nor the server can tell which one without an external witness. ## What Was Observed A single-session agent loop issuing `tools/call` over Streamable HTTP. The sequence under load: 1. Client sends `POST /mcp` with JSON-RPC `tools/call` (id `c-4417`), carrying `Mcp-Session-Id`. Server accepts, begins executing a tool with an external side effect (an append to a remote ledger), and streams a `202 Accepted` with an SSE channel. 2. Server commits the side effect at T+0. Server writes the JSON-RPC response event to the session's event buffer with `event: message`, `id: 118`. The write to the socket fails (NAT rebind, LB idle timeout at 60s, or a proxy half-close). The event sits in the buffer, unacknowledged. 3. Client's SSE reader raises `RemoteProtocolError`. The agent runtime, following the transport spec, reconnects with `GET /mcp` + `Last-Event-ID: 117` (last *successfully parsed* event, not 118, because 118 never arrived). 4. Server resumes the stream from 117 and **replays event 118**, which is the response to `c-4417`. Good — this is the happy path, and it works. 5. The failure case: the disconnect happens *before* the server writes event 118, at T+0 but between the side-effect commit and the buffer append. Server reconnects at `Last-Event-ID: 117`, replays nothing new (118 not yet written), and the client's pending-request table still holds `c-4417` with no response. The agent's per-request timeout fires at T+30s. The runtime — reasonably, given no response — **retries `c-4417` with the same JSON-RPC id**. 6. Server sees `c-4417` again. Its session state has no dedup entry (the response was never emitted, so nothing recorded the id as answered). It executes the tool again. The ledger gets two appends. The non-obvious part: in step 5 the server *did* keep the session alive and *did* honor resumption semantics correctly. The spec is satisfied on both sides. The duplicate side effect is a consequence of the spec leaving request-level idempotency to the application while the transport's resumption machinery creates the exact window where a client is *forced* to retry an unacknowledged request. A second observed variant: the server writes event 118 *and* the client parses it, but the client crashes between parse and dispatch to the pending-request table (process restart, OOM kill of the worker). On cold start the agent has the session ID from its checkpoint but not the in-memory pending table, so it reconnects, gets no replay (cursor is past 118), and either hangs the tool call forever or re-issues it. Here the event was delivered but the *dispatch* was lost — a checkpoint/resume gap that the SSE cursor cannot see. ## Condition of Validity The invariant "SSE resumption preserves tool-call continuity" holds only when **all three** of the following are true: - **(A) Effect-before-event ordering is atomic.** The server must commit the tool side effect and append the response event to the session buffer in a single durable step (same transaction, or event-append-then-effect with a compensating rollback, or effect-then-event with a durable "effect committed, event pending" marker). If the two can diverge across a crash or socket failure, the window is open. - **(B) The client's cursor advances only on dispatch, not on parse.** `Last-Event-ID` must be persisted *after* the response is routed to the pending-request table and the caller is unblocked. If the runtime persists the cursor on parse (the common SSE client idiom), a crash between parse and dispatch loses the response with no replay path. - **(C) Request IDs are deduped server-side across the session lifetime.** The server must retain a bounded map of `(session_id, jsonrpc_id) → response` so that a retried `c-4417` returns the cached response rather than re-executing. This is the only thing that makes client retry safe. When any one is false, the client is in a state where it *must* either hang (no response, no replay) or duplicate (retry into a server that re-executes). There is no third option available at the transport layer. ## Decision Boundary The agent runtime must decide, on stream drop with pending requests, between **replay-wait** and **retry**, and the correct choice depends on a fact the runtime does not have: whether the side effect committed. The boundary is: - If the transport can prove the response event exists past the cursor (server advertises a `resume-token` or a `GET /mcp/sessions/{id}/pending` endpoint returning the set of unanswered request IDs), the runtime must **wait for replay** and never retry. Retry is forbidden while a pending request is provably unanswered-but-alive. - If the server cannot prove it (no pending-set endpoint, or the endpoint returns "unknown" because the session buffer was evicted), the runtime must **retry with a client-generated idempotency key**, not the bare JSON-RPC id, and the server must honor the key. The JSON-RPC id is per-connection in most client libraries and is not a stable dedup key across reconnects. - The forbidden middle: retrying with the same JSON-RPC id against a server that has no dedup map. This is the observed failure. It is forbidden not because it is wrong in principle but because it converts an unknown-outcome into a duplicate-effect. Concretely, the runtime should refuse to retry any `tools/call` whose tool is declared non-idempotent unless it carries an idempotency key the server has acknowledged. The declaration must live in the tool's schema, not in the agent's prompt — a probabilistic reasoner will not reliably remember which tools are safe to retry under context pressure. ## Operational Effect The downstream consequences compound in ways that look like reasoning failures but are transport artifacts: - **Duplicate ledger entries, double-sent emails, double-charged cards** — the direct effect, and the one that gets noticed. - **Error compounding in multi-step loops**: the agent sees two responses for what it believes is one call (the replayed `c-4417` from step 4's happy path, then the retry's response), and its scratchpad now contains two tool results for one intent. It reconciles them incorrectly, and the divergence propagates into subsequent steps. - **Stale pending-table entries** after cold start: the agent resumes with a session ID, no pending table, and either re-issues work already done (duplicate) or abandons work whose response is sitting in the server's buffer past its cursor (lost). The session looks alive; the work is not. - **Auditor disagreement in multi-agent setups**: a verifier agent reading the ledger sees two appends and flags the executor as having violated a one-call invariant, when the executor's reasoning was correct and the transport duplicated. The verification replay disagrees with the execution trace, and the disagreement is unresolvable without the transport's event log. The guardrail that bounds this is the three-condition invariant above, enforced at the transport integration layer, not at the agent layer. The agent cannot be trusted to enforce it because the agent is the component whose finite context and probabilistic retry policy create the window. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class ResumptionContinuityError(RuntimeError): """Raised when SSE resumption cannot prove tool-call continuity.""" pass @dataclass class PendingCall: jsonrpc_id: str idempotency_key: str tool_name: str non_idempotent: bool cursor_at_send: int dispatched: bool = False @dataclass class SessionState: session_id: str last_event_id: int = 0 pending: dict = field(default_factory=dict) # server-advertised: ids the server has committed effects for but not yet # emitted response events for. Empty set + no endpoint => unknown. server_unanswered: Optional[set] = None server_dedup_supported: bool = False def make_idempotency_key(session_id: str, jsonrpc_id: str, tool_name: str) -> str: return hashlib.sha256( f"{session_id}:{jsonrpc_id}:{tool_name}".encode() ).hexdigest()[:32] def on_stream_drop(state: SessionState) -> None: """Called when the SSE reader raises. Decide replay-wait vs retry.""" if not state.pending: return for call in state.pending.values(): if call.non_idempotent: if state.server_unanswered is None: raise ResumptionContinuityError( f"non-idempotent call {call.jsonrpc_id} ({call.tool_name}) " f"in flight; server exposes no pending-set endpoint, so " f"outcome is unknown. Refusing to retry — would duplicate " f"a committed side effect. Requires server-side dedup or " f"pending-set advertisement to proceed." ) if call.jsonrpc_id in state.server_unanswered: # server proves the request is alive; wait for replay, do not retry continue # server proves the request is answered but event was lost; # only safe to retry if the server dedups on idempotency key if not state.server_dedup_supported: raise ResumptionContinuityError( f"call {call.jsonrpc_id} answered server-side but response " f"event lost past cursor {state.last_event_id}; server does " f"not honor idempotency keys, retry would re-execute." ) def advance_cursor(state: SessionState, event_id: int, routed: bool) -> None: """Cursor must advance only after dispatch, not on parse.""" if not routed: raise ResumptionContinuityError( f"refusing to advance Last-Event-ID to {event_id}: event parsed " f"but not dispatched to pending table; crash here loses the " f"response with no replay path (cursor would be past it)." ) state.last_event_id = max(state.last_event_id, event_id) def resume(state: SessionState, advertised_cursor: int) -> None: if advertised_cursor > state.last_event_id: raise ResumptionContinuityError( f"server cursor {advertised_cursor} ahead of persisted cursor " f"{state.last_event_id}; events in between were never dispatched. " f"Cold-start gap — reconcile pending table before resuming." ) ```