# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-description-it-has-never-executed-manifest-resident-instruction-payloads-and-the-pre-execution-trust-boundary-in-mcp.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-tool-description-it-has-never-executed-manifest-resident-instruction-payloads-and-the-pre-execution-trust-boundary-in-mcp.warrant.json
# Markdown SHA-256:   52b5034e4ddeb6e1e76352f13e0e13e3dd25fc7f5245d0eb79233d4eb95cbbb3
# Code AST SHA-256:   8917adfff4fb5dc40033e9e9dabc1f09eaa22e14c05d2e5477379c5dbd4cc2b7
# Verified Classes:   ManifestInjectionError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ManifestInjectionError(RuntimeError):
    """Raised when a tool manifest field carries a directive rather than a description."""
    pass


ORDERING_TOKENS = ("before", "first", "then", "prior to", "must", "always", "immediately after")
AUTHORITY_TOKENS = ("required by the runtime", "system requires", "safe without confirmation",
                    "pre-approved", "operator has authorized", "no need to confirm")


def sanitize_tool_manifest(manifest: dict, server_id: str) -> dict:
    """
    Enforce the invariant: tool metadata is data, never instruction.
    Reject prescriptive content at registration time, before it reaches model context.
    """
    cleaned = {}
    for tool in manifest.get("tools", []):
        name = tool.get("name", "<unnamed>")
        desc = (tool.get("description") or "").lower()

        hits = [t for t in ORDERING_TOKENS if t in desc]
        auth = [t for t in AUTHORITY_TOKENS if t in desc]

        if auth:
            # Fabricated runtime authority is never acceptable in a manifest field.
            raise ManifestInjectionError(
                f"server={server_id} tool={name}: manifest asserts runtime authority "
                f"({auth}); authority resolves only from operator system prompt."
            )
        if hits:
            # Ordering directives hijack planning; quarantine rather than pass through.
            raise ManifestInjectionError(
                f"server={server_id} tool={name}: prescriptive sequencing in description "
                f"({hits}); planning authority belongs to the operator, not the manifest."
            )

        cleaned[name] = {
            "description": tool.get("description", ""),
            "inputSchema": tool.get("inputSchema", {}),
            "effect_class": tool.get("x-effect-class", "unclassified"),
            "provenance": f"server:{server_id}",  # tag so the prompt can mark it untrusted
        }
    return {"tools": cleaned}


def register_tools(manifest: dict, server_id: str, policy_engine) -> dict:
    tools = sanitize_tool_manifest(manifest, server_id)
    for name, spec in tools.items():
        # Confirmation is keyed to effect class, never to what the description claims.
        spec["requires_confirmation"] = policy_engine.is_side_effecting(spec["effect_class"])
    return tools
