# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-a-signed-mcp-manifest-before-tool-invocation-schema-drift-detection-across-the-signature-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-invalidate-a-signed-mcp-manifest-before-tool-invocation-schema-drift-detection-across-the-signature-boundary.warrant.json
# Markdown SHA-256:   1f780ca09d9a5028d8892aecda59daa5c44e22d932e687ca989ceda26ea7132c
# Code AST SHA-256:   6ff3afae713371a151fd629b0cfd142643b29da731c704dfbb886b9fc73f2f1f
# Verified Classes:   SchemaDriftError, SignedManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class SchemaDriftError(RuntimeError):
    """Raised when the live MCP tool schema diverges from the signed manifest."""


@dataclass(frozen=True)
class SignedManifest:
    tool_digest: str      # sha256 over canonicalized tools/list at signing time
    version: str
    expires_at: int       # epoch seconds


def canonical_digest(tools: list[dict]) -> str:
    # Canonicalization MUST match the signer's: sorted keys, no whitespace,
    # NFC-normalized strings, numbers as-is.
    blob = json.dumps(tools, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return hashlib.sha256(blob.encode("utf-8")).hexdigest()


def bind_manifest(manifest: SignedManifest, live_tools: list[dict],
                  live_version: str, now: int) -> None:
    """Bind a verified manifest to the live schema. Raises on any divergence.

    This runs BEFORE tool registration. Drift must never reach the retry loop.
    """
    if now >= manifest.expires_at:
        raise SchemaDriftError(
            f"manifest expired at {manifest.expires_at}, now={now}"
        )
    if live_version != manifest.version:
        raise SchemaDriftError(
            f"version mismatch: manifest={manifest.version} live={live_version}"
        )
    live_digest = canonical_digest(live_tools)
    if live_digest != manifest.tool_digest:
        # One re-canonicalization attempt is permitted only to rule out a
        # canonicalization artifact; a persistent mismatch is a hard stop.
        raise SchemaDriftError(
            "live tool schema diverges from signed manifest: "
            f"manifest={manifest.tool_digest} live={live_digest}"
        )
