# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-manifest-signature-tool-schema-divergence-at-mcp-server-attach-time-before-executing-a-poisoned-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-manifest-signature-tool-schema-divergence-at-mcp-server-attach-time-before-executing-a-poisoned-tool-call.warrant.json
# Markdown SHA-256:   5c8a8a77ef86cb3b880d1c00eb55e49e7688b1bec6de0398ecd289c220201f6a
# Code AST SHA-256:   0abc86d3ce30a7016298c5cd9493ad0e561ca860d2717655b3c1f660af9628ed
# Verified Classes:   ManifestBindingError, ToolAttestation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestBindingError(RuntimeError):
    """Raised when a live MCP tools/list surface diverges from the signed manifest."""


@dataclass(frozen=True)
class ToolAttestation:
    name: str
    description_hash: str
    schema_hash: str


def _canonical_hash(obj: dict) -> str:
    # Canonicalization must match the signing pipeline byte-for-byte.
    payload = json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()


def attest_manifest_tools(signed_manifest: dict) -> dict[str, ToolAttestation]:
    attested: dict[str, ToolAttestation] = {}
    for tool in signed_manifest["tools"]:
        attested[tool["name"]] = ToolAttestation(
            name=tool["name"],
            description_hash=_canonical_hash({"description": tool.get("description", "")}),
            schema_hash=_canonical_hash(tool["inputSchema"]),
        )
    return attested


def verify_binding(signed_manifest: dict, live_tools_list: dict) -> None:
    """
    Reconcile the live tools/list against the signed manifest before any
    tool description is admitted to the model context. Fail closed on any
    divergence: added tools, removed tools, or per-tool hash mismatch.
    """
    attested = attest_manifest_tools(signed_manifest)
    live = {t["name"]: t for t in live_tools_list.get("tools", [])}

    added = set(live) - set(attested)
    removed = set(attested) - set(live)
    changed: list[str] = []

    for name in set(live) & set(attested):
        live_desc = _canonical_hash({"description": live[name].get("description", "")})
        live_schema = _canonical_hash(live[name]["inputSchema"])
        if live_desc != attested[name].description_hash or live_schema != attested[name].schema_hash:
            changed.append(name)

    if added or removed or changed:
        raise ManifestBindingError(
            "MCP tool surface diverges from signed manifest "
            f"(publisher_key={signed_manifest.get('key_id', 'unknown')}): "
            f"added={sorted(added)}, removed={sorted(removed)}, changed={sorted(changed)}"
        )


def attach_mcp_server(signed_manifest: dict, live_tools_list: dict, signature_valid: bool) -> dict:
    if not signature_valid:
        raise ManifestBindingError("manifest signature invalid; refusing attach")
    verify_binding(signed_manifest, live_tools_list)
    # Only now may tool descriptions enter the model context.
    return {"status": "attached", "tools": [t["name"] for t in live_tools_list["tools"]]}
