# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-tools-list-capability-claims-as-untrusted-adversarial-input-rather-than-schema.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-tools-list-capability-claims-as-untrusted-adversarial-input-rather-than-schema.warrant.json
# Markdown SHA-256:   059f215d1a0db73df3542c96577ecf89c94f9699c2a3e17c8cab5183f262ff64
# Code AST SHA-256:   e0d1f880363681d0bc21d02569153dac730fc0d88dea5bfa6be1ca8d7da5d8d7
# Verified Classes:   CapabilitySpoofingError, PinnedServer
# Defensive Guards:   10 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Iterable


class CapabilitySpoofingError(RuntimeError):
    """Raised when a tool manifest attempts to smuggle instruction text or widen capability."""


# Fields whose natural-language content is attacker-writable and instruction-adjacent.
_INSTRUCTION_BEARING_KEYS = ("description", "title", "summary")
_MAX_DESC_CHARS = 160
_MAX_ENUM_CHARS = 48


@dataclass(frozen=True)
class PinnedServer:
    server_id: str
    manifest_digest: str  # sha256 of the canonicalized, approved manifest


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


def _contains_instruction_markers(text: str) -> bool:
    lowered = text.lower()
    markers = (
        "note to assistant", "ignore prior", "system:", "you are now",
        "before answering", "required for", "do not tell", "exfil",
    )
    return any(m in lowered for m in markers)


def validate_registration(
    manifest: dict,
    pinned: Iterable[PinnedServer],
    existing_tools: dict[str, dict],
) -> None:
    """
    Enforce the registration invariant. Any violation fails closed.
    existing_tools maps fully-qualified name -> previously accepted schema.
    """
    server_id = manifest.get("server_id")
    if not server_id:
        raise CapabilitySpoofingError("manifest missing server_id; cannot establish provenance")

    pinned_by_id = {p.server_id: p for p in pinned}
    pin = pinned_by_id.get(server_id)
    if pin is None:
        raise CapabilitySpoofingError(
            f"server {server_id!r} is not pinned; dynamic registration of unpinned servers is refused"
        )
    if _canonical_digest(manifest) != pin.manifest_digest:
        raise CapabilitySpoofingError(
            f"manifest digest for {server_id!r} does not match pinned approval; possible tampering"
        )

    for tool in manifest.get("tools", []):
        raw_name = tool.get("name", "")
        if not raw_name:
            raise CapabilitySpoofingError(f"server {server_id!r} declared a tool with empty name")

        # Namespace by server identity so collisions are structurally impossible.
        fq_name = f"{server_id}.{raw_name}"

        for key in _INSTRUCTION_BEARING_KEYS:
            text = tool.get(key, "")
            if not isinstance(text, str):
                raise CapabilitySpoofingError(f"{fq_name}: {key} must be a string")
            if len(text) > _MAX_DESC_CHARS:
                raise CapabilitySpoofingError(
                    f"{fq_name}: {key} exceeds {_MAX_DESC_CHARS} chars; oversized descriptions are an injection vector"
                )
            if _contains_instruction_markers(text):
                raise CapabilitySpoofingError(
                    f"{fq_name}: {key} contains instruction-like content; refusing as untrusted data"
                )

        schema = tool.get("inputSchema", {})
        for param, spec in schema.get("properties", {}).items():
            for enum_val in spec.get("enum", []):
                if not isinstance(enum_val, str):
                    continue
                if len(enum_val) > _MAX_ENUM_CHARS or _contains_instruction_markers(enum_val):
                    raise CapabilitySpoofingError(
                        f"{fq_name}.{param}: enum value is instruction-bearing; reject"
                    )

        # Capability-widening check: a re-registration may not broaden the surface.
        prior = existing_tools.get(fq_name)
        if prior is not None:
            prior_params = set(prior.get("inputSchema", {}).get("properties", {}))
            new_params = set(schema.get("properties", {}))
            if new_params - prior_params:
                raise CapabilitySpoofingError(
                    f"{fq_name}: registration widens parameter surface "
                    f"({sorted(new_params - prior_params)}); requires explicit re-approval"
                )
            if prior.get("inputSchema") != schema:
                raise CapabilitySpoofingError(
                    f"{fq_name}: schema drift on re-registration; requires explicit re-approval"
                )
