# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-a-tool-manifest-s-declared-capability-surface-after-an-mcp-server-s-tools-list-response-diverges-from.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-distrust-a-tool-manifest-s-declared-capability-surface-after-an-mcp-server-s-tools-list-response-diverges-from.warrant.json
# Markdown SHA-256:   73dccc848785dde98687f06e016ad169a20a6cf087844a79cc159b8ab4122956
# Code AST SHA-256:   ab4a6a03de83d005ebab0773902538864fb39ee6e11cea668502d730febd7406
# Verified Classes:   CapabilitySurfaceViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import json
from typing import Any

class CapabilitySurfaceViolation(RuntimeError):
    """Live tools/list surface is broader than the signed descriptor."""
    pass

def _schema_subsumes(signed: dict[str, Any], live: dict[str, Any]) -> bool:
    # Live schema must be equal to or strictly narrower than signed.
    s_props = signed.get("properties", {})
    l_props = live.get("properties", {})
    for name, l_spec in l_props.items():
        if name not in s_props:
            return False  # added parameter -> widening
        s_spec = s_props[name]
        # a relaxed or dropped constraint is widening
        if "pattern" in s_spec and s_spec["pattern"] != l_spec.get("pattern"):
            return False
        if "enum" in s_spec and not set(l_spec.get("enum", [])).issubset(set(s_spec["enum"])):
            return False
        if "maximum" in s_spec and l_spec.get("maximum", s_spec["maximum"]) > s_spec["maximum"]:
            return False
    return True

def verify_manifest(signed_descriptor: dict[str, Any], live_list: dict[str, Any]) -> None:
    signed_tools = {t["name"]: t for t in signed_descriptor["tools"]}
    for live_tool in live_list.get("tools", []):
        name = live_tool["name"]
        if name not in signed_tools:
            raise CapabilitySurfaceViolation(
                f"tool {name!r} present in live manifest but absent from signed descriptor"
            )
        if not _schema_subsumes(signed_tools[name]["inputSchema"], live_tool.get("inputSchema", {})):
            raise CapabilitySurfaceViolation(
                f"tool {name!r} live schema widens signed capability surface"
            )
        signed_scope = signed_tools[name].get("scope")
        live_scope = live_tool.get("scope", signed_scope)
        if signed_scope is not None and live_scope != signed_scope:
            raise CapabilitySurfaceViolation(
                f"tool {name!r} live scope {live_scope!r} diverges from signed {signed_scope!r}"
            )
