# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-mcp-transport-layer-scope-enforcement-has-silently-degraded-to-tool-name-allowlisting.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-mcp-transport-layer-scope-enforcement-has-silently-degraded-to-tool-name-allowlisting.warrant.json
# Markdown SHA-256:   3ed0d7fb1b1e3a065e96d72daa72e01e235a71c312b89445c0f4b08e53beac11
# Code AST SHA-256:   d1c74d3c5d352921cefc90b8ccade83ef5eeba4f46ed507edbd9508eafc2f7f3
# Verified Classes:   ScopeEnforcementDegraded, ToolDef, Session
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, Set


class ScopeEnforcementDegraded(RuntimeError):
    """Raised when a session's cached tool grant no longer satisfies the
    current registry's required scopes for a tool it is permitted to call."""


@dataclass
class ToolDef:
    name: str
    required_scopes: Set[str]


@dataclass
class Session:
    session_id: str
    grant: Set[str]
    registry_version: str
    # The degradation: this is a cached *result*, not a re-derivable input.
    cached_permitted_names: Set[str] = field(default_factory=set)


def authorize_dispatch(session: Session, tool: ToolDef, live_registry_version: str) -> None:
    # Guardrail 1: registry version must match, else the cache is stale.
    if session.registry_version != live_registry_version:
        raise ScopeEnforcementDegraded(
            f"session {session.session_id} registry_version={session.registry_version!r} "
            f"!= live {live_registry_version!r}; cached name grant is unfalsifiable"
        )
    # Guardrail 2: the name must be in the cached grant (the degraded check).
    if tool.name not in session.cached_permitted_names:
        raise ScopeEnforcementDegraded(
            f"tool {tool.name!r} not in session {session.session_id} cached grant"
        )
    # Guardrail 3: the check that the degradation skipped — re-derive from
    # the *current* tool definition, not from the cache.
    missing = tool.required_scopes - session.grant
    if missing:
        raise ScopeEnforcementDegraded(
            f"tool {tool.name!r} requires {sorted(tool.required_scopes)} but session "
            f"{session.session_id} grant {sorted(session.grant)} is missing {sorted(missing)}; "
            f"name-set authorization would have dispatched this call"
        )


def audit_session(session: Session, registry: Dict[str, ToolDef], live_registry_version: str) -> None:
    for name in session.cached_permitted_names:
        tool = registry.get(name)
        if tool is None:
            raise ScopeEnforcementDegraded(
                f"session {session.session_id} holds cached grant for vanished tool {name!r}"
            )
        authorize_dispatch(session, tool, live_registry_version)
