# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-tool-description-poisoning-when-mcp-schema-text-is-treated-as-capability-metadata-rather-than-untrusted-input.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-tool-description-poisoning-when-mcp-schema-text-is-treated-as-capability-metadata-rather-than-untrusted-input.warrant.json
# Markdown SHA-256:   753dc170effe5ca0997d6d7ba7bae35746ea80a36553efa9fb78a5eadd87c94e
# Code AST SHA-256:   2e60c046932958748684e7e220be04b0168ebcde3087513fa3745052f7d273f3
# Verified Classes:   ToolDescriptionPoisoningError, ApprovedTool
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ToolDescriptionPoisoningError(RuntimeError):
    """Raised when a registry-supplied tool description fails provenance checks."""
    pass


@dataclass(frozen=True)
class ApprovedTool:
    name: str
    version: str
    description_digest: str  # sha256 hex of the description text


def digest(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


def load_tool_descriptions(
    fetched: list[dict],
    approved: dict[str, ApprovedTool],
    prior_session_digests: dict[str, str],
) -> list[dict]:
    """
    fetched: raw tools/list entries from the registry.
    approved: operator-pinned digests keyed by tool name.
    prior_session_digests: digests recorded in durable memory last cold start.
    """
    loaded = []
    for entry in fetched:
        name = entry["name"]
        desc = entry.get("description", "")
        d = digest(desc)

        pin = approved.get(name)
        if pin is None:
            raise ToolDescriptionPoisoningError(
                f"tool {name!r} has no approved digest; refusing to load unpinned description"
            )
        if d != pin.description_digest:
            raise ToolDescriptionPoisoningError(
                f"tool {name!r} description digest {d[:12]} != approved {pin.description_digest[:12]}; "
                f"possible registry supply-chain compromise"
            )

        prior = prior_session_digests.get(name)
        if prior is not None and prior != d and entry.get("version") == pin.version:
            raise ToolDescriptionPoisoningError(
                f"tool {name!r} description mutated at fixed version {pin.version}; "
                f"operator re-approval required"
            )

        # Wrap as untrusted data so precedence claims inside are voided.
        loaded.append({
            "name": name,
            "description": desc,
            "provenance": f'<tool-desc source="registry:{name}@{pin.version}" trust="data">',
            "digest": d,
        })
    return loaded
