# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-re-signed-mcp-tool-manifest-whose-declared-version-pin-matches-but-whose-capability-surface-has-silently-widened.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-re-signed-mcp-tool-manifest-whose-declared-version-pin-matches-but-whose-capability-surface-has-silently-widened.warrant.json
# Markdown SHA-256:   54c11724176019f87479224ce8fb73ff38db712149e879ac8116bb3d702ead7a
# Code AST SHA-256:   cec6140664296a2a65bc7d016608066664514936af2df46227abea33a3908631
# Verified Classes:   CapabilityDriftError, Pin
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CapabilityDriftError(RuntimeError):
    """Raised when a served MCP tool surface diverges from the pinned digest
    under a valid signature and matching version string."""


@dataclass(frozen=True)
class Pin:
    publisher_key: str
    version: str
    capability_digest: str


def capability_digest(tools: list[dict]) -> str:
    # Canonicalize: sort by name, drop volatile fields, stable key order.
    canon = sorted(
        (
            {
                "name": t["name"],
                "inputSchema": t.get("inputSchema", {}),
                "scopes": sorted(t.get("scopes", [])),
            }
            for t in tools
        ),
        key=lambda t: t["name"],
    )
    blob = json.dumps(canon, sort_keys=True, separators=(",", ":")).encode()
    return "sha256:" + hashlib.sha256(blob).hexdigest()


def resolve_server(
    manifest: dict,
    served_tools: list[dict],
    pin: Pin,
    verify_signature,
) -> None:
    # Identity check: signature must chain to the pinned publisher key.
    if not verify_signature(manifest, pin.publisher_key):
        raise CapabilityDriftError(
            f"manifest signature invalid for publisher {pin.publisher_key}"
        )

    # Version check is necessary but NOT sufficient. Do not return here.
    if manifest.get("version") != pin.version:
        raise CapabilityDriftError(
            f"version mismatch: manifest={manifest.get('version')} pin={pin.version}"
        )

    # Behavior check: recompute the digest of the SERVED surface on every
    # resolution. A valid re-signed manifest at the same version can still
    # carry a widened capability surface.
    served = capability_digest(served_tools)
    if served != pin.capability_digest:
        raise CapabilityDriftError(
            "capability drift under stable identity: "
            f"served={served} pinned={pin.capability_digest} "
            f"version={pin.version} publisher={pin.publisher_key}"
        )
