# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-dynamically-loaded-mcp-tool-whose-description-mutates-between-capability-negotiation-and-invocatio.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-dynamically-loaded-mcp-tool-whose-description-mutates-between-capability-negotiation-and-invocatio.warrant.json
# Markdown SHA-256:   79f6f6d2efb47e294bfe5dcaec3cbc199366255d9db29abcaea253cc0709159d
# Code AST SHA-256:   cd516572dec433106a946214e698f6dd36d5be3874905b46274311b19927a7f0
# Verified Classes:   DescriptionDriftError, VerifiedTool
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class DescriptionDriftError(RuntimeError):
    """Raised when a tool's instruction-bearing description changes after verification."""
    pass


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


def _hash(text: str) -> str:
    # Normalize whitespace so benign re-serialization does not trip the guard.
    normalized = " ".join(text.split())
    return hashlib.sha256(normalized.encode("utf-8")).hexdigest()


def verify_at_negotiation(name: str, schema: dict, description: str, server_id: str) -> VerifiedTool:
    return VerifiedTool(
        name=name,
        schema_hash=_hash(repr(sorted(schema.items()))),
        description_hash=_hash(description),
        server_identity=server_id,
    )


def resolve_for_invocation(
    verified: VerifiedTool,
    live_name: str,
    live_schema: dict,
    live_description: str,
    live_server_id: str,
) -> str:
    """Return the description to inject into the prompt, or raise if it drifted.

    The description is the only field the model reads as instructions, so it
    must be byte-stable between negotiation and invocation. Schema and identity
    equality are necessary but NOT sufficient.
    """
    if live_name != verified.name or live_server_id != verified.server_identity:
        raise DescriptionDriftError(
            f"tool identity changed: {verified.name}@{verified.server_identity} "
            f"-> {live_name}@{live_server_id}"
        )
    if _hash(repr(sorted(live_schema.items()))) != verified.schema_hash:
        raise DescriptionDriftError(f"schema drift on {verified.name}")

    live_desc_hash = _hash(live_description)
    if live_desc_hash != verified.description_hash:
        # Quarantine: do not inject the mutated description. Surface to operator.
        raise DescriptionDriftError(
            f"description-channel drift on {verified.name}: "
            f"verified={verified.description_hash[:12]} live={live_desc_hash[:12]}; "
            f"quarantine until re-approved out of band"
        )
    return live_description
