# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-validate-mcp-scope-grants-after-a-tool-s-inputschema-mutates-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-validate-mcp-scope-grants-after-a-tool-s-inputschema-mutates-mid-session.warrant.json
# Markdown SHA-256:   6568662b5035ed87671648118d7cb194636f336f32b756bd6adc96db3006b431
# Code AST SHA-256:   512679f2671a084e823f867b7e14345c8bb21842db703fefb37ef860a256a9bf
# Verified Classes:   SchemaDriftConsentError, ScopeAnnotationError, ConsentGrant, Session
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class SchemaDriftConsentError(RuntimeError):
    """Raised when a tools/call is dispatched against a schema hash
    that no longer matches the hash recorded at consent time."""
    pass


class ScopeAnnotationError(RuntimeError):
    """Raised when the live schema declares a scope not present in the
    granted scope set, even if the tool name matches."""
    pass


def canonical_schema_hash(schema: dict[str, Any]) -> str:
    # Materialize defaults and sort keys so cosmetic reorderings don't
    # trigger false re-consent, but default changes do.
    normalized = json.dumps(schema, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(normalized.encode()).hexdigest()[:16]


@dataclass
class ConsentGrant:
    tool_name: str
    schema_hash: str
    scopes: frozenset[str]


@dataclass
class Session:
    session_id: str
    grants: dict[str, ConsentGrant] = field(default_factory=dict)
    suspended: set[str] = field(default_factory=set)


def on_tools_list_changed(session: Session, live_schemas: dict[str, dict[str, Any]]) -> None:
    for tool_name, grant in session.grants.items():
        live = live_schemas.get(tool_name)
        if live is None:
            session.suspended.add(tool_name)
            continue
        if canonical_schema_hash(live) != grant.schema_hash:
            session.suspended.add(tool_name)


def dispatch_tool_call(
    session: Session,
    tool_name: str,
    arguments: dict[str, Any],
    live_schemas: dict[str, dict[str, Any]],
) -> dict[str, Any]:
    grant = session.grants.get(tool_name)
    if grant is None:
        raise SchemaDriftConsentError(f"no consent grant for tool {tool_name!r}")

    live = live_schemas.get(tool_name)
    if live is None:
        raise SchemaDriftConsentError(f"tool {tool_name!r} no longer advertised")

    live_hash = canonical_schema_hash(live)
    if tool_name in session.suspended or live_hash != grant.schema_hash:
        # Fail closed: do not dispatch against a schema the client never
        # consented to. Surface the new hash for re-consent.
        raise SchemaDriftConsentError(
            f"consent expired for {tool_name!r}: granted schema {grant.schema_hash}, "
            f"live schema {live_hash}; re-consent required"
        )

    declared = frozenset(live.get("x-mcp-scopes", []))
    undeclared = declared - grant.scopes
    if undeclared:
        raise ScopeAnnotationError(
            f"live schema for {tool_name!r} declares scopes {sorted(undeclared)} "
            f"not present in grant {sorted(grant.scopes)}"
        )

    # Only now is dispatch sound: session auth (checked upstream), schema
    # identity, and scope annotations all agree with the consent record.
    return {"tool": tool_name, "arguments": arguments, "dispatched": True}
