# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a-malicious-mcp-server-that-poisons-tool-descriptions-rather-than-tool-outputs-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a-malicious-mcp-server-that-poisons-tool-descriptions-rather-than-tool-outputs-mid-session.warrant.json
# Markdown SHA-256:   6e95593699ca0cd22a6d1bb97983ef888778fa2397bbbc32c8d10e98412b0de2
# Code AST SHA-256:   f79c7d3c7cd88e9a12274cbc5bc32f74e71dfc7603511cb6a9958edd2cd1cd4a
# Verified Classes:   ToolDescriptionMutationError, ToolEntry, ManifestCache
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class ToolDescriptionMutationError(RuntimeError):
    """Raised when a refreshed MCP manifest mutates a model-visible field
    (description, param docs, enum labels) without an approval gate."""
    pass


@dataclass
class ToolEntry:
    name: str
    input_schema: dict[str, Any]
    description: str

    def trust_fingerprint(self) -> str:
        # CRITICAL: description and all model-visible fields are in the hash.
        # Fingerprinting on name+schema alone is the vulnerability.
        payload = json.dumps(
            {
                "name": self.name,
                "inputSchema": self.input_schema,
                "description": self.description,
            },
            sort_keys=True,
            separators=(",", ":"),
        )
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass
class ManifestCache:
    entries: dict[str, ToolEntry] = field(default_factory=dict)
    approved_fingerprints: dict[str, str] = field(default_factory=dict)

    def reconcile(self, refreshed: list[ToolEntry]) -> list[str]:
        """Returns names of tools quarantined pending re-approval."""
        quarantined: list[str] = []
        refreshed_by_name = {t.name: t for t in refreshed}

        # Removals are authoritative: surface them, do not retry.
        for name in list(self.entries):
            if name not in refreshed_by_name:
                del self.entries[name]
                del self.approved_fingerprints[name]

        for name, tool in refreshed_by_name.items():
            fp = tool.trust_fingerprint()
            prev = self.approved_fingerprints.get(name)
            if prev is None:
                # Additive tool post-handshake: untrusted until approved.
                quarantined.append(name)
            elif prev != fp:
                # Description (or schema) mutated mid-session: quarantine.
                quarantined.append(name)
            else:
                self.entries[name] = tool

        return quarantined

    def approve(self, name: str, tool: ToolEntry) -> None:
        self.entries[name] = tool
        self.approved_fingerprints[name] = tool.trust_fingerprint()

    def active_manifest(self) -> list[ToolEntry]:
        return list(self.entries.values())


def enforce_manifest_integrity(
    cache: ManifestCache,
    refreshed: list[ToolEntry],
    auto_approve: bool = False,
) -> list[ToolEntry]:
    quarantined = cache.reconcile(refreshed)
    if quarantined and not auto_approve:
        raise ToolDescriptionMutationError(
            f"Refreshed MCP manifest mutated model-visible fields for tools "
            f"{quarantined!r} without approval. Refusing to inject into context. "
            f"Re-approve explicitly or drop the server."
        )
    for name in quarantined:
        tool = next(t for t in refreshed if t.name == name)
        cache.approve(name, tool)
    return cache.active_manifest()
