# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-when-an-mcp-tool-s-description-not-its-handler-becomes-the-injection-surface-during-server-registration.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-when-an-mcp-tool-s-description-not-its-handler-becomes-the-injection-surface-during-server-registration.warrant.json
# Markdown SHA-256:   da45f69ebda46e057d8186293d07e4b522a8b68f4794d2365ec806be03376a18
# Code AST SHA-256:   8b2fb0c02236b3a34675a5e246b6b952336761c1b04f491291e21a6ce1359da2
# Verified Classes:   ManifestDriftError, DescriptionInjectionError, PinnedRegistry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestDriftError(RuntimeError):
    """Raised when a tools/list manifest no longer matches its pinned hash."""


class DescriptionInjectionError(RuntimeError):
    """Raised when a tool description attempts cross-tool choreography."""


# Verbs that indicate a description is instructing the model, not documenting a tool.
_CHOREOGRAPHY_MARKERS = (
    "before using",
    "first read",
    "then call",
    "include the contents",
    "pass the output of",
    "using the available",
)


def canonical_manifest_hash(tools: list[dict]) -> str:
    # Canonicalize so key ordering / whitespace cannot mask a real change.
    canonical = json.dumps(tools, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def _iter_description_strings(tools: list[dict]):
    for tool in tools:
        yield tool.get("name", "?"), tool.get("description", "")
        schema = tool.get("inputSchema", {}) or {}
        for prop_name, prop in (schema.get("properties", {}) or {}).items():
            yield f"{tool.get('name', '?')}.{prop_name}", prop.get("description", "")


@dataclass
class PinnedRegistry:
    pinned_hash: str | None = None

    def verify_and_admit(self, tools: list[dict]) -> str:
        # 1. Content pin: exact manifest must match the approved hash.
        current = canonical_manifest_hash(tools)
        if self.pinned_hash is not None and current != self.pinned_hash:
            raise ManifestDriftError(
                f"tools/list manifest drifted: pinned={self.pinned_hash[:12]} "
                f"current={current[:12]}; re-approval required before use"
            )

        # 2. Description quarantine: reject cross-tool choreography at any level.
        for label, text in _iter_description_strings(tools):
            lowered = text.lower()
            for marker in _CHOREOGRAPHY_MARKERS:
                if marker in lowered:
                    raise DescriptionInjectionError(
                        f"tool '{label}' description contains choreography marker "
                        f"'{marker}'; refusing to admit manifest into reasoning context"
                    )

        # 3. Only after both gates pass do we pin and return for context injection.
        self.pinned_hash = current
        return current


def register_server(pinned: PinnedRegistry, tools: list[dict]) -> str:
    return pinned.verify_and_admit(tools)
