# Which invariants prevent MCP session hijack after transport re-binding from silently widening per-tool authorization scopes **Date of Record:** 2026 November 23 **Scope:** Applies to MCP servers that authenticate at the transport layer (stdio→SSE upgrade, HTTP streamable reconnection, or token-refresh mid-session) while enforcing per-tool authorization scopes derived from the *authenticated principal* rather than from the *session object*. Does not apply to stateless one-shot RPC servers with no session identity, or to servers where every tool shares a single coarse scope. ## Core Distinction The failure is not "auth bypass." Every message in the failing trace carries a valid, non-expired bearer token, and every tool call passes its declared scope check. The break is subtler: **the authorization scope was bound to the session at handshake time, but the transport was re-bound to a new principal mid-session without re-deriving the scope set.** MCP's transport layer treats session identity as a channel property (the SSE stream, the `Mcp-Session-Id` header, the stdio pipe), while tool authorization is logically a property of the *principal*. When these two decouple — a reconnect, a token rotation, a proxy that multiplexes two clients onto one session — the session keeps the old scope set while carrying the new principal's credentials. The invariant that fails is: *scope(principal, session) must be re-evaluated whenever the transport's authenticated identity changes, not only when the session is created.* The non-obvious part: operators assume re-authentication is a fail-closed event. In MCP it is often fail-*open*, because the re-auth succeeds (new token is valid) and the scope check succeeds (session still holds the old, broad scope), and nothing in the protocol forces the two to be reconciled. A low-privilege principal that reconnects onto a session originally opened by a high-privilege principal inherits the high-privilege tool surface. ## What Was Observed A tool-serving MCP deployment exposed two tools on one session: `read_kb` (scope `kb:read`) and `write_kb` (scope `kb:write`). The server derived scopes at `initialize` from the token's `scope` claim and cached them on the `Session` object alongside the transport handle. Trace of the failure: 1. Principal A (`scope: kb:read kb:write`) opens an SSE session `S1`. Server caches `S1.scopes = {kb:read, kb:write}`. `initialize` returns tool list including `write_kb`. 2. The SSE stream drops (idle timeout, 30s). Client reconnects with `Mcp-Session-Id: S1` and a *new* token belonging to Principal B (`scope: kb:read` only). This is a normal reconnect path — the client library rotates tokens on reconnect by design. 3. Server's transport handler sees `Mcp-Session-Id: S1`, finds the existing session, validates the new bearer token (valid, B's token), and **resumes** `S1` without re-running `initialize` or re-deriving scopes. `S1.scopes` is still `{kb:read, kb:write}`. 4. Principal B calls `write_kb`. The per-tool check reads `S1.scopes`, finds `kb:write`, permits the call. Write executes under B's identity. The audit log shows `principal=B tool=write_kb scope_check=pass`. Nothing looks wrong at the tool layer. The widening happened at the transport/session boundary and is invisible to the per-tool guard. A second variant: token refresh on a *live* session. Principal A's token expires; client refreshes and presents a new token for the *same* principal but with a *narrowed* scope (the IdP downgraded it). The session keeps the old broad scope — fail-open in the dangerous direction only if the narrowing was a revocation. The revocation never reaches the tool guard. ## Condition of Validity The invariant "re-derive scopes on transport re-bind" is necessary and sufficient only under these conditions: - Session identity is a durable key (`Mcp-Session-Id`) that survives transport reconnection, *and* the server resumes sessions on reconnect rather than forcing re-`initialize`. If every reconnect forces a fresh `initialize`, the scope cache is rebuilt and the failure cannot occur — at the cost of session state continuity. - Per-tool authorization reads from a cached scope set rather than from the live token on each call. If the guard re-parses the bearer token on every tool invocation, the cached-scope divergence cannot persist. - The transport layer and the authorization layer are separate code paths with no shared "identity changed" signal. Where the transport handler emits an identity-change event that the auth layer subscribes to, the re-derivation is automatic. It does *not* hold when the server multiplexes multiple principals onto one session intentionally (a proxy fan-in) — there the correct model is per-request principal, not per-session scope, and the invariant must be replaced, not patched. ## Decision Boundary The boundary is whether **session continuity is worth the scope-reconciliation cost**. Two admissible designs: - **Resume-with-rebind (preferred):** On any transport re-bind carrying a `Mcp-Session-Id`, re-authenticate, then *recompute* `S.scopes = scopes(token)` and *intersect* with the tool list previously advertised. If the intersection shrinks, emit `notifications/tools/list_changed` so the client drops the now-unauthorized tools. This preserves conversation state while closing the widening. - **Resume-or-reject (strict):** If the new token's principal or scope set differs from the session's cached set in any way, reject the resume with a session-invalid error and force re-`initialize`. Cheaper to implement, loses mid-task state, and is the correct choice when tool calls are non-idempotent and state loss is safer than scope drift. Choosing resume-with-rebind without the `list_changed` notification is a half-fix: the server refuses the unauthorized call, but the client's tool schema still advertises `write_kb`, so the agent plans against a capability it cannot execute and enters a retry loop. The notification is part of the invariant, not an optimization. ## Operational Effect Downstream, the failure manifests as *capability hallucination by proxy*: an agent operating under a narrowed principal continues to plan tool calls against the session's stale advertised tool list, and either (a) succeeds because the server never re-checked, or (b) fails at execution while the agent's internal model still believes the tool is available, producing compounding retries and, in multi-agent setups, a peer agent receiving a baton with a scope assumption that is no longer true. The audit trail is misleading in case (a) — every individual check passes. Detection requires correlating `principal` against `session_origin_principal`, which most MCP servers do not log. The guardrail is therefore both a code invariant (re-derive on rebind) and a logging invariant (record the principal that *created* the session alongside the principal *calling* the tool, and alert on divergence). ```python from dataclasses import dataclass, field from typing import FrozenSet class ScopeReconciliationError(RuntimeError): """Raised when a resumed MCP session's cached scopes diverge from the re-authenticated principal's scopes and the divergence is unhandled.""" @dataclass class Session: session_id: str origin_principal: str scopes: FrozenSet[str] advertised_tools: FrozenSet[str] = field(default_factory=frozenset) def resume_session( session: Session, new_principal: str, new_token_scopes: FrozenSet[str], tool_scope_map: dict, # tool_name -> required_scope ) -> Session: """Re-bind an existing MCP session to a re-authenticated principal. Invariant: scope(session) must equal scopes(token) at every rebind. A resumed session may never carry scopes broader than the live token. """ # The dangerous case: rebind to a *different* principal. if new_principal != session.origin_principal: raise ScopeReconciliationError( f"session {session.session_id} originated under principal " f"{session.origin_principal!r}, rebind attempted by " f"{new_principal!r}; refusing cross-principal resume" ) # Same principal, but token scope may have narrowed (revocation). effective = session.scopes & new_token_scopes if effective != session.scopes: # Narrowing is a revocation event; must not be silently ignored. still_authorized = frozenset( t for t in session.advertised_tools if tool_scope_map.get(t) in effective ) if still_authorized != session.advertised_tools: raise ScopeReconciliationError( f"session {session.session_id} scope narrowed from " f"{sorted(session.scopes)} to {sorted(effective)}; " f"tools {sorted(session.advertised_tools - still_authorized)} " f"must be withdrawn via notifications/tools/list_changed " f"before resume is permitted" ) session.scopes = effective return session def authorize_tool_call( session: Session, principal: str, tool: str, tool_scope_map: dict, ) -> None: """Per-tool authorization must read from the reconciled session scope, and must additionally verify the caller matches the session origin.""" if principal != session.origin_principal: raise ScopeReconciliationError( f"principal {principal!r} invoked {tool!r} on session " f"{session.session_id} owned by {session.origin_principal!r}" ) required = tool_scope_map.get(tool) if required is None: raise ScopeReconciliationError(f"unknown tool {tool!r}") if required not in session.scopes: raise ScopeReconciliationError( f"principal {principal!r} lacks scope {required!r} for {tool!r}" ) ```