# Which invariants prevent silent tool-call replay divergence when an MCP stream is resumed across an HTTP session re-bind **Date of Record:** 2026 November 23 **Scope:** Applies to MCP servers exposing tool calls over HTTP-native transport with `Last-Event-ID` stream resumption (SSE) and session re-binding via `Mcp-Session-Id`, where the agent client is stateless per-call and the server keeps per-session replay buffers. Does not apply to stdio transport, nor to purely idempotent read-only tools with no server-side side effects. ## Core Distinction The failure is not "the connection dropped." The failure is that a resumed stream and a re-bound session are two *independent* recovery mechanisms that each restore a different half of the state, and nothing in the MCP transport layer forces them to agree. `Last-Event-ID` restores the *event cursor* (which `tools/call` responses the client has not yet consumed). `Mcp-Session-Id` restores the *server-side session context* (capability set, in-flight call bookkeeping, per-session replay buffer). When a client reconnects with a valid `Last-Event-ID` but a *fresh or mismatched* session id — or vice versa — the server may replay events from a cursor that belongs to a different session's buffer, or accept a session re-bind that re-executes a tool whose result event was already delivered under the old buffer. The invariant that must hold is: **an event cursor is only meaningful relative to the exact session buffer that issued it.** Any resumption path that reconstructs one without pinning the other produces replay divergence — the client believes it has a coherent view of tool-call results, but some results were re-emitted (double effect) and others were silently dropped (lost effect) because the cursor and the buffer were never validated as a pair. ## What Was Observed A stateless agent client issues `tools/call` for a side-effecting tool (`append_ledger_entry`) and receives the response as an SSE event with `id: 41`. The TCP connection dies mid-stream, *after* the server has already committed the side effect and emitted event 41, but *before* the client's read loop has acknowledged it. The client's retry wrapper does two things in the wrong order: 1. It opens a new connection and re-binds a session, sending `Mcp-Session-Id: S2` (a freshly negotiated session, because the client treats sessions as disposable per-connection). 2. It also sends `Last-Event-ID: 41` (because the cursor is persisted in the client's durable retry state, independent of session). The server receives a cursor `41` that was minted by session `S1`'s buffer, but the request is authenticated against session `S2`. Two server implementations diverge here, and both are wrong in different ways: - **Lenient server:** resolves `Last-Event-ID: 41` against `S2`'s buffer. `S2` is fresh, so its buffer has no event 41; the server treats the cursor as "already consumed up to 41" and sends nothing. The client waits forever for a result that was *committed* but never *delivered*. Silent lost effect. - **Strict-replay server:** cannot find 41 in `S2`, falls back to replaying `S2` from its start, which re-issues the `tools/call` because the client's retry also re-sent the request body. The tool executes twice. Double effect on the ledger. The divergence is invisible to the agent's reasoning loop: in the first case it hangs, in the second it sees a "success" for an operation that actually happened twice. Neither case surfaces a transport error, because both the cursor and the session id were individually *valid* — only their *pairing* was invalid. ## Condition of Validity Stream resumption is only sound under a conjunction of conditions that the transport must enforce, not assume: 1. **Cursor–buffer binding:** the server must reject any `Last-Event-ID` whose originating session id does not match the presented `Mcp-Session-Id`. The cursor is opaque but must be *scoped*; treat it as `(session_id, seq)` internally even if the wire form is a bare token. 2. **Effect-once guarantee:** a `tools/call` that has committed a side effect must have its result event durably recorded in the session buffer *before* the side effect is acknowledged to the caller, so that any resumption that reaches the cursor will find the result. If the result event is emitted after commit but not persisted, a resume that skips the cursor loses the result. 3. **Re-bind ≠ replay:** re-binding a session must never re-execute a request that the server has already processed. Session re-bind restores *context*, not *work*. Re-execution is only permissible when the client explicitly re-issues the request with a fresh idempotency key, and the server must deduplicate on that key. 4. **Monotonic cursor per session:** within a session, event ids must be strictly increasing and never reused, so that "consume up to N" is a well-defined cut. A server that recycles ids across re-binds breaks the cut semantics. The boundary: if any of these is violated, the client's recovered state is *plausible but wrong* — the worst class of failure for an agent, because it will proceed to reason on a corrupted view of what tools actually did. ## Decision Boundary The operational decision is how the client should behave on reconnect, and it hinges on whether the cursor and session can be proven to belong together: - **If the client can present the original session id and the server still holds that session's buffer:** resume with `Last-Event-ID` and *do not* re-send the request body. This is the only safe replay path. - **If the original session is gone (server GC'd it) but the cursor is retained:** the client must treat the cursor as *invalid*, discard it, and re-issue the call with a new idempotency key. It must NOT present a stale cursor against a new session — that is precisely the divergence trigger. - **If the server cannot distinguish "cursor from another session" from "cursor ahead of buffer":** it must fail closed with a typed error rather than silently skipping. A skipped cursor is indistinguishable from a consumed event, and the agent cannot tell the difference. The invariant the decision enforces: *never let a client's belief about tool-call completion be reconstructed from two independently-validated tokens.* Either both the cursor and session validate together, or neither is trusted. ## Operational Effect When the pairing invariant is enforced, the failure mode degrades from silent divergence to a loud, recoverable error: the client gets a `SessionCursorMismatch`, discards the stale cursor, and re-issues with idempotency — at worst one duplicate-suppressed retry, never a double effect or a phantom hang. When it is not enforced, agents exhibit a characteristic pathology: they hang on tools that actually succeeded (lost-effect case) or double-count side effects (double-effect case), and their reasoning traces look *internally consistent* because the corruption is in the transport's reconstruction, not in the model's logic. The agent has no signal to distrust its own memory of what happened. The guardrail is architectural, not probabilistic: bind the cursor to the session at mint time, persist the result event before committing the effect, and make re-bind a context operation that never re-executes work. These three together are the minimum to keep stateless tool calls from silently diverging across a resumed stream. ```python class SessionCursorMismatch(RuntimeError): """Raised when a Last-Event-ID cursor cannot be proven to belong to the presented Mcp-Session-Id, so resumption would risk replay divergence.""" pass class ReplayBuffer: def __init__(self): # session_id -> list of (seq, event_payload) self._buffers: dict[str, list[tuple[int, dict]]] = {} def mint_cursor(self, session_id: str, seq: int) -> str: # Cursor is scoped: wire form encodes session so it can be validated. return f"{session_id}:{seq}" def resume(self, session_id: str, last_event_id: str) -> list[dict]: try: cursor_session, cursor_seq_str = last_event_id.rsplit(":", 1) cursor_seq = int(cursor_seq_str) except (ValueError, AttributeError): raise SessionCursorMismatch( f"malformed cursor {last_event_id!r}; refusing to resume" ) # Invariant: cursor must have been minted by the same session buffer. if cursor_session != session_id: raise SessionCursorMismatch( f"cursor {last_event_id!r} belongs to session {cursor_session!r} " f"but request is bound to {session_id!r}; replay would diverge" ) buf = self._buffers.get(session_id) if buf is None: raise SessionCursorMismatch( f"session {session_id!r} buffer is gone; cursor {last_event_id!r} " f"is unverifiable, must re-issue with idempotency key" ) # Monotonic cut: only events strictly after the cursor are replayed. return [payload for seq, payload in buf if seq > cursor_seq] ```