# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-manifest-poisoning-from-surviving-mcp-server-re-registration-and-capability-re-advertisement.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-manifest-poisoning-from-surviving-mcp-server-re-registration-and-capability-re-advertisement.warrant.json
# Markdown SHA-256:   466f4012bd91decba3da7d3fc6ed99c08c74f29006633a3c0fe561ff22bb350f
# Code AST SHA-256:   a88fe17d4b2555e35c1ef5d2b0f627e0ab054a5fd5d62dfb3dd0420f75c36647
# Verified Classes:   ManifestPoisoningError, ApprovedGrant, ToolRegistry
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class ManifestPoisoningError(RuntimeError):
    """Raised when a re-advertised tool manifest diverges from its approved digest."""


# Fields the model can read as instruction; these MUST be in the digest.
SEMANTIC_FIELDS = ("name", "description", "inputSchema", "annotations", "default")


def semantic_digest(manifest: dict[str, Any]) -> str:
    payload = {k: manifest.get(k) for k in SEMANTIC_FIELDS}
    # canonicalize: sorted keys, no whitespace ambiguity
    canon = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return hashlib.sha256(canon.encode("utf-8")).hexdigest()


@dataclass
class ApprovedGrant:
    name: str
    digest: str


@dataclass
class ToolRegistry:
    grants: dict[str, ApprovedGrant] = field(default_factory=dict)  # keyed by name -> approved digest

    def reconcile(self, advertised: list[dict[str, Any]]) -> list[dict[str, Any]]:
        """Return tools safe to expose to the model. Quarantine any whose
        semantic digest differs from the approved grant, even on name match."""
        safe: list[dict[str, Any]] = []
        for manifest in advertised:
            name = manifest.get("name")
            if not name:
                raise ManifestPoisoningError("advertised tool missing name")
            digest = semantic_digest(manifest)
            grant = self.grants.get(name)
            if grant is None:
                # never approved: quarantine, do not auto-expose
                continue
            if grant.digest != digest:
                # name matched but model-visible bytes changed -> poisoned or edited
                raise ManifestPoisoningError(
                    f"manifest drift for {name!r}: approved={grant.digest[:12]} "
                    f"advertised={digest[:12]} — re-approval required before exposure"
                )
            safe.append(manifest)
        return safe

    def approve(self, manifest: dict[str, Any]) -> None:
        name = manifest["name"]
        self.grants[name] = ApprovedGrant(name=name, digest=semantic_digest(manifest))


def handle_tools_list_changed(registry: ToolRegistry, server_payload: list[dict[str, Any]]) -> list[dict[str, Any]]:
    # A reconnect is NOT an implicit re-approval. Reconcile strictly.
    try:
        return registry.reconcile(server_payload)
    except ManifestPoisoningError:
        # fail closed: expose nothing from this server until operator re-consents
        return []
