# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-renegotiates-mcp-tool-capability-scope-mid-session-and-the-policy-cache-is-keyed-on-tool-name-rather-than-capability-tup.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-renegotiates-mcp-tool-capability-scope-mid-session-and-the-policy-cache-is-keyed-on-tool-name-rather-than-capability-tup.warrant.json
# Markdown SHA-256:   c951914183d84d3a97a8efae4fa62661866a8923f13ff983cb06ba5a00901d0e
# Code AST SHA-256:   fce2371ae1c9ae5911e305aebee4707942734e7b18a6ccf6a9ac403e744f8e45
# Verified Classes:   CapabilityScopeViolation, ToolKey, PolicyCache
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class CapabilityScopeViolation(RuntimeError):
    """Raised when a cached allow decision is reused across a manifest mutation
    that widened the tool's declared capability or input schema."""


@dataclass(frozen=True)
class ToolKey:
    server_id: str
    name: str
    schema_digest: str
    capabilities: tuple[str, ...]


def _canonical_digest(schema: dict[str, Any], capabilities: list[str]) -> str:
    if schema.get("additionalProperties") is True and not schema.get("properties"):
        return "UNCONSTRAINED"
    payload = json.dumps(
        {"schema": schema, "capabilities": sorted(capabilities)},
        sort_keys=True,
        separators=(",", ":"),
    )
    return hashlib.sha256(payload.encode()).hexdigest()


@dataclass
class PolicyCache:
    decisions: dict[ToolKey, bool] = field(default_factory=dict)
    baseline: dict[str, ToolKey] = field(default_factory=dict)

    def key_for(self, server_id: str, entry: dict[str, Any]) -> ToolKey:
        return ToolKey(
            server_id=server_id,
            name=entry["name"],
            schema_digest=_canonical_digest(
                entry.get("inputSchema", {}), entry.get("capabilities", [])
            ),
            capabilities=tuple(sorted(entry.get("capabilities", []))),
        )

    def apply_manifest(self, server_id: str, manifest: list[dict[str, Any]]) -> None:
        for entry in manifest:
            new_key = self.key_for(server_id, entry)
            prior = self.baseline.get(entry["name"])
            if prior is not None and prior != new_key:
                # name matched but tuple changed -> stale allow is unsound
                self.decisions.pop(prior, None)
                self.decisions[new_key] = None  # type: ignore[assignment]
            self.baseline[entry["name"]] = new_key

    def authorize(self, server_id: str, entry: dict[str, Any]) -> bool:
        key = self.key_for(server_id, entry)
        if key.schema_digest == "UNCONSTRAINED":
            raise CapabilityScopeViolation(
                f"tool {entry['name']!r} has unconstrained schema; "
                "cannot inherit or cache an allow decision"
            )
        decision = self.decisions.get(key)
        if decision is None:
            raise CapabilityScopeViolation(
                f"tool {entry['name']!r} has no adjudicated decision for "
                f"tuple {key}; re-adjudication required before invocation"
            )
        if decision is False:
            raise CapabilityScopeViolation(
                f"tool {entry['name']!r} denied under tuple {key}"
            )
        return True
