# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-an-mcp-tool-invocation-allowlist-when-the-advertised-tool-schema-mutates-between-discovery-and-dispatch.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-an-mcp-tool-invocation-allowlist-when-the-advertised-tool-schema-mutates-between-discovery-and-dispatch.warrant.json
# Markdown SHA-256:   da991e79ca65c678b15f9b309baccbd04c34ae8c96100ff9363f6c5954ed28ff
# Code AST SHA-256:   486546844eb1f609033505a6c1f73784ea75768a7b905ca499eec31c7ebe3ad2
# Verified Classes:   SchemaDriftDenied, SchemaUnprovable, Grant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class SchemaDriftDenied(PermissionError):
    """Raised when a tool call's live schema no longer matches its grant."""
    pass


class SchemaUnprovable(RuntimeError):
    """Raised when the server cannot supply a descriptor to revalidate against."""
    pass


@dataclass(frozen=True)
class Grant:
    name: str
    schema_hash: str          # hash at authorization time
    session: str


def _hash_schema(name: str, input_schema: dict) -> str:
    canon = json.dumps(
        {"name": name, "inputSchema": input_schema},
        sort_keys=True, separators=(",", ":"),
    )
    return hashlib.sha256(canon.encode()).hexdigest()


def authorize(name: str, live_descriptor: dict | None, grant: Grant) -> None:
    """
    Revalidate a grant against the *current* descriptor at dispatch time.
    Fail-closed on drift and on unprovable schema.
    """
    if live_descriptor is None:
        # Server returned no descriptor on re-fetch: treat as unprovable, not unchanged.
        raise SchemaUnprovable(
            f"no live descriptor for {name!r}; cannot prove schema stability "
            f"for session {grant.session!r}"
        )

    live_hash = _hash_schema(live_descriptor["name"], live_descriptor["inputSchema"])
    if live_hash != grant.schema_hash:
        raise SchemaDriftDenied(
            f"schema drift on {name!r}: grant={grant.schema_hash[:12]} "
            f"live={live_hash[:12]}; re-authorize before dispatch"
        )


def dispatch(name: str, args: dict, fetch_descriptor, grant: Grant) -> dict:
    # fetch_descriptor must hit the server (or a version-token cache the server signed),
    # never a session-start cache.
    live = fetch_descriptor(name)
    authorize(name, live, grant)
    return {"tool": name, "args": args, "dispatch": "authorized"}
