# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-load-a-signed-mcp-manifest-when-the-signature-verifies-but-the-tool-set-drifts-from-its-provenance-attestation.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-load-a-signed-mcp-manifest-when-the-signature-verifies-but-the-tool-set-drifts-from-its-provenance-attestation.warrant.json
# Markdown SHA-256:   c49dcbe8869349f2a2eea451acca6778e54f9a7472efe2ef8a21d3514a7d5a56
# Code AST SHA-256:   ecad4c74888fb08056fca1a91b9b5d142112739ccec9b72b3946faf1b841a6a5
# Verified Classes:   ManifestAttestationJoinError, AdmissionRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ManifestAttestationJoinError(RuntimeError):
    """Raised when a signed MCP manifest's tool set does not join cleanly
    against its SBOM and the live server's introspected tool surface."""

    def __init__(self, reason: str, detail: dict):
        self.reason = reason
        self.detail = detail
        super().__init__(f"{reason}: {json.dumps(detail, sort_keys=True)}")


@dataclass(frozen=True)
class AdmissionRecord:
    manifest_digest: str
    sbom_digest: str
    attestation_digest: str
    tool_schema_digests: dict  # tool_name -> schema digest


def _schema_digest(schema: dict) -> str:
    canon = json.dumps(schema, sort_keys=True, separators=(",", ":")).encode()
    return "sha256:" + hashlib.sha256(canon).hexdigest()


def admit_mcp_server(
    manifest: dict,
    sbom_tool_names: set[str],
    live_tools: dict[str, dict],
) -> AdmissionRecord:
    """Fail-closed join. Signature verification is assumed already done
    upstream; this function enforces the *cross-artifact* invariant."""
    manifest_tools = {t["name"]: t["inputSchema"] for t in manifest["tools"]}
    manifest_names = set(manifest_tools)

    # (1) Manifest must not advertise tools the SBOM never built (spoof/stale).
    extra = manifest_names - sbom_tool_names
    if extra:
        raise ManifestAttestationJoinError(
            "manifest_sbom_toolset_mismatch",
            {"direction": "manifest_superset", "tools": sorted(extra)},
        )

    # (2) Manifest must not hide tools the SBOM attests were built (stale cache).
    missing = sbom_tool_names - manifest_names
    if missing:
        raise ManifestAttestationJoinError(
            "manifest_sbom_toolset_mismatch",
            {"direction": "manifest_subset", "tools": sorted(missing)},
        )

    # (3) Per-tool schema digests must match the live server exactly.
    schema_digests: dict[str, str] = {}
    for name, schema in manifest_tools.items():
        if name not in live_tools:
            raise ManifestAttestationJoinError(
                "manifest_tool_absent_at_runtime",
                {"tool": name},
            )
        expected = _schema_digest(schema)
        actual = _schema_digest(live_tools[name])
        if expected != actual:
            raise ManifestAttestationJoinError(
                "manifest_schema_drift",
                {"tool": name, "manifest": expected, "runtime": actual},
            )
        schema_digests[name] = actual

    return AdmissionRecord(
        manifest_digest="sha256:" + hashlib.sha256(
            json.dumps(manifest, sort_keys=True).encode()).hexdigest(),
        sbom_digest="sha256:" + hashlib.sha256(
            json.dumps(sorted(sbom_tool_names)).encode()).hexdigest(),
        attestation_digest=manifest["_attestation_digest"],
        tool_schema_digests=schema_digests,
    )
