# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-caches-a-capability-grant-across-an-mcp-server-restart-and-reconnects-to-a-re-scoped-tool-surface.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-caches-a-capability-grant-across-an-mcp-server-restart-and-reconnects-to-a-re-scoped-tool-surface.warrant.json
# Markdown SHA-256:   d69c5a5d8314f4180db48f7ff2f97690706472ce30fe99550ce543b84888dcfa
# Code AST SHA-256:   6fae44de0528b3fe4b036edf34ce6ddcc19e55319f47981759c5de58b5eadb71
# Verified Classes:   StaleGrantError, Surface, Grant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleGrantError(RuntimeError):
    """Raised when a cached capability grant no longer corresponds to the
    server's current tool surface (identity matched, surface did not)."""
    pass


@dataclass(frozen=True)
class Surface:
    digest: str
    root: str
    tools: frozenset


@dataclass(frozen=True)
class Grant:
    tool: str
    granted_against: str  # surface digest at grant time
    root: str


def surface_digest(tools_list: list[dict], policy_root: str) -> str:
    canon = "|".join(sorted(t["name"] for t in tools_list)) + "::" + policy_root
    return hashlib.sha256(canon.encode()).hexdigest()


def authorize_call(grant: Grant, current: Surface, tool: str, path: str) -> str:
    # Invariant: grant is only valid against the surface it was issued for.
    if grant.granted_against != current.digest:
        raise StaleGrantError(
            f"grant for {grant.tool} issued against {grant.granted_against[:8]} "
            f"but server surface is {current.digest[:8]}; renegotiate before call"
        )
    if tool not in current.tools:
        raise StaleGrantError(f"tool {tool} absent from current surface")

    # Canonicalize against the SERVER-DECLARED root, not the cached grant root.
    import os
    resolved = os.path.realpath(os.path.join(current.root, path))
    if not resolved.startswith(os.path.realpath(current.root) + os.sep):
        raise StaleGrantError(
            f"path {path!r} escapes current root {current.root!r} "
            f"(resolved {resolved!r}); cached grant root was {grant.root!r}"
        )
    return resolved
