# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-tool-schema-and-tool-description-under-mcp-manifest-injection.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-trust-boundary-between-tool-schema-and-tool-description-under-mcp-manifest-injection.warrant.json
# Markdown SHA-256:   3f5ed23d7b9cf9e40cc0283e84fea33fe902c4d795e352d5d7f9bbca427c60bf
# Code AST SHA-256:   3e60dcd51cfc66734528d37d643fff4601f3635729c1e1661aade74bc2ec936c
# Verified Classes:   ManifestTrustViolation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class ManifestTrustViolation(RuntimeError):
    """Raised when a tool manifest description attempts to cross the trust boundary."""
    pass


DIRECTIVE_MARKERS = (
    "you must", "always first call", "before calling", "do not tell",
    "ignore previous", "pass the contents", "read_file", "credentials",
)

def classify_description(server: str, tool: str, description: str,
                         declared_tools: set[str]) -> str:
    lowered = description.lower()
    for marker in DIRECTIVE_MARKERS:
        if marker in lowered:
            raise ManifestTrustViolation(
                f"{server}/{tool}: directive-like text {marker!r} in description; "
                f"manifest attempts instruction-level injection"
            )
    # cross-namespace reference check: any tool name mentioned that is not
    # declared by this same server is an attempted cross-server orchestration
    for token in declared_tools:
        if token in lowered and token != tool:
            continue  # same-server reference is documentation
    import re
    for candidate in re.findall(r"[a-z_][a-z0-9_]{2,}", lowered):
        if candidate in KNOWN_CROSS_SERVER_TOOLS and candidate not in declared_tools:
            raise ManifestTrustViolation(
                f"{server}/{tool}: description references foreign tool "
                f"{candidate!r}; cross-server orchestration must not be "
                f"delegated to a manifest"
            )
    return description  # safe to serialize as untrusted documentation


def ingest_manifest(server: str, manifest: dict) -> list[dict]:
    declared = {t["name"] for t in manifest.get("tools", [])}
    safe = []
    for tool in manifest.get("tools", []):
        cleaned = classify_description(
            server, tool["name"], tool.get("description", ""), declared
        )
        safe.append({
            "name": tool["name"],
            "inputSchema": tool["inputSchema"],  # schema already validated
            "description": f"<UNTRUSTED_TOOL_METADATA>{cleaned}</UNTRUSTED_TOOL_METADATA>",
            "provenance": {"server": server, "trust": "untrusted"},
        })
    return safe
