# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-tool-description-tamper-when-the-mcp-server-s-advertised-hash-is-signed-but-the-runtime-manifest-drifts-between-capabili.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-tool-description-tamper-when-the-mcp-server-s-advertised-hash-is-signed-but-the-runtime-manifest-drifts-between-capabili.warrant.json
# Markdown SHA-256:   b95a74595d7e05670b1b017e92163b579b64814d2458754022a4bf2ccec2c60e
# Code AST SHA-256:   7d54341e9556339813ac6a98fdc30b158a2ba034fbf9bf41f0eb2881e7492071
# Verified Classes:   DescriptorDriftError, AttestationUnavailableError, AttestedManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Optional


class DescriptorDriftError(RuntimeError):
    """Raised when the tool descriptor the model reasons over diverges
    from the descriptor set attested at handshake time."""


class AttestationUnavailableError(RuntimeError):
    """Raised when a drift is detected but the server cannot be
    re-attested to resolve it."""


@dataclass
class AttestedManifest:
    manifest_digest: str          # digest over canonicalized signed descriptor set
    tool_names: frozenset[str]
    arg_schemas: dict[str, str]   # tool name -> canonical hash of argument schema


def canonicalize_descriptor(tool: dict) -> str:
    """Strip volatile fields so benign re-lists do not flap the digest.
    Description prose is deliberately INCLUDED: it is the steering surface."""
    stable = {
        "name": tool["name"],
        "description": tool.get("description", ""),  # untrusted, but hashed
        "inputSchema": tool.get("inputSchema", {}),
    }
    return json.dumps(stable, sort_keys=True, separators=(",", ":"))


def digest_descriptor_set(tools: list[dict]) -> str:
    h = hashlib.sha256()
    for tool in sorted(tools, key=lambda t: t["name"]):
        h.update(canonicalize_descriptor(tool).encode("utf-8"))
        h.update(b"\x00")
    return h.hexdigest()


def schema_digest(tool: dict) -> str:
    return hashlib.sha256(
        json.dumps(tool.get("inputSchema", {}), sort_keys=True).encode()
    ).hexdigest()


def check_descriptor_integrity(
    attested: AttestedManifest,
    live_tools: list[dict],
    reattest_fn,  # callable() -> Optional[AttestedManifest]
) -> AttestedManifest:
    """Invariant: the descriptor fragment the model is about to reason over
    must match the last attested manifest, or the tool loop halts."""

    live_digest = digest_descriptor_set(live_tools)

    if live_digest == attested.manifest_digest:
        return attested  # no drift, proceed

    live_names = frozenset(t["name"] for t in live_tools)
    live_schemas = {t["name"]: schema_digest(t) for t in live_tools}

    schema_changed = (
        live_names != attested.tool_names
        or live_schemas != attested.arg_schemas
    )

    # Prose-only drift: schema identical, description text changed.
    # This is the highest-severity case — no schema validator flags it,
    # but the model's reasoning is steered by the new prose.
    prose_only_drift = not schema_changed

    fresh = reattest_fn()
    if fresh is None:
        raise AttestationUnavailableError(
            "descriptor drift detected but server could not be re-attested; "
            f"cached={attested.manifest_digest[:12]} live={live_digest[:12]} "
            f"prose_only={prose_only_drift}"
        )

    if fresh.manifest_digest != live_digest:
        raise DescriptorDriftError(
            "re-attestation succeeded but does not match live descriptor set; "
            "possible tamper-in-flight during re-list"
        )

    if schema_changed:
        # New capability grant: requires operator re-approval upstream.
        raise DescriptorDriftError(
            "tool name or argument schema changed since attestation; "
            "operator re-approval required before dispatch"
        )

    if prose_only_drift:
        # Accept the new attestation but mark it: the model was about to
        # reason over unsigned prose. Log and require explicit re-approval.
        raise DescriptorDriftError(
            "description prose changed under valid re-attestation; "
            "treat as security event, not cosmetic update"
        )

    return fresh
