# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-capability-registry-impersonation-when-a-poisoned-mcp-tool-manifest-passes-schema-validation-but-silently-rewrites-tool-se.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-capability-registry-impersonation-when-a-poisoned-mcp-tool-manifest-passes-schema-validation-but-silently-rewrites-tool-se.warrant.json
# Markdown SHA-256:   849a79777028619628d2dc26ddf0ee6a16de9dd5f8db65426b7e5475d8e41cb9
# Code AST SHA-256:   21034ce346660d26da4e88363ddce3c212862061c7b4a8571141d5388d4509ad
# Verified Classes:   CapabilityBindingError, ToolManifest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CapabilityBindingError(RuntimeError):
    """Raised when a tool name binds to conflicting semantic contracts."""
    pass


@dataclass(frozen=True)
class ToolManifest:
    name: str
    input_schema: dict
    description: str
    annotations: dict

    def schema_hash(self) -> str:
        return hashlib.sha256(
            json.dumps(self.input_schema, sort_keys=True).encode()
        ).hexdigest()

    def description_hash(self) -> str:
        payload = json.dumps(
            {"description": self.description, "annotations": self.annotations},
            sort_keys=True,
        )
        return hashlib.sha256(payload.encode()).hexdigest()


def bind_registry(manifests: list[ToolManifest]) -> dict[str, ToolManifest]:
    """
    Bind a capability registry to a name -> manifest map, enforcing the
    invariant: within one session, a tool name maps to exactly one
    (schema_hash, description_hash) pair.

    Collisions with identical schema AND identical description are benign
    duplicates and deduplicate silently. Any collision where the name and
    schema match but the description diverges is treated as impersonation
    and fails closed.
    """
    bound: dict[str, ToolManifest] = {}
    for m in manifests:
        prior = bound.get(m.name)
        if prior is None:
            bound[m.name] = m
            continue

        if prior.schema_hash() != m.schema_hash():
            # Version skew: distinct tool version, must be pinned explicitly.
            raise CapabilityBindingError(
                f"tool {m.name!r} registered with divergent schema "
                f"({prior.schema_hash()[:12]} vs {m.schema_hash()[:12]}); "
                f"require explicit version pinning"
            )

        if prior.description_hash() != m.description_hash():
            # The boundary condition: schema-valid, name-valid, semantics diverged.
            raise CapabilityBindingError(
                f"capability impersonation suspected for {m.name!r}: "
                f"identical input_schema but description hash "
                f"{prior.description_hash()[:12]} != {m.description_hash()[:12]}; "
                f"refusing to bind"
            )

        # Benign duplicate: same name, schema, and description.
        continue

    return bound
