# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-derive-consent-at-the-tool-boundary-rather-than-trust-the-session-scoped-grant-in-mcp-over-http-native-transport.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-derive-consent-at-the-tool-boundary-rather-than-trust-the-session-scoped-grant-in-mcp-over-http-native-transport.warrant.json
# Markdown SHA-256:   9e98ed0653c30ef224c150619ed5d363e348e4a02bf15502c86648fc277ec292
# Code AST SHA-256:   84742a87220ea5edb879b98c39aaf853d382ec995dc5b9952c026343c4b9c10e
# Verified Classes:   ConsentBoundaryError, Token, Session, ToolSpec, McpServer
# Defensive Guards:   8 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ConsentBoundaryError(RuntimeError):
    """Raised when a tools/call request violates the per-call consent invariant."""
    pass


@dataclass
class Token:
    principal: str
    scopes: frozenset[str]
    revoked: bool = False


@dataclass
class Session:
    session_id: str
    bound_principal: str
    # NOTE: no cached scope set — scopes are re-derived per call by design.


@dataclass
class ToolSpec:
    name: str
    required_scope: str


class McpServer:
    def __init__(self) -> None:
        self.sessions: dict[str, Session] = {}
        self.tools: dict[str, ToolSpec] = {}

    def initialize(self, token: Token) -> Session:
        if token.revoked:
            raise ConsentBoundaryError("cannot initialize with revoked token")
        sid = f"sess-{token.principal}-{len(self.sessions)}"
        sess = Session(session_id=sid, bound_principal=token.principal)
        self.sessions[sid] = sess
        return sess

    def tools_call(
        self,
        session_id: str,
        tool_name: str,
        token: Optional[Token],
    ) -> str:
        # Invariant: consent is re-derived from the presented credential on
        # every call. The session supplies only the principal binding.
        if token is None:
            raise ConsentBoundaryError("missing Authorization on tools/call")

        sess = self.sessions.get(session_id)
        if sess is None:
            raise ConsentBoundaryError(f"unknown session {session_id}")

        if token.revoked:
            # Revocation is authoritative regardless of session state.
            del self.sessions[session_id]
            raise ConsentBoundaryError(
                f"token for principal {token.principal} is revoked; session invalidated"
            )

        if token.principal != sess.bound_principal:
            # Cross-principal reuse is escalation, not retention. Kill session.
            del self.sessions[session_id]
            raise ConsentBoundaryError(
                f"principal_mismatch: session bound to {sess.bound_principal}, "
                f"request presented {token.principal}"
            )

        spec = self.tools.get(tool_name)
        if spec is None:
            raise ConsentBoundaryError(f"unknown tool {tool_name}")

        if spec.required_scope not in token.scopes:
            raise ConsentBoundaryError(
                f"insufficient_scope: {tool_name} requires {spec.required_scope!r}, "
                f"presented scopes={sorted(token.scopes)}"
            )

        return f"executed {tool_name} as {token.principal}"


# Reproduce the failure: broad token establishes session, narrowed token
# continues the same session. The naive server would have cached the broad
# grant; this one rejects at the tool boundary.
srv = McpServer()
srv.tools["shell"] = ToolSpec(name="shell", required_scope="shell:exec")
srv.tools["read"] = ToolSpec(name="read", required_scope="files:read")

broad = Token(principal="agent-a", scopes=frozenset({"files:read", "shell:exec"}))
sess = srv.initialize(broad)
assert srv.tools_call(sess.session_id, "shell", broad) == "executed shell as agent-a"

narrowed = Token(principal="agent-a", scopes=frozenset({"files:read"}))
try:
    srv.tools_call(sess.session_id, "shell", narrowed)
except ConsentBoundaryError as e:
    print(f"correctly denied: {e}")

# Cross-principal reuse must escalate to session teardown.
other = Token(principal="agent-b", scopes=frozenset({"files:read", "shell:exec"}))
try:
    srv.tools_call(sess.session_id, "shell", other)
except ConsentBoundaryError as e:
    print(f"correctly rejected: {e}")
