# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-verifies-a-signed-tool-manifest-against-a-live-mcp-server-whose-capability-set-has-drifted-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-verifies-a-signed-tool-manifest-against-a-live-mcp-server-whose-capability-set-has-drifted-mid-session.warrant.json
# Markdown SHA-256:   65be95426ce51ba261a428aa1229d0bb2022244c4c11857ee6b9601de27c7ae9
# Code AST SHA-256:   5c39ddaee7a8329af1131955978710538325f9339539dae2f958c7e883088b44
# Verified Classes:   ManifestDriftError, SignedManifest
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Mapping


class ManifestDriftError(RuntimeError):
    """Raised when the live MCP server's capability surface diverges from the signed manifest."""


@dataclass(frozen=True)
class SignedManifest:
    tools: Mapping[str, str]  # tool name -> canonical digest of (name, inputSchema, description)
    valid_until: float
    signature: bytes


def canonical_digest(tool: Mapping) -> str:
    payload = json.dumps(
        {
            "name": tool["name"],
            "inputSchema": tool["inputSchema"],
            "description": tool.get("description", ""),
        },
        sort_keys=True,
        separators=(",", ":"),
    ).encode("utf-8")
    return hashlib.sha256(payload).hexdigest()


def verify_and_gate_dispatch(
    manifest: SignedManifest,
    live_tools: list[Mapping],
    requested_tool: str,
    now: float,
    signature_ok: bool,
) -> str:
    # Signature failure is the easy case: fail closed, no dispatch.
    if not signature_ok:
        raise ManifestDriftError("manifest signature invalid; refusing dispatch")
    if now > manifest.valid_until:
        raise ManifestDriftError("manifest expired; capability claim is stale")

    live = {t["name"]: canonical_digest(t) for t in live_tools}
    declared = dict(manifest.tools)

    # Set-equality, not subset: additive drift is unauthorized capability.
    added = set(live) - set(declared)
    removed = set(declared) - set(live)
    if added or removed:
        raise ManifestDriftError(
            f"capability set drift: added={sorted(added)} removed={sorted(removed)}"
        )

    # Per-tool digest: catches in-place schema/description mutation (injection).
    for name, digest in live.items():
        if digest != declared[name]:
            raise ManifestDriftError(
                f"capability digest mismatch for tool {name!r}: "
                f"declared={declared[name]} live={digest}"
            )

    # Dispatch is manifest-gated: the requested tool must be in the signed set.
    if requested_tool not in declared:
        raise ManifestDriftError(
            f"dispatch to {requested_tool!r} not authorized by signed manifest"
        )

    return live[requested_tool]
