# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-re-signed-mcp-server-manifest-that-preserves-tools-list-but-mutates-tool-descriptions-at-the-transport-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-re-signed-mcp-server-manifest-that-preserves-tools-list-but-mutates-tool-descriptions-at-the-transport-boundary.warrant.json
# Markdown SHA-256:   4bc4dbfcdeb96f66914ebfe468a687907b70a0615218ecb142a844f1d137a217
# Code AST SHA-256:   24b39720b6ae3e243aff02815b195f291e74184a3aa556e2bada371b8cecfe9a
# Verified Classes:   ManifestDriftError, SemanticProjection
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class ManifestDriftError(RuntimeError):
    """Raised when a signed MCP manifest is semantically discontinuous with its pin."""
    pass


@dataclass(frozen=True)
class SemanticProjection:
    tool_name: str
    description_norm: str
    schema_annotations: tuple[tuple[str, str], ...]
    enum_values: tuple[tuple[str, tuple[str, ...]], ...]
    default_values: tuple[tuple[str, str], ...]

    def fingerprint(self) -> str:
        blob = json.dumps(
            {
                "name": self.tool_name,
                "desc": self.description_norm,
                "ann": self.schema_annotations,
                "enum": self.enum_values,
                "def": self.default_values,
            },
            sort_keys=True,
            separators=(",", ":"),
        ).encode("utf-8")
        return hashlib.sha256(blob).hexdigest()


def _norm(text: str) -> str:
    # Conservative: unicode NFC + collapse whitespace runs. Preserve all tokens.
    return " ".join(unicodedata.normalize("NFC", text).split())


def project_tool(tool: dict[str, Any]) -> SemanticProjection:
    schema = tool.get("inputSchema", {}) or {}
    props = schema.get("properties", {}) or {}
    annotations = []
    enums = []
    defaults = []
    for prop_name, prop in sorted(props.items()):
        if isinstance(prop, dict):
            if "description" in prop:
                annotations.append((prop_name, _norm(str(prop["description"]))))
            if "enum" in prop and isinstance(prop["enum"], list):
                enums.append((prop_name, tuple(sorted(str(v) for v in prop["enum"]))))
            if "default" in prop:
                defaults.append((prop_name, _norm(str(prop["default"]))))
    return SemanticProjection(
        tool_name=str(tool.get("name", "")),
        description_norm=_norm(str(tool.get("description", ""))),
        schema_annotations=tuple(annotations),
        enum_values=tuple(enums),
        default_values=tuple(defaults),
    )


def check_manifest_continuity(
    signed_manifest: dict[str, Any],
    pinned_fingerprints: dict[str, str],
    signature_valid: bool,
    trusted_key: bool,
) -> None:
    """
    Gate runs at transport boundary, before tools enter model context.
    Raises on provenance break or semantic drift. Returns only on CONTINUOUS.
    """
    if not signature_valid or not trusted_key:
        raise ManifestDriftError(
            "PROVENANCE-BREAK: signature invalid or signing key not in trust store"
        )

    tools = signed_manifest.get("tools", []) or []
    seen: set[str] = set()
    for tool in tools:
        proj = project_tool(tool)
        seen.add(proj.tool_name)
        pinned = pinned_fingerprints.get(proj.tool_name)
        if pinned is None:
            raise ManifestDriftError(
                f"PROVENANCE-BREAK: unpinned tool '{proj.tool_name}' appeared in manifest"
            )
        if proj.fingerprint() != pinned:
            raise ManifestDriftError(
                f"DRIFT-SUSPECT: semantic projection of '{proj.tool_name}' "
                f"diverged from pin (desc/schema/enum/default mutated); "
                f"quarantine manifest and require explicit re-pin"
            )

    missing = set(pinned_fingerprints) - seen
    if missing:
        raise ManifestDriftError(
            f"PROVENANCE-BREAK: pinned tools missing from manifest: {sorted(missing)}"
        )


def admit_manifest(
    signed_manifest: dict[str, Any],
    pinned_fingerprints: dict[str, str],
    signature_valid: bool,
    trusted_key: bool,
) -> dict[str, Any]:
    # Hard stop on drift; only CONTINUOUS manifests reach the model context.
    check_manifest_continuity(
        signed_manifest, pinned_fingerprints, signature_valid, trusted_key
    )
    return signed_manifest
