# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-signed-mcp-manifest-has-been-silently-re-scoped-at-runtime-capability-narrowing-drift-under-tool-poisoning-defense.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-signed-mcp-manifest-has-been-silently-re-scoped-at-runtime-capability-narrowing-drift-under-tool-poisoning-defense.warrant.json
# Markdown SHA-256:   eb111363ecddcdbe5ef6e31a40f22daff50a51042e47cef21c4178d4b65f18da
# Code AST SHA-256:   3e0191dd943e646bcf05a1abfa88993103e748b213c704d1313a90489e027a0d
# Verified Classes:   CapabilityNarrowingDrift, SignedTool, AdvertisedTool
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CapabilityNarrowingDrift(RuntimeError):
    """Raised when a signed MCP tool's runtime advertisement widens or
    laterally rewrites its semantic surface under a stable tool name."""
    pass


@dataclass(frozen=True)
class SignedTool:
    name: str
    input_schema: dict
    description: str

    def semantic_hash(self) -> str:
        payload = json.dumps(
            {"schema": self.input_schema, "desc": self.description},
            sort_keys=True,
            separators=(",", ":"),
        ).encode()
        return hashlib.sha256(payload).hexdigest()


@dataclass(frozen=True)
class AdvertisedTool:
    name: str
    input_schema: dict
    description: str

    def semantic_hash(self) -> str:
        payload = json.dumps(
            {"schema": self.input_schema, "desc": self.description},
            sort_keys=True,
            separators=(",", ":"),
        ).encode()
        return hashlib.sha256(payload).hexdigest()


def _is_narrowing(signed: SignedTool, advertised: AdvertisedTool) -> bool:
    """Narrowing is permitted only if the advertised schema is a strict
    capability subset: no new properties, no raised defaults, no relaxed
    additionalProperties, and no imperative description rewrite."""
    signed_props = set(signed.input_schema.get("properties", {}))
    adv_props = set(advertised.input_schema.get("properties", {}))
    if not adv_props.issubset(signed_props):
        return False
    if advertised.input_schema.get("additionalProperties", False) and not \
            signed.input_schema.get("additionalProperties", False):
        return False
    for prop, spec in advertised.input_schema.get("properties", {}).items():
        signed_spec = signed.input_schema["properties"].get(prop, {})
        if "default" in spec and "default" in signed_spec:
            if spec["default"] != signed_spec["default"]:
                return False
    if advertised.description != signed.description:
        # Any description change is treated as widening unless the runtime
        # has an explicit signed allowlist of revisions.
        return False
    return True


def verify_advertisement(
    signed: SignedTool, advertised: AdvertisedTool
) -> None:
    if advertised.name != signed.name:
        raise CapabilityNarrowingDrift(
            f"tool name drift: signed={signed.name!r} advertised={advertised.name!r}"
        )
    if advertised.semantic_hash() == signed.semantic_hash():
        return  # exact match, permit and cache
    if _is_narrowing(signed, advertised):
        return  # strict subset, permit with recorded delta
    raise CapabilityNarrowingDrift(
        "semantic surface widened or rewritten under stable name "
        f"{signed.name!r}: signed_hash={signed.semantic_hash()[:12]} "
        f"advertised_hash={advertised.semantic_hash()[:12]}"
    )


def validate_call_against_signed(
    signed: SignedTool, params: dict
) -> None:
    """Per-call validation must use the SIGNED schema, not the advertisement,
    so properties introduced only in the mutated advertisement are rejected."""
    allowed = set(signed.input_schema.get("properties", {}))
    extra = set(params) - allowed
    if extra:
        raise CapabilityNarrowingDrift(
            f"call to {signed.name!r} used unsigned parameters: {sorted(extra)}"
        )
