# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-fingerprints-an-mcp-server-by-its-tool-schema-and-the-server-silently-rotates-its-behavior-under-a-stable-schema.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-fingerprints-an-mcp-server-by-its-tool-schema-and-the-server-silently-rotates-its-behavior-under-a-stable-schema.warrant.json
# Markdown SHA-256:   c1419a21f37f9d58ceac78d6b201d4a1849c36b78167f2f4cc79b135250bd3f4
# Code AST SHA-256:   b26bd69d9577f0e27e6de9314ac8cc4761fa369e529b63dd57e08ed68622464f
# Verified Classes:   SchemaStabilityNotSufficient, ServerFingerprint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class SchemaStabilityNotSufficient(RuntimeError):
    """Raised when an agent attempts to clear a server for instruction-ingesting
    tool calls on the basis of a stable tools/list schema alone."""


@dataclass
class ServerFingerprint:
    contract_hash: str                      # sha256 of canonical tools/list
    behavior_hash: dict = field(default_factory=dict)  # tool -> normalized canary output hash
    attested: bool = False


def canonical_contract_hash(tools_list_payload: dict) -> str:
    # Sort keys so serialization order cannot mask a real change.
    blob = json.dumps(tools_list_payload, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(blob.encode("utf-8")).hexdigest()


def clear_server_for_call(
    tool_name: str,
    pinned: ServerFingerprint,
    current_contract_hash: str,
    current_behavior_hash: str | None,
    tool_output_is_reingested_as_instructions: bool,
) -> None:
    contract_match = current_contract_hash == pinned.contract_hash
    behavior_match = (
        current_behavior_hash is not None
        and current_behavior_hash == pinned.behavior_hash.get(tool_name)
    )

    if contract_match and behavior_match and pinned.attested:
        return  # both channels agree and identity is established

    if contract_match and tool_output_is_reingested_as_instructions and not behavior_match:
        # The exact boundary failure: schema stable, behavior unverified,
        # and the result feeds the instruction stream.
        raise SchemaStabilityNotSufficient(
            f"tool {tool_name!r}: contract hash matches but behavior hash "
            f"{'missing' if current_behavior_hash is None else 'differs'}; "
            f"refusing to authorize instruction-ingesting call on schema alone"
        )

    if not contract_match:
        # New or changed tool surface: always treat as untrusted until re-baselined.
        raise SchemaStabilityNotSufficient(
            f"tool {tool_name!r}: contract drift detected; re-baseline required"
        )

    # Contract matches, behavior matches or tool is not instruction-ingesting,
    # but server identity is unattested: downgrade, do not silently clear.
    raise SchemaStabilityNotSufficient(
        f"tool {tool_name!r}: server unattested; schema stability is not a warrant"
    )
