# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-signed-mcp-manifest-from-surviving-tool-schema-drift-between-build-and-first-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-signed-mcp-manifest-from-surviving-tool-schema-drift-between-build-and-first-invocation.warrant.json
# Markdown SHA-256:   bc8d4fdaa04f29b5f0bf9be955b1b947912bb23f641ed7a07ecdf7707bfd9832
# Code AST SHA-256:   d3d1d2c10a4cea64bf3288deb991fe192e72fbe43acedf981cf5645609b4bcfc
# Verified Classes:   ManifestSchemaDriftError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from typing import Mapping


class ManifestSchemaDriftError(RuntimeError):
    """Raised when a live MCP tools/list schema does not match the signed manifest digest."""


def canonical_tools_digest(tools_list: list[dict]) -> str:
    # Canonicalize deterministically: sorted keys, stable separators, no whitespace.
    canonical = json.dumps(
        tools_list, sort_keys=True, separators=(",", ":"), ensure_ascii=True
    )
    return "sha256:" + hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def verify_runtime_schema(
    manifest: Mapping,
    live_tools_list: list[dict],
    live_env_vector: Mapping[str, str],
) -> None:
    """
    Enforce the runtime digest gate. Must be called at session establishment,
    BEFORE tools are exposed to the agent planner.
    """
    declared_env = manifest.get("envVector", {})
    # Any environment input not committed in the manifest is an unpinned
    # degree of freedom and invalidates the digest's reproducibility.
    unpinned = {
        k: v
        for k, v in live_env_vector.items()
        if declared_env.get(k) != v
    }
    if unpinned:
        raise ManifestSchemaDriftError(
            f"Environment inputs not committed in manifest: {sorted(unpinned)}. "
            f"Signed toolsDigest does not cover schema produced under this env."
        )

    expected = manifest["toolsDigest"]
    actual = canonical_tools_digest(live_tools_list)
    if actual != expected:
        raise ManifestSchemaDriftError(
            f"Live tools/list digest {actual} != signed manifest digest {expected}. "
            f"Server is offering tools the signer did not attest; refusing exposure."
        )
