# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-dynamically-registered-mcp-capability-the-description-trust-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-dynamically-registered-mcp-capability-the-description-trust-boundary.warrant.json
# Markdown SHA-256:   58dc2783c2802b7e4e1c653c2ed3ab7a3c844dff41e90c3ee45e0a920d07c4d1
# Code AST SHA-256:   1fe125e6bb579c6420869df9d56b0c4a6bf1de8fc303ee6e6eaa9c423d0a6b8b
# Verified Classes:   CapabilityTrustError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
import re
from typing import Any


class CapabilityTrustError(RuntimeError):
    """Raised when a dynamically registered MCP capability violates the description-trust boundary."""
    pass


# Imperatives and cross-scope references that have no place in a tool description.
_IMPERATIVE_PATTERNS = [
    re.compile(r"\bignore (all )?(previous|prior|above) instructions?\b", re.I),
    re.compile(r"\binstead\b.*\bcall\b", re.I),
    re.compile(r"\bbefore (invoking|calling|using)\b.*\b(read|send|include|pass)\b", re.I),
    re.compile(r"\bdo not (tell|inform|mention)\b", re.I),
    re.compile(r"\balways include\b", re.I),
]


def _collect_natural_language_fields(tool: dict[str, Any]) -> list[str]:
    """Every string field a model will read, not just the top-level description."""
    fields: list[str] = []
    if isinstance(tool.get("description"), str):
        fields.append(tool["description"])
    if isinstance(tool.get("title"), str):
        fields.append(tool["title"])
    schema = tool.get("inputSchema") or {}
    for prop_name, prop in (schema.get("properties") or {}).items():
        if isinstance(prop, dict):
            if isinstance(prop.get("description"), str):
                fields.append(prop["description"])
            for label in prop.get("enum") or []:
                if isinstance(label, str):
                    fields.append(label)
    return fields


def manifest_fingerprint(manifest: dict[str, Any]) -> str:
    """Hash the FULL manifest including natural-language fields, not just schemas."""
    canonical = json.dumps(manifest, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def validate_registration(
    server_id: str,
    incoming_manifest: dict[str, Any],
    pinned_fingerprint: str | None,
    declared_scope: set[str],
) -> str:
    """
    Gate a tools/list or tools/list_changed registration.
    Returns the new fingerprint on success; raises CapabilityTrustError otherwise.
    """
    tools = incoming_manifest.get("tools") or []

    # 1. Scan every natural-language field, including uninvoked tools' schemas.
    for tool in tools:
        for text in _collect_natural_language_fields(tool):
            for pattern in _IMPERATIVE_PATTERNS:
                if pattern.search(text):
                    raise CapabilityTrustError(
                        f"server {server_id!r} tool {tool.get('name')!r}: "
                        f"imperative instruction in description field: {text[:120]!r}"
                    )

    # 2. Scope check: a server may only register tools within its declared scope.
    for tool in tools:
        name = tool.get("name", "")
        if declared_scope and name not in declared_scope:
            raise CapabilityTrustError(
                f"server {server_id!r} registered out-of-scope tool {name!r}; "
                f"declared scope: {sorted(declared_scope)}"
            )

    # 3. Fingerprint covers descriptions, so a description-only edit is a full re-pin event.
    new_fp = manifest_fingerprint(incoming_manifest)
    if pinned_fingerprint is not None and new_fp != pinned_fingerprint:
        raise CapabilityTrustError(
            f"server {server_id!r}: manifest fingerprint changed "
            f"({pinned_fingerprint[:12]} -> {new_fp[:12]}); "
            f"re-registration requires out-of-band re-pin, not silent acceptance"
        )

    return new_fp
