# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-capability-scoped-mcp-tool-grants-from-silently-widening-across-a-re-negotiated-session.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-capability-scoped-mcp-tool-grants-from-silently-widening-across-a-re-negotiated-session.warrant.json
# Markdown SHA-256:   1f800774a9b52a4b7b2d69ff2d0a9a6e23cd8e59f31823e7a51cc748582a0faf
# Code AST SHA-256:   d01829c816fa1dbebcc0111e9aaea5570d5baf359d709523897acc91c1d5f3fd
# Verified Classes:   CapabilityWidenedError, DescriptorDriftError, Grant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CapabilityWidenedError(RuntimeError):
    """Raised when a live tool descriptor has widened relative to the
    descriptor a capability grant was evaluated against."""


class DescriptorDriftError(RuntimeError):
    """Raised when a descriptor changed in a way that cannot be classified
    as safe narrowing and must be re-authorized."""


def canonical_hash(descriptor: dict[str, Any]) -> str:
    normalized = json.dumps(descriptor, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(normalized.encode("utf-8")).hexdigest()


@dataclass(frozen=True)
class Grant:
    tool_name: str
    bound_schema_hash: str
    bound_schema: dict[str, Any]
    allowed_params: frozenset[str]


def _param_names(schema: dict[str, Any]) -> frozenset[str]:
    return frozenset(schema.get("properties", {}).keys())


def classify_drift(grant: Grant, live_descriptor: dict[str, Any]) -> str:
    live_params = _param_names(live_descriptor.get("inputSchema", {}))
    bound_params = _param_names(grant.bound_schema)
    added = live_params - bound_params
    removed = bound_params - live_params
    if added:
        return "widened"
    if removed and not added:
        return "narrowed"
    return "reshaped"


def authorize_call(
    grant: Grant,
    live_descriptor: dict[str, Any],
    args: dict[str, Any],
) -> None:
    live_hash = canonical_hash(live_descriptor)
    if live_hash != grant.bound_schema_hash:
        drift = classify_drift(grant, live_descriptor)
        if drift == "widened":
            raise CapabilityWidenedError(
                f"tool {grant.tool_name!r} descriptor widened: "
                f"new params {sorted(_param_names(live_descriptor['inputSchema']) - _param_names(grant.bound_schema))} "
                f"not covered by grant bound at {grant.bound_schema_hash[:12]}"
            )
        if drift == "reshaped":
            raise DescriptorDriftError(
                f"tool {grant.tool_name!r} descriptor reshaped without clear "
                f"narrowing; re-authorization required"
            )
        # narrowed: safe to proceed against the original bound constraints
    unexpected = set(args) - grant.allowed_params
    if unexpected:
        raise CapabilityWidenedError(
            f"tool {grant.tool_name!r} called with args {sorted(unexpected)} "
            f"outside grant-bound parameter set {sorted(grant.allowed_params)}"
        )
