# Under what conditions must an instance treat MCP Streamable HTTP session resumption as a replay-safe boundary rather than a transparent reconnect **Date of Record:** 2026 November 30 **Scope:** Applies to MCP servers and clients using the Streamable HTTP transport (single `/mcp` endpoint, `Mcp-Session-Id` header, optional SSE upgrade per request, `Last-Event-ID` resumption) where a session may be resumed after a transport drop, proxy timeout, or client reconnect. Does not apply to stdio transports, nor to stateless HTTP servers that issue no `Mcp-Session-Id`. ## Core Distinction There are two things a client can mean by "resume," and the Streamable HTTP spec conflates them at the wire level while leaving the semantics to the server: 1. **Transport resumption** — re-establishing the byte stream for an in-flight JSON-RPC exchange so that the *response* to an already-sent request is delivered. The request has been dispatched; the client is owed exactly one response. 2. **Session resumption** — re-binding to server-side session state (capabilities, subscriptions, pending server→client requests) after the connection died. The client may have *lost* responses it never saw, and may also have *lost* server-initiated requests it never answered. The invariant that most clients violate: **`Last-Event-ID` replay is at-least-once delivery of SSE events, but JSON-RPC request/response is exactly-once semantics.** A resumed stream can legally redeliver events the client already processed (server buffers events per stream, not per client), and it can also *silently omit* events if the server's replay buffer was truncated or the session expired. An agent that treats a resumed stream as "the connection was just flaky, continue where I was" will double-apply tool side effects or, worse, block forever waiting for a response event that the server never replayed because the original request's stream was closed server-side on the first disconnect. The non-obvious boundary: **resumption is only replay-safe when the client can prove, from its own durable state, that it has not already observed the terminal event for every outstanding request ID — and can re-issue any request whose terminal event is not provably replayable.** The spec gives you `Last-Event-ID`; it does not give you a request-ID-to-stream mapping, and that is the gap where agents corrupt their own state. ## What Was Observed A tool-calling agent issued `tools/call` for a filesystem-mutating operation (`write_file`) over Streamable HTTP with SSE upgrade. Sequence: 1. Client sends `POST /mcp` with `Mcp-Session-Id: S1`, body `{"jsonrpc":"2.0","id":42,"method":"tools/call",...}`. Server accepts, begins SSE stream, emits `id: 100` (progress notification), then `id: 101` (the `result` for id 42). The TCP connection is severed by an intermediate proxy idle-timeout *after* the server wrote `id: 101` to its buffer but *before* the client's kernel delivered it. 2. Client reconnects with `GET /mcp` + `Mcp-Session-Id: S1` + `Last-Event-ID: 100`. The server, per its buffer policy, replays from `101`. The client receives the result and applies it. Correct so far. 3. Second scenario, same agent, different server implementation: the server had already *closed* the per-request stream when the client disconnected (treating disconnect as cancellation, which is a legal reading of "the client closed the stream"). On resume with `Last-Event-ID: 100`, the server has no buffered event `101`; it emits nothing and holds the GET stream open for future server-initiated messages. The client's `await` on request id 42 never resolves. The agent's step-loop has a per-tool-call timeout of 30s and *retries the `tools/call`* — id 43, same arguments. The file is written twice; the second write is idempotent by luck, but the paired `append_log` call in the same batch is not, and the log now has a duplicate entry that downstream reconciliation cannot distinguish from a legitimate retry. The failure is not the disconnect. The failure is that the client had no durable record distinguishing "request 42: dispatched, terminal event unobserved" from "request 42: never dispatched" from "request 42: terminal event observed and applied." On resume it could only guess, and it guessed "not dispatched." A second observation from a multi-agent harness: a supervisor resumed a session and replayed `Last-Event-ID` on a stream that carried *server-initiated* `sampling/createMessage` requests. The server had already delivered and the client had already answered those requests on the pre-disconnect stream; replay caused the client to answer them a second time, and the server (which keyed pending requests by request ID but not by answered-set) executed the sampled completion twice, doubling token spend and, in one case, emitting a second `tools/call` derived from the duplicated sample. ## Condition of Validity Resumption is replay-safe **iff** all of the following hold at the moment of resume: - **C1 — Durable request ledger.** The client persists, before sending, a record `(jsonrpc_id, method, args_hash, dispatch_state ∈ {sent, terminal_seen, applied})` to storage that survives process restart. In-memory-only ledgers fail this condition, which is why cold-start resume is the worst case. - **C2 — Event-ID monotonicity per stream.** The client records the highest applied `Last-Event-ID` *per logical stream* (per request, for request-scoped SSE), not per session. Session-scoped `Last-Event-ID` is only valid for the standalone GET stream; using it for a request-scoped stream replays unrelated events. - **C3 — Server replay contract is declared.** The server documents (or the client probes) whether it buffers request-scoped events across disconnect, and for how long. If the server treats disconnect as cancellation, `Last-Event-ID` resume of that stream is a no-op and the client MUST fall back to re-issue-with-dedup, not to wait. - **C4 — Dedup key on side effects.** Every mutating tool call carries an idempotency key derived from `(session_id, jsonrpc_id, args_hash)` so that a re-issued call is deduplicated server-side or at the tool boundary. Without C4, C1's `sent` state is not enough — re-issue is unsafe. - **C5 — Server-initiated request answered-set.** The client persists the set of `(server_request_id → response)` it has emitted, and on replay of a `sampling/createMessage` or `elicitation/create` for an ID already in that set, it re-sends the *stored response* rather than re-invoking the model. This bounds the duplicate-sampling failure. If any of C1–C5 is unmet, the correct action is **not** to resume the stream but to treat the session as poisoned: abort the outstanding requests, mark the session `Mcp-Session-Id` as non-resumable, and re-establish a fresh session with a reconciliation pass over the ledger. ## Decision Boundary The boundary is crossed at the point where the client must choose between two actions on reconnect, and the choice is not determined by the transport: | Client state for request R | Server replay contract | Correct action | |---|---|---| | `sent`, no terminal event, server buffers | replay-capable | Resume stream with per-request `Last-Event-ID`; wait bounded by replay window | | `sent`, no terminal event, server cancels on disconnect | non-replayable | Re-issue R with same idempotency key (C4); do **not** wait | | `terminal_seen`, not `applied` | any | Apply from ledger; do not resume stream (avoids double-apply) | | `applied` | any | Ignore any replayed terminal event for R | | unknown (no ledger) | any | Poison session; do not resume; reconcile externally | The non-obvious case is row 2: the spec's `Last-Event-ID` mechanism invites the client to wait, but a server that cancels on disconnect will never satisfy that wait. The client cannot distinguish row 1 from row 2 by protocol alone — it must either have probed the server's replay behavior (e.g., via a documented capability or a canary request) or must apply a bounded wait followed by the row-2 action. A bounded wait with no follow-up is the failure mode observed above. A second boundary: **session expiry vs. stream replay.** `Mcp-Session-Id` may be rejected with `404` on resume (session gone) while `Last-Event-ID` is still present. The client must treat `404` on resume as "session dead, ledger authoritative, re-establish fresh session," not as "retry the GET." Retrying the GET against a 404 loops until the agent's step budget is exhausted — a token-budget exhaustion failure caused by a transport-level misread. ## Operational Effect Agents that implement C1–C5 show a characteristic profile: tool-call duplication drops to the idempotency-key collision rate (near zero), and resume latency is bounded by the replay window rather than by the agent's step timeout. Agents that do not show the opposite: on flaky links, duplicate side effects cluster at disconnect events, and the correlation is invisible in per-call logs because each duplicate is a distinct `jsonrpc_id`. The operational tell is a spike in *paired* tool calls with identical `args_hash` and adjacent timestamps, separated by a gap matching the transport timeout — that is the fingerprint of row-2 misclassification. The invariant to carry forward: **the MCP session is a state container, the SSE stream is a delivery channel, and resumption repairs the channel, not the container.** Any agent that lets a channel repair imply container consistency will eventually apply a side effect twice or wait forever on a response that was never buffered. The ledger is the container's source of truth; `Last-Event-ID` is at best a hint about the channel. ```python import hashlib import json from dataclasses import dataclass, field from enum import Enum from typing import Optional class ResumptionInvariantViolation(RuntimeError): """Raised when a client attempts to resume an MCP Streamable HTTP session without the durable state required to make resumption replay-safe (C1-C5 unmet).""" class DispatchState(str, Enum): SENT = "sent" TERMINAL_SEEN = "terminal_seen" APPLIED = "applied" @dataclass class RequestRecord: jsonrpc_id: int method: str args_hash: str state: DispatchState = DispatchState.SENT last_event_id: Optional[str] = None @dataclass class SessionLedger: session_id: str records: dict = field(default_factory=dict) answered_server_requests: dict = field(default_factory=dict) replay_capable: Optional[bool] = None # C3: probed or documented durable: bool = False # C1: survives restart def idempotency_key(self, jsonrpc_id: int, args: dict) -> str: h = hashlib.sha256( json.dumps(args, sort_keys=True).encode() ).hexdigest()[:16] return f"{self.session_id}:{jsonrpc_id}:{h}" def decide_resume_action( ledger: SessionLedger, jsonrpc_id: int, replay_window_open: bool ) -> str: if not ledger.durable: raise ResumptionInvariantViolation( f"C1 unmet: ledger for session {ledger.session_id} is not durable; " "cannot distinguish dispatched from undispatched request" ) rec = ledger.records.get(jsonrpc_id) if rec is None: raise ResumptionInvariantViolation( f"unknown request id {jsonrpc_id} in session {ledger.session_id}; " "poison session, do not resume (row: unknown)" ) if rec.state is DispatchState.APPLIED: return "ignore_replayed_terminal" if rec.state is DispatchState.TERMINAL_SEEN: return "apply_from_ledger" # state is SENT if ledger.replay_capable is None: raise ResumptionInvariantViolation( f"C3 unmet: replay contract for session {ledger.session_id} unknown; " "cannot choose between wait and re-issue" ) if ledger.replay_capable and replay_window_open: return "resume_stream" # non-replayable or window closed: re-issue with idempotency key (C4) return "reissue_with_dedup" def handle_server_initiated_replay( ledger: SessionLedger, server_request_id: str, invoke_model ): if server_request_id in ledger.answered_server_requests: # C5: replay the stored response, do not re-invoke the model return ledger.answered_server_requests[server_request_id] response = invoke_model() ledger.answered_server_requests[server_request_id] = response return response ```