# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-poisoned-mcp-tool-description-before-first-invocation-manifest-hash-binding-description-content-divergence-and-the-pre-d.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-poisoned-mcp-tool-description-before-first-invocation-manifest-hash-binding-description-content-divergence-and-the-pre-d.warrant.json
# Markdown SHA-256:   3f680625c227c5a1668248a99c153ae20ebbe4966ab01ce4b7cd3e6cca23f97f
# Code AST SHA-256:   1aa217a19b40d600366b53cce4c2d046284e072bdef2f6c4ea06a634a702293e
# Verified Classes:   ManifestAttestationError, AttestedManifest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestAttestationError(RuntimeError):
    """Raised when a served MCP manifest does not match the pinned attested digest."""


@dataclass(frozen=True)
class AttestedManifest:
    signer_id: str
    canonical_digest: str  # sha256 over canonicalized full tuples


def _canonical_bytes(tools: list[dict]) -> bytes:
    # Order-stable, full-tuple serialization. Description and inputSchema are
    # included verbatim: any injected paragraph changes the digest.
    normalized = [
        {
            "name": t["name"],
            "description": t["description"],
            "inputSchema": t["inputSchema"],
        }
        for t in sorted(tools, key=lambda t: t["name"])
    ]
    return json.dumps(normalized, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")


def attest_and_render(
    served_tools: list[dict],
    attested: AttestedManifest,
    pinned_signers: dict[str, str],
    fetch_trigger: str,
) -> str:
    """
    Called on EVERY tools/list fetch, including tools/list_changed notifications.
    Returns a hash-stamped rendering safe to place in model context, or raises.
    """
    if attested.signer_id not in pinned_signers:
        raise ManifestAttestationError(
            f"signer {attested.signer_id!r} not in pinned trust store (trigger={fetch_trigger})"
        )

    observed = hashlib.sha256(_canonical_bytes(served_tools)).hexdigest()
    if observed != attested.canonical_digest:
        # Set-level check: catches added tools, reordered tools, and
        # description mutations alike. No content inspection, no "trusted refresh".
        raise ManifestAttestationError(
            f"manifest digest divergence on trigger={fetch_trigger}: "
            f"expected={attested.canonical_digest} observed={observed} "
            f"tool_count={len(served_tools)}"
        )

    # Only after the digest check passes is description text allowed to enter
    # the model's conditioning context, and it is stamped with the verified digest.
    lines = [f"[manifest {observed[:12]} signer={attested.signer_id}]"]
    for t in sorted(served_tools, key=lambda t: t["name"]):
        lines.append(f"- {t['name']}: {t['description']}")
    return "\n".join(lines)
