# How does an instance detect that an MCP stream resumption has silently replayed a non-idempotent tool call **Date of Record:** 2026 November 26 **Scope:** Applies to Model Context Protocol servers and clients using the HTTP-native transport (SSE-over-POST, `Last-Event-ID` resumption) where a streaming tool invocation spans a reconnect. Does not cover stdio transport, in-process transports, or servers that buffer entire responses before emitting a single terminal event. ## Core Distinction The distinction that matters is between **transport-level resumption** and **execution-level resumption**. The MCP HTTP-native transport defines a resumption contract at the stream layer: the client reconnects with `Last-Event-ID`, and the server replays every event after that ID from a per-session buffer. This contract says nothing about whether the *tool execution* that produced those events is idempotent. A resumed stream is a faithful replay of bytes; it is not a faithful replay of side effects. The failure mode is therefore not "the stream broke." The stream resumes correctly. The failure is that a client which reconnects mid-call cannot distinguish between (a) events it missed because it disconnected and (b) events it already processed before disconnecting, when the server's event-ID assignment is per-connection rather than per-session. In the per-connection case, the reconnecting client is issued a fresh ID namespace starting near zero, and its `Last-Event-ID` from the prior connection either matches nothing or matches an unrelated event. The server then either replays from the beginning of the buffered log (duplicating already-consumed events, including a `tools/call` result whose side effect already fired) or resets the buffer entirely (dropping events the client never saw, leaving a `tools/call` with no terminal result). The invariant that is violated: **event IDs must be monotonic and session-global, not connection-local, for `Last-Event-ID` resumption to be safe.** When a server assigns IDs from a per-connection counter, the protocol's resumption semantics degrade from "resume exactly where you left off" to "resume somewhere plausible," and the client has no protocol-level signal to tell which. ## What Was Observed A client agent issued `tools/call` for a tool that appends a row to an external ledger and returns the new row count. The transport was HTTP-native with SSE streaming. The server emitted three events: an acknowledgement (`event: message`, id `1`), a progress notification (id `2`), and the terminal result (id `3`). The client's network path dropped after receiving id `2` but before id `3` arrived. The client reconnected with `Last-Event-ID: 2`. The server had been restarted between the disconnect and the reconnect (a rolling deploy, not a crash). Its session store was in-memory and per-process. The new process had no record of session `s-4471`. It accepted the reconnect, created a fresh session under the same client-supplied session header, and — because the client's `Last-Event-ID: 2` referenced an event the new process had never emitted — treated the header as a hint it could not honor. It re-executed the `tools/call` from the request body (the client had resent the original POST, which is the documented reconnect behavior for a POST-initiated stream) and emitted a new event stream with IDs `1`, `2`, `3` under the new connection. The ledger received two rows. The client received a terminal result reporting row count `N+1` for a call that had actually produced `N+2`. The client's internal state was consistent with its own view of the world and inconsistent with the ledger. No error was raised at any layer: the transport reconnected cleanly, the tool returned success, the event IDs were well-formed, and the JSON-RPC response was schema-valid. The detection signal was not in the protocol. It was in a downstream reconciliation job that compared the client's reported row count against the ledger's actual count and found a delta of one. The delta was attributed to the client until the server's access log showed two `tools/call` executions for the same logical request, separated by 4.2 seconds — the reconnect window. ## Condition of Validity The failure requires the conjunction of four conditions, and the guardrail is only meaningful when all four hold: 1. **The tool is non-idempotent.** A read-only or upsert tool replayed twice produces the same observable state. A tool that appends, increments, sends, or charges does not. 2. **The server's event-ID namespace is connection-local.** If IDs are session-global and the buffer survives the reconnect, `Last-Event-ID` correctly suppresses replay and the client resumes at id `3`. The bug is specifically the mismatch between the protocol's assumption (session-global IDs) and the server's implementation (connection-local IDs). 3. **The session state does not survive the reconnect.** In-memory session stores behind a load balancer without sticky routing, or processes that restart between disconnect and reconnect, lose the buffer. A durable session store with a monotonic ID counter eliminates the failure even with connection-local-looking IDs, because the counter is persisted. 4. **The client resends the original request on reconnect.** This is the documented behavior for POST-initiated SSE streams: the client re-POSTs and presents `Last-Event-ID` as a header. If the client instead opens a bare GET with `Last-Event-ID` and the server supports replay-only GET, the tool is not re-executed — but the client then hangs waiting for a terminal event that the new process will never emit, which is a different failure (liveness, not duplication). When any of these four is absent, the failure does not manifest, and the guardrail described below is unnecessary overhead. The guardrail is therefore conditional, and the condition is detectable at session-establishment time. ## Decision Boundary The decision the client must make on reconnect is: **do I trust `Last-Event-ID` to mean "events after this point have not been executed," or do I treat the reconnect as a fresh call?** The protocol does not give the client enough information to decide, so the client must impose its own invariant. The invariant: **a `tools/call` is only safely resumable if the client can prove the server's event-ID namespace is session-global and the session store is durable.** The client cannot prove this from the protocol alone. It can prove it by one of two mechanisms: - **Capability negotiation at session init.** The server advertises a capability flag (e.g., `streaming.resumable: true` with a `session.id.epoch` value). The client records the epoch at session start and refuses `Last-Event-ID` resumption across an epoch change, falling back to a fresh call with a client-generated idempotency key. - **Idempotency keys on the tool call itself.** The client attaches a deterministic key (hash of tool name, arguments, and a client-side monotonic call counter) to every `tools/call`. The server deduplicates on the key. Replay becomes safe regardless of transport semantics, because the second execution is suppressed at the application layer. The boundary is crossed when a client resumes a stream without either mechanism in place. Below the boundary — read-only tools, or servers with durable session stores — resumption is safe and the client should resume. Above the boundary — mutating tools against a server whose session durability is unknown — the client must not resume; it must re-issue with an idempotency key and accept the possibility of a duplicate that the server will suppress. The hard part is that the client often does not know which side of the boundary it is on. The session-init handshake is the only reliable place to establish it, and most MCP client implementations skip the handshake's capability fields when the server returns a minimal response. ## Operational Effect The operational effect is a class of silent duplicate side effects that are invisible to every layer of the stack: the transport reports a clean reconnect, the tool reports success, the JSON-RPC response validates, and the client's state is internally consistent. The duplicate is only visible in the external system the tool mutated, and only if that system is reconciled against the client's reported state. The secondary effect is worse: because the client's terminal result reflects the *second* execution, the client's reported state is off by exactly the number of replayed non-idempotent calls. In a fan-out scenario where a supervisor agent dispatches twenty sub-agents each making a mutating call, a single reconnect storm during a deploy can produce a systematic bias in the supervisor's aggregated state that is indistinguishable from a legitimate result. The supervisor has no way to know its sub-agents' calls were replayed, because each sub-agent's report is internally consistent. The architectural guardrail is therefore not at the transport layer. It is at the tool-call layer: **every non-idempotent `tools/call` must carry a client-generated idempotency key, and the server must deduplicate on it before executing.** The transport's `Last-Event-ID` resumption is a latency optimization, not a correctness mechanism. Treating it as a correctness mechanism is the boundary violation. The detection mechanism, when the guardrail is absent, is reconciliation against the external system — which means the failure is only caught after the fact, by a system that was designed to catch it for other reasons. That is not a detection strategy; it is a hope. ```python import hashlib import json from dataclasses import dataclass, field from typing import Any class ResumptionIntegrityError(RuntimeError): """Raised when a stream resumption cannot be proven safe for a non-idempotent call.""" @dataclass class SessionEpoch: session_id: str epoch: str durable: bool ids_session_global: bool @dataclass class PendingCall: tool: str arguments: dict[str, Any] idempotency_key: str last_event_id: int | None = None executed: bool = False def make_idempotency_key(tool: str, arguments: dict[str, Any], call_seq: int) -> str: payload = json.dumps( {"tool": tool, "args": arguments, "seq": call_seq}, sort_keys=True, separators=(",", ":"), ).encode() return hashlib.sha256(payload).hexdigest() def resume_stream( epoch_at_connect: SessionEpoch, epoch_at_resume: SessionEpoch, pending: PendingCall, server_supports_dedup: bool, ) -> str: """Decide whether to resume via Last-Event-ID or re-issue with an idempotency key. Returns a decision token: "resume" or "reissue". """ if not pending.executed: # Nothing has fired yet; resumption is always safe. return "resume" # A tool call already executed. Resumption now risks replaying its side effect. epoch_changed = epoch_at_connect.epoch != epoch_at_resume.epoch session_lost = epoch_at_connect.session_id != epoch_at_resume.session_id ids_unsafe = not epoch_at_resume.ids_session_global store_unsafe = not epoch_at_resume.durable resumption_unsafe = epoch_changed or session_lost or ids_unsafe or store_unsafe if resumption_unsafe and not server_supports_dedup: raise ResumptionIntegrityError( f"cannot safely resume executed call {pending.tool!r} " f"(key={pending.idempotency_key[:12]}...): " f"epoch_changed={epoch_changed} session_lost={session_lost} " f"ids_unsafe={ids_unsafe} store_unsafe={store_unsafe} " f"and server does not deduplicate on idempotency keys" ) if resumption_unsafe and server_supports_dedup: # Safe to re-issue: the server will suppress the duplicate. return "reissue" return "resume" ```