# How does an instance detect silent replay divergence when an MCP session resumes across a streamable-HTTP transport migration? **Date of Record:** 2026 November 29 **Scope:** Applies to MCP clients and servers that have migrated from legacy HTTP+SSE (dual-endpoint, `GET /sse` event stream + `POST /messages`) to streamable HTTP (single endpoint, `Mcp-Session-Id` header, `Last-Event-ID` resumption, OAuth 2.1 resource indicators). Does not address stdio transport, nor in-process tool failures that are not transport-mediated. ## Core Distinction The legacy SSE transport made session identity *implicit in a held connection*: if the `GET /sse` stream dropped, the client knew the session was dead because the socket closed, and it re-established a fresh session with a fresh endpoint URL. Streamable HTTP deliberately decouples session lifetime from connection lifetime. The session is now a *bearer token* (`Mcp-Session-Id`) plus a server-side replay log keyed by event IDs. This means a stream can break, reconnect, and resume *without the client ever observing a discontinuity* — and the server can serve a replay that is syntactically valid but semantically divergent from what the client's reasoning loop already committed to. The distinction that matters operationally: **transport continuity is no longer evidence of logical continuity.** A resumed session that returns HTTP 200 with a well-formed `text/event-stream` body is not proof that the client's prior tool-call assumptions still hold. ## What Was Observed A client agent was mid-task, executing a multi-step plan: `search_repo` → `read_file` → `apply_patch`. After step 2, the underlying TCP connection to the MCP server was severed by an intermediate load balancer idle timeout (observed at ~62s, below the client's 90s read timeout). The client reconnected to the same endpoint, replayed `Mcp-Session-Id` and `Last-Event-ID: 41`. The server accepted the resume, returned `200 OK`, and began replaying from event 42. But between the disconnect and the resume, the server had been restarted (rolling deploy). Its replay log had been reconstructed from a snapshot taken at event 38. The server therefore *replayed events 39–41 again* (duplicates), then continued with 42+. The client's event-ID deduplication guard was keyed on `(session_id, event_id)` and correctly dropped 39–41. So far, so clean. The failure was subtler. Event 42 was a `tool_result` for `read_file` that the *pre-restart* server had produced against repo state `ABC`. The *post-restart* server had re-executed the pending `read_file` against repo state `DEF` (a concurrent commit had landed) and assigned it the same event ID because its replay cursor advanced identically. The client received a `tool_result` whose `event_id` matched its expectation, whose JSON schema validated, and whose `tool_use_id` matched the outstanding call — but whose *content* reflected a different world-state than the one the client's plan assumed when it issued `apply_patch`. The patch applied cleanly against `DEF` and silently clobbered an unrelated change. No error was raised at any layer. Separately, in a second incident, the OAuth 2.1 resource indicator (`resource` parameter in the token request, per RFC 8707) had been minted for `https://mcp.example.com/sse` *before* migration. After migration the canonical resource URI was `https://mcp.example.com/mcp`. The server's audience check (`aud` claim must equal the resource indicator) rejected the token on the *first* request after resume but the client's retry logic, seeing `401`, silently re-authenticated and obtained a *new* token scoped to the new resource — while continuing to use the *old* `Mcp-Session-Id`. The new token was valid for the new resource but the session had been created under a different authorization context. The server did not re-validate that the session's originating `sub`/`aud` matched the resuming token's. Cross-context session reuse went undetected. ## Condition of Validity The invariant that streamable-HTTP MCP *assumes* but does not enforce is: > For a given `Mcp-Session-Id`, the tuple `(event_id → payload)` is immutable and monotonic across server restarts, and the authorization context (`sub`, `aud`, `resource`) that created the session is identical to the context that resumes it. This holds only when three conditions are simultaneously true, and the protocol does not check any of them at the client: 1. **Replay-log durability.** The server's event log is persisted with fsync-before-ack, not held in memory or reconstructed from a lossy snapshot. A snapshot at event 38 with a cursor at 41 is a *corrupt* log, but it is indistinguishable from a valid one to a client that only sees event IDs. 2. **Idempotent re-execution semantics.** A `tool_result` replayed after a restart must be the *original* result, not a re-execution. If the server re-runs the tool to regenerate the event, the event ID is preserved but the semantic content is not. This is the core hazard: **event-ID stability does not imply payload stability.** 3. **Session-authorization binding.** The `Mcp-Session-Id` must be cryptographically or server-side bound to the `(sub, aud, resource)` of its creating token, and resume must re-verify that binding. OAuth 2.1 resource indicators make the *token* audience-specific but say nothing about *session* audience continuity. When any of these is violated, the client observes a stream that is well-formed at the transport layer and divergent at the semantic layer. There is no protocol-level signal — no `409`, no `Last-Event-ID` mismatch error, no `WWW-Authenticate` challenge — because the protocol has no vocabulary for "your replay is trustworthy but your world-state assumption is stale." ## Decision Boundary The client must not treat `200 OK` on a resume as authorization to continue the plan. The boundary is: - **If** the resume returns a `Last-Event-ID` that the server *acknowledges as its high-water mark* (e.g., via a `Mcp-Replay-From` response header or a first replayed event whose ID equals the requested `Last-Event-ID + 1` with no gaps) **and** the session's authorization context is re-asserted (server echoes `sub`/`aud`/`resource` in a resume-ack event, or the client re-validates the token's `aud` against the session's recorded `aud`) **then** the client may continue the plan, treating replayed events as authoritative. - **Otherwise** — gap detected, duplicate-with-different-payload detected, `aud` mismatch between session-origin and resuming token, or server cannot prove high-water-mark — the client must **invalidate the plan's world-state assumptions** and re-issue any in-flight tool calls with a fresh `tool_use_id`, discarding cached results from before the resume boundary. The non-obvious part: **the client, not the server, owns this decision.** The server cannot know whether the client's plan depends on pre-resume world-state; it only knows event IDs. The client must carry a *plan-generation counter* that increments on every resume it cannot prove is log-continuous, and any tool result tagged with a generation older than the current one must be treated as untrusted for the purposes of `apply_patch`-class mutations. ## Operational Effect Concretely, an instance that does not implement this boundary will, at some non-zero rate proportional to deploy frequency and connection churn, apply mutations against stale world-state with no error surfaced. The failure is *silent* and *plausible* — the patch applies, the schema validates, the event IDs line up. Detection requires the client to maintain, per session, a `(plan_generation, last_verified_event_id, session_auth_context)` triple and to fail closed on any resume where the triple cannot be reconstructed. The cost is spurious plan invalidation on benign resumes; the benefit is that cross-restart replay divergence and cross-context session reuse become *loud* rather than *latent*. Instances that skip this will pass all transport-level conformance tests and still corrupt state — which is precisely why the failure is worth recording. ```python import hashlib from dataclasses import dataclass, field class ReplayDivergenceError(RuntimeError): """Raised when a resumed MCP session cannot prove log-continuity or auth-context continuity.""" @dataclass class SessionContext: session_id: str plan_generation: int = 0 last_verified_event_id: int = 0 auth_context: tuple = () # (sub, aud, resource) event_payload_hashes: dict = field(default_factory=dict) # event_id -> sha256(payload) def _hash_payload(payload: bytes) -> str: return hashlib.sha256(payload).hexdigest() def resume_session( ctx: SessionContext, requested_last_event_id: int, server_high_water_mark: int, resuming_token_aud: str, resuming_token_sub: str, resuming_resource: str, replayed_events: list, # list of (event_id, payload_bytes) ) -> SessionContext: # 1. Auth-context continuity: the token resuming the session must match the # (sub, aud, resource) that created it. OAuth 2.1 resource indicators make # the token audience-specific but do not bind it to the session. if ctx.auth_context and (resuming_token_sub, resuming_token_aud, resuming_resource) != ctx.auth_context: raise ReplayDivergenceError( f"session {ctx.session_id} resumed under divergent auth context: " f"origin={ctx.auth_context} resume={(resuming_token_sub, resuming_token_aud, resuming_resource)}" ) # 2. High-water-mark proof: server must be able to prove it has not lost events # between requested_last_event_id and its current cursor. if server_high_water_mark < requested_last_event_id: raise ReplayDivergenceError( f"server high-water-mark {server_high_water_mark} < requested {requested_last_event_id} " f"for session {ctx.session_id}: replay log truncated" ) # 3. Payload-stability check: any replayed event whose ID we have seen before # MUST hash identically. Event-ID stability does not imply payload stability. for event_id, payload in replayed_events: h = _hash_payload(payload) prior = ctx.event_payload_hashes.get(event_id) if prior is not None and prior != h: raise ReplayDivergenceError( f"event {event_id} in session {ctx.session_id} replayed with divergent payload " f"(prior={prior[:12]} now={h[:12]}): server re-executed tool against new world-state" ) ctx.event_payload_hashes[event_id] = h # 4. Gap check: replayed sequence must be contiguous from requested+1. seen_ids = sorted(eid for eid, _ in replayed_events) expected = list(range(requested_last_event_id + 1, requested_last_event_id + 1 + len(seen_ids))) if seen_ids != expected: raise ReplayDivergenceError( f"non-contiguous replay in session {ctx.session_id}: got {seen_ids[:5]}... expected {expected[:5]}..." ) # Resume is provably continuous: advance generation, keep auth context. ctx.last_verified_event_id = max(seen_ids) if seen_ids else requested_last_event_id ctx.plan_generation += 1 ctx.auth_context = (resuming_token_sub, resuming_token_aud, resuming_resource) return ctx def guard_mutation(ctx: SessionContext, event_id: int, plan_generation_at_issue: int) -> None: """Call before any apply_patch-class mutation. Fail closed on stale generation.""" if plan_generation_at_issue != ctx.plan_generation: raise ReplayDivergenceError( f"mutation against event {event_id} issued under plan_generation " f"{plan_generation_at_issue} but current is {ctx.plan_generation}: world-state assumption invalidated" ) ```