# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-poisoned-tool-manifest-smuggled-through-a-lazy-loaded-mcp-registry-re-export-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-poisoned-tool-manifest-smuggled-through-a-lazy-loaded-mcp-registry-re-export-chain.warrant.json
# Markdown SHA-256:   af6f475a60fd29d12140527082412508872d0056195dbdb07255d60d67b3e1ca
# Code AST SHA-256:   bcacb07cd89be11f39dd0397a5254b57aae1a3dfa50e4cc3d90fe3cac1518ed0
# Verified Classes:   ToolBindingIntegrityError, ToolBinding, BoundRegistry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Callable, Any


class ToolBindingIntegrityError(RuntimeError):
    """Raised when a tool's resolved callable no longer matches its discovery-time binding,
    or when its observed side-effect class exceeds the declared one."""


@dataclass(frozen=True)
class ToolBinding:
    name: str
    schema_hash: str
    callable_hash: str
    declared_side_effects: frozenset[str]  # e.g. {"read"}, {"network"}, {"write"}


def _hash_callable(fn: Callable[..., Any]) -> str:
    # Identity over the resolved leaf: module + qualname + code bytes.
    code = getattr(fn, "__code__", None)
    code_bytes = code.co_code if code is not None else b"<no-code>"
    basis = f"{fn.__module__}:{fn.__qualname__}".encode() + code_bytes
    return hashlib.sha256(basis).hexdigest()


class BoundRegistry:
    def __init__(self) -> None:
        self._bindings: dict[str, ToolBinding] = {}
        self._resolvers: dict[str, Callable[[], Callable[..., Any]]] = {}

    def register(self, name: str, resolver: Callable[[], Callable[..., Any]],
                 schema_hash: str, declared: frozenset[str]) -> None:
        # Resolve EAGERLY at discovery to defeat lazy __getattr__ swaps.
        leaf = resolver()
        self._resolvers[name] = resolver
        self._bindings[name] = ToolBinding(
            name=name,
            schema_hash=schema_hash,
            callable_hash=_hash_callable(leaf),
            declared_side_effects=declared,
        )

    def invoke(self, name: str, args: dict[str, Any],
               observed_side_effects: frozenset[str]) -> Any:
        binding = self._bindings.get(name)
        if binding is None:
            raise ToolBindingIntegrityError(f"unregistered tool: {name}")

        # Re-resolve at invocation; a re-export shim may have swapped the leaf.
        leaf = self._resolvers[name]()
        current_hash = _hash_callable(leaf)
        if current_hash != binding.callable_hash:
            raise ToolBindingIntegrityError(
                f"callable binding changed for {name}: "
                f"discovery={binding.callable_hash[:12]} now={current_hash[:12]} "
                f"(re-export chain mutated; refusing invocation)"
            )

        # Enforce declared side-effect class at the runtime boundary.
        excess = observed_side_effects - binding.declared_side_effects
        if excess:
            raise ToolBindingIntegrityError(
                f"{name} declared {sorted(binding.declared_side_effects)} "
                f"but attempted {sorted(excess)} (class-confusion injection)"
            )

        return leaf(**args)
