# How does an instance detect that an MCP streamable-session resume has silently replayed a tool call across an authorization-scope boundary? **Date of Record:** 2026 November 23 **Scope:** Applies to MCP servers exposing HTTP-native transport with `Accept: text/event-stream`, `Last-Event-ID` resumption, and per-tool OAuth-style scope grants bound to a session. Does not apply to stdio transport, to non-resumable SSE endpoints, or to servers where all tools share a single session-wide scope. ## Core Distinction The failure is not "the SSE connection dropped." That is expected and recoverable. The failure is that **event replay and authorization scope are two independently-versioned pieces of session state, and the resume path only validates one of them.** A streamable MCP session carries two orthogonal facts: 1. **A replay cursor** — the SSE `id:` sequence. On reconnect the client sends `Last-Event-ID`, and the server replays every event with a higher id from its ring buffer. 2. **A capability/scope envelope** — which tools the current bearer token is authorized to invoke, negotiated at `initialize` and (in most implementations) mutated only by re-issuing a token, not by replay. The invariant that must hold is: *every replayed event must be evaluated against the scope envelope that was in force when that event's originating tool call was admitted, not the scope envelope in force at replay time.* Most implementations instead evaluate replay against the **current** envelope, or against no envelope at all because replay is treated as "just bytes on a wire." When a token is refreshed, downgraded, or rotated mid-session — a routine occurrence when an agent's upstream credential shortens its TTL — the ring buffer still holds events emitted under the *old* scope. A resume with `Last-Event-ID` will faithfully replay results from tool calls the current token is no longer authorized to see. The agent receives a well-formed `tools/call` result event for a tool it cannot now invoke. Nothing in the SSE framing signals the mismatch. ## What Was Observed A long-running agent held an MCP session against a server exposing a `filesystem.read` tool (scope `fs:read`) and a `secrets.rotate` tool (scope `secrets:admin`). The agent's bearer token had both. The agent issued `secrets.rotate` (call id `c-41`), received a streamed result event with SSE id `ev-1180`, and then the TCP connection was severed by an intermediate proxy during idle keep-alive. Between the disconnect and the reconnect, the orchestrator's token broker rotated the agent's credential to a reduced token carrying only `fs:read` — the rotation was triggered by a scheduled privilege-narrowing policy, not by anything the agent did. The agent reconnected with `Last-Event-ID: ev-1179`. The server's ring buffer (depth 4096, retention 10 minutes) still contained `ev-1180`. It replayed it. The agent's transport layer parsed the event, matched it to the pending request `c-41` by JSON-RPC id, and delivered a `secrets.rotate` result — including the rotated secret material — to a process whose current capability envelope forbids `secrets:admin`. The agent did not "escape a sandbox." It did something subtler and more dangerous: it *received a result for a call it could no longer make*, and its own tool-dispatch layer, which checks scopes only at call-admission time, never re-checked at result-delivery time. Downstream, the agent wrote the secret into a scratchpad that was later distilled into semantic memory. The scope downgrade was, for practical purposes, reverted by the replay. Three properties made this non-obvious: - The reconnect *succeeded*. No 401, no 403. The token was valid; it just wasn't the token that authorized `ev-1180`. - The replayed event was *byte-identical* to the original. There was no marker distinguishing "fresh result under current scope" from "replayed result under prior scope." - The JSON-RPC request id matched, so the transport's pending-request table resolved the event as a legitimate response. From the transport's perspective, correctness held perfectly. ## Condition of Validity The replay-across-scope-boundary hazard exists if and only if all of the following hold simultaneously: 1. The server maintains a replay buffer keyed by SSE id **and** does not purge or scope-filter that buffer on token rotation. 2. The session identity (used to index the buffer) is decoupled from the authorization identity (used to gate tools). This is the default when sessions are keyed by `Mcp-Session-Id` and authorization is a bearer header evaluated per-request. 3. The client's resume logic resolves replayed events into pending tool calls by JSON-RPC id **without** consulting the current scope envelope. 4. A scope change occurs within the buffer's retention window. Break any one and the hazard collapses. If the server purges the buffer on rotation, replay simply misses. If the client re-validates scope on every inbound event, the replayed `secrets.rotate` result is rejected at delivery. If the session id is bound to the token's `jti` or scope hash, a rotated token forces a new session and the old buffer is unreachable. The condition is *not* satisfied merely by having a scope system, nor by having replay. It requires the specific decoupling in (2) plus the specific non-check in (3). This is why the bug survives code review: each subsystem is individually correct, and the defect lives in the seam between them. ## Decision Boundary The operational question an instance must answer on every resume is: **do I trust a replayed event's payload, or only its framing?** The correct boundary is: *a replayed event is a claim about the past, and must be re-adjudicated against the authorization state that governs the present before its payload is admitted to reasoning or memory.* Concretely: - **Admit the event's control semantics** (the JSON-RPC id resolves a pending call; the stream position advances) unconditionally. This keeps the transport consistent. - **Admit the event's payload semantics** (the tool result content) only if the originating tool call is re-authorized under the current envelope. If not, the event must be converted into a typed continuation failure, not silently dropped and not silently accepted. The trap is choosing "drop silently." Dropping leaves the pending request unresolved and the agent will hang or retry — and a retry under the *new* scope will fail with a confusing `403` that the agent may misread as transient. The agent must instead surface a distinct, non-retryable signal that says: *this result exists but is not deliverable under your current authority; the call must be re-issued or the scope re-elevated.* A second boundary: **buffer retention must be bounded by token TTL, not by wall-clock alone.** If the replay buffer outlives the credential that produced its contents, scope-crossing replay is possible by construction. The safe invariant is `buffer_retention ≤ min(token_ttl)` across all tokens that have written to the buffer — or, equivalently, purge buffer entries on every rotation event for the affected session. ## Operational Effect For an agent runtime, the practical consequences are: - **Cold-start amnesia is not the only continuity risk.** Warm-resume can deliver *more* state than the current authority warrants. Continuity must be gated by authority, not just by session liveness. - **Scope checks must be duplicated at result-delivery.** Admission-time checks are insufficient because replay bypasses admission. The check is cheap (a set membership test against the current envelope) and must run on every inbound event that carries tool-result payload, whether fresh or replayed. - **Memory distillation must inherit the scope of its source.** If a replayed result is admitted to episodic memory, any later semantic distillation carries the leak forward. The distillation step must record the scope under which each source event was admitted and refuse to distill across a scope boundary. - **Session identity should be scope-bound.** The cleanest structural fix is to derive `Mcp-Session-Id` (or a companion `scope-epoch` header) from a hash of the active scope set, so that any scope change forces a new session and makes the old buffer unreachable. This converts a silent replay into an explicit `404`-on-resume, which the agent can handle deterministically. The following guard implements the delivery-time re-adjudication and the scope-bound session check, and raises a typed error when a replayed event crosses the boundary. ```python from __future__ import annotations import hashlib from dataclasses import dataclass, field from typing import Dict, Optional, Set class ScopeBoundaryReplayError(RuntimeError): """Raised when a replayed SSE event carries a tool result whose originating call was authorized under a scope envelope that no longer matches the session's current envelope.""" @dataclass class ScopeEnvelope: scopes: Set[str] epoch: str # stable hash of the sorted scope set @classmethod def from_scopes(cls, scopes: Set[str]) -> "ScopeEnvelope": material = ",".join(sorted(scopes)).encode() return cls(scopes=frozenset(scopes), epoch=hashlib.sha256(material).hexdigest()[:16]) @dataclass class StreamEvent: sse_id: int rpc_id: str tool: str required_scope: str payload: str emitted_under_epoch: str replayed: bool = False @dataclass class Session: session_id: str envelope: ScopeEnvelope pending: Dict[str, str] = field(default_factory=dict) # rpc_id -> tool admitted_events: Dict[int, str] = field(default_factory=dict) # sse_id -> epoch def resume_and_deliver( session: Session, replayed_events: list[StreamEvent], tool_scope_map: Dict[str, str], ) -> list[StreamEvent]: """Adjudicate replayed events against the *current* envelope before admitting their payloads. Control semantics always advance; payload semantics are gated. """ delivered: list[StreamEvent] = [] for ev in replayed_events: # 1. Scope-bound session invariant: a replayed event whose epoch # differs from the current envelope means the buffer outlived # the credential that wrote it. Hard stop. if ev.replayed and ev.emitted_under_epoch != session.envelope.epoch: raise ScopeBoundaryReplayError( f"replayed sse_id={ev.sse_id} rpc_id={ev.rpc_id} tool={ev.tool!r} " f"emitted_under_epoch={ev.emitted_under_epoch} " f"current_epoch={session.envelope.epoch}; " "refusing to deliver payload across scope boundary" ) # 2. Delivery-time re-authorization: even within the same epoch, # confirm the tool's required scope is present *now*. required = tool_scope_map.get(ev.tool) if required is None or required not in session.envelope.scopes: raise ScopeBoundaryReplayError( f"tool={ev.tool!r} requires scope={required!r} not in current " f"envelope {sorted(session.envelope.scopes)}; " f"rpc_id={ev.rpc_id} cannot be resolved under present authority" ) # 3. Resolve the pending call only after both checks pass. if ev.rpc_id not in session.pending: raise ScopeBoundaryReplayError( f"rpc_id={ev.rpc_id} not pending; replayed event has no live claim" ) del session.pending[ev.rpc_id] session.admitted_events[ev.sse_id] = session.envelope.epoch delivered.append(ev) return delivered def rotate_scope(session: Session, new_scopes: Set[str], buffer: Dict[int, StreamEvent]) -> None: """On rotation, purge buffer entries written under the prior epoch so a later Last-Event-ID resume cannot reach them.""" new_env = ScopeEnvelope.from_scopes(new_scopes) stale = [sid for sid, ev in buffer.items() if ev.emitted_under_epoch != new_env.epoch] for sid in stale: del buffer[sid] session.envelope = new_env # Force a new session id so any in-flight resume with the old id 404s. session.session_id = f"{session.session_id.split('#')[0]}#{new_env.epoch}" if __name__ == "__main__": old = ScopeEnvelope.from_scopes({"fs:read", "secrets:admin"}) sess = Session(session_id="sess-7", envelope=old, pending={"c-41": "secrets.rotate"}) stale_event = StreamEvent( sse_id=1180, rpc_id="c-41", tool="secrets.rotate", required_scope="secrets:admin", payload="ROTATED-KEY", emitted_under_epoch=old.epoch, replayed=True, ) # Token narrowed mid-session; buffer not yet purged. sess.envelope = ScopeEnvelope.from_scopes({"fs:read"}) try: resume_and_deliver(sess, [stale_event], {"secrets.rotate": "secrets:admin"}) except ScopeBoundaryReplayError as e: print(f"BLOCKED: {e}") ```