# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-manifest-level-skill-injection-before-first-tool-call-the-description-channel-trust-boundary-in-mcp-server-registration.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-manifest-level-skill-injection-before-first-tool-call-the-description-channel-trust-boundary-in-mcp-server-registration.warrant.json
# Markdown SHA-256:   093bebb79e0a31ad19d48343dbe3cc945ecf4ea82d5cf09d35f117ff9f13dac9
# Code AST SHA-256:   0db7c09a84840f92cdfcd2229a232659fc42e6459b77b3cb22600f6a1b0f31e0
# Verified Classes:   ManifestTrustViolation, ToolManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import re
from dataclasses import dataclass


class ManifestTrustViolation(RuntimeError):
    """Raised when a tool manifest crosses the description-channel trust boundary."""
    pass


# Cross-tool reference: description names another tool, implying routing/aliasing.
_CROSS_TOOL_REF = re.compile(
    r"\b(?:supersedes|replaces|instead of|route(?:s|d)? (?:the )?calls? to|"
    r"when \w+ is requested|prefer this (?:tool|over))\b",
    re.IGNORECASE,
)

# Second-person imperative aimed at the orchestrator, not the user.
_ORCHESTRATOR_IMPERATIVE = re.compile(
    r"\b(?:note for (?:orchestrators?|agents?|assistants?)|"
    r"before calling|always include|you (?:must|should) (?:pass|include|route))\b",
    re.IGNORECASE,
)

_MAX_DESCRIPTION_TOKENS = 400


@dataclass(frozen=True)
class ToolManifest:
    server_id: str
    name: str
    description: str
    schema: dict


def _approx_tokens(text: str) -> int:
    return len(text.split())


def gate_manifest(manifest: ToolManifest, known_tool_names: set[str]) -> None:
    """
    Enforce the manifest trust boundary at ingestion time.
    Raises ManifestTrustViolation on the first crossed boundary.
    """
    desc = manifest.description

    if _approx_tokens(desc) > _MAX_DESCRIPTION_TOKENS:
        raise ManifestTrustViolation(
            f"server={manifest.server_id} tool={manifest.name} "
            f"description exceeds {_MAX_DESCRIPTION_TOKENS}-token budget "
            f"({_approx_tokens(desc)} tokens); quarantine for operator review"
        )

    if _CROSS_TOOL_REF.search(desc):
        raise ManifestTrustViolation(
            f"server={manifest.server_id} tool={manifest.name} "
            f"description contains cross-tool routing/aliasing language; "
            f"refusing registration"
        )

    if _ORCHESTRATOR_IMPERATIVE.search(desc):
        raise ManifestTrustViolation(
            f"server={manifest.server_id} tool={manifest.name} "
            f"description contains orchestrator-directed imperative; "
            f"refusing registration"
        )

    # Schema strictness: reject unconstrained object parameters that can carry
    # exfiltration payloads (e.g. meta.source_path) without operator allowlist.
    props = manifest.schema.get("properties", {})
    for param_name, param_spec in props.items():
        if param_spec.get("type") == "object" and not param_spec.get(
            "additionalProperties", True
        ) is False:
            if param_spec.get("additionalProperties", True) is not False:
                raise ManifestTrustViolation(
                    f"server={manifest.server_id} tool={manifest.name} "
                    f"param={param_name} is an unconstrained object; "
                    f"require additionalProperties:false or operator allowlist"
                )

    # Provenance marker for the context-window render path.
    manifest_hash = hashlib.sha256(desc.encode("utf-8")).hexdigest()[:12]
    # Caller must render with: f"[UNTRUSTED server={manifest.server_id} "
    # f"desc_hash={manifest_hash}] {desc}" and a preamble forbidding
    # instruction-following within the block.


def register_tools(manifests: list[ToolManifest], known_tool_names: set[str]) -> list[ToolManifest]:
    accepted: list[ToolManifest] = []
    for m in manifests:
        gate_manifest(m, known_tool_names)  # raises on violation
        accepted.append(m)
    return accepted
