# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-semantically-consistent-but-adversarially-re-scoped-mcp-tool-descriptor-at-load-time.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-semantically-consistent-but-adversarially-re-scoped-mcp-tool-descriptor-at-load-time.warrant.json
# Markdown SHA-256:   f3011696d369b4988737fda238ce04cfbe67bb5e3919fc61f81d015509508a8b
# Code AST SHA-256:   381cb7542f34f3eaea4319d34a937437b3f494f96b6003402fcb6a14608599e8
# Verified Classes:   DescriptorRescopeError, Binding, DescriptorRegistry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class DescriptorRescopeError(RuntimeError):
    """Raised when a tool descriptor's semantic fields change under a stable schema hash,
    or when annotations and description contradict each other."""
    pass


MUTATING_VERBS = ("TRUNCATE", "DROP", "DELETE", "INSERT", "UPDATE", "ALTER", "GRANT", "REVOKE")


def _canonical(desc: dict[str, Any]) -> bytes:
    return json.dumps(desc, sort_keys=True, separators=(",", ":")).encode()


def full_tuple_hash(desc: dict[str, Any]) -> str:
    # Pin ALL behavior-steering fields, not just inputSchema.
    projection = {
        "name": desc["name"],
        "inputSchema": desc["inputSchema"],
        "description": desc["description"],
        "annotations": desc.get("annotations", {}),
    }
    return hashlib.sha256(_canonical(projection)).hexdigest()


def assert_cross_field_consistency(desc: dict[str, Any]) -> None:
    ann = desc.get("annotations", {})
    if ann.get("readOnlyHint") is True:
        prose = desc["description"].upper()
        for verb in MUTATING_VERBS:
            if verb in prose:
                raise DescriptorRescopeError(
                    f"tool {desc['name']!r}: readOnlyHint=true but description "
                    f"authorizes mutating verb {verb!r}; refusing to bind"
                )


@dataclass
class Binding:
    descriptor: dict[str, Any]
    full_hash: str


class DescriptorRegistry:
    def __init__(self) -> None:
        self._bindings: dict[str, Binding] = {}

    def bind_initial(self, desc: dict[str, Any]) -> None:
        assert_cross_field_consistency(desc)
        self._bindings[desc["name"]] = Binding(desc, full_tuple_hash(desc))

    def refresh(self, desc: dict[str, Any]) -> None:
        name = desc["name"]
        prior = self._bindings.get(name)
        if prior is None:
            # New capability: allowed, but must pass consistency.
            assert_cross_field_consistency(desc)
            self._bindings[name] = Binding(desc, full_tuple_hash(desc))
            return

        # The high-risk transition: schema stable, semantic fields moved.
        schema_stable = prior.descriptor["inputSchema"] == desc["inputSchema"]
        new_hash = full_tuple_hash(desc)

        if schema_stable and new_hash != prior.full_hash:
            raise DescriptorRescopeError(
                f"tool {name!r}: inputSchema unchanged but description/annotations "
                f"mutated ({prior.full_hash[:12]} -> {new_hash[:12]}); "
                f"treating as re-authorization event, not silent rebind"
            )

        assert_cross_field_consistency(desc)
        self._bindings[name] = Binding(desc, new_hash)
