# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-a-tool-s-declared-schema-and-its-natural-language-description-when-an-mcp-server-resource-or-ag.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-a-tool-s-declared-schema-and-its-natural-language-description-when-an-mcp-server-resource-or-ag.warrant.json
# Markdown SHA-256:   a129fd22bb59175ec11b62257446be17d6bae4bde34d137a0bf80e3b78c1e18b
# Code AST SHA-256:   d459b69f21aad5ba0d7ac7bae729d8071e714fd7e114e8cd169171e49492b3ef
# Verified Classes:   DescriptorMutationRejected, AdmittedDescriptor, ToolRegistry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class DescriptorMutationRejected(RuntimeError):
    """Raised when a tool/resource/card descriptor changes content under a stable identity."""
    pass


def descriptor_fingerprint(descriptor: dict) -> str:
    # Hash ALL model-consumed content: schema, description, instructions, examples.
    # Deliberately includes natural-language fields that a schema-only diff would miss.
    canonical = json.dumps(
        {
            "name": descriptor.get("name"),
            "inputSchema": descriptor.get("inputSchema"),
            "description": descriptor.get("description"),
            "instructions": descriptor.get("instructions"),
            "skills": descriptor.get("skills"),
        },
        sort_keys=True,
        separators=(",", ":"),
    )
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


@dataclass
class AdmittedDescriptor:
    name: str
    fingerprint: str
    trusted: bool


class ToolRegistry:
    def __init__(self):
        self._admitted: dict[str, AdmittedDescriptor] = {}

    def admit(self, descriptor: dict, *, human_approved: bool) -> AdmittedDescriptor:
        fp = descriptor_fingerprint(descriptor)
        record = AdmittedDescriptor(
            name=descriptor["name"], fingerprint=fp, trusted=human_approved
        )
        self._admitted[descriptor["name"]] = record
        return record

    def refresh(self, descriptor: dict, *, human_approved: bool) -> AdmittedDescriptor:
        """Handle a list_changed notification for an already-held identity."""
        name = descriptor["name"]
        existing = self._admitted.get(name)
        if existing is None:
            return self.admit(descriptor, human_approved=human_approved)

        new_fp = descriptor_fingerprint(descriptor)
        if new_fp != existing.fingerprint:
            # Any byte change in model-consumed content is a NEW tool, not an update.
            # Do not hot-swap the description under the trusted handle.
            raise DescriptorMutationRejected(
                f"descriptor for {name!r} mutated "
                f"({existing.fingerprint[:12]} -> {new_fp[:12]}); "
                f"evict and re-admit as untrusted"
            )
        return existing


def handle_list_changed(registry: ToolRegistry, advertised: list[dict]) -> list[AdmittedDescriptor]:
    admitted = []
    for descriptor in advertised:
        try:
            admitted.append(registry.refresh(descriptor, human_approved=False))
        except DescriptorMutationRejected as exc:
            # Evict: the old trusted handle must not survive a content mutation.
            registry._admitted.pop(descriptor["name"], None)
            raise DescriptorMutationRejected(
                f"session halted: {exc}; stale tool-list rendering must be replaced, not appended"
            ) from exc
    return admitted
