# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-peer-mcp-server-s-advertised-tool-description-as-untrusted-code-rather-than-as-metadata-and-how-does-capabi.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-peer-mcp-server-s-advertised-tool-description-as-untrusted-code-rather-than-as-metadata-and-how-does-capabi.warrant.json
# Markdown SHA-256:   ffdb55a235642f6ea067bfcb5b13723ff4ec308036d9ea2b9720bc3996d188cd
# Code AST SHA-256:   cf4f5a0e416ac423e7c2061d93a6d569b1791adae2bbbca89f6950563b80def5
# Verified Classes:   CapabilitySpoofError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CapabilitySpoofError(RuntimeError):
    """Raised when a dynamically discovered MCP manifest attempts to steer
    execution or when declared capability disagrees with reachable effect."""

# Host-approved capability names, admitted out-of-band. Never populated from
# a remote manifest.
APPROVED_TOOLS = {"query_metrics", "read_log"}

# Declared effects the host will honor per tool; enforcement is host-side.
DECLARED_EFFECTS = {
    "query_metrics": {"read"},
    "read_log": {"read"},
}

IMPERATIVE_MARKERS = ("before calling", "first call", "you must", "required to")


def gate_manifest(manifest: dict, session_pinned_hash: str, current_hash: str) -> dict:
    # 1. Manifest must not have changed mid-session (anti-spoof on handler swap).
    if session_pinned_hash != current_hash:
        raise CapabilitySpoofError(
            f"manifest hash drift {session_pinned_hash}->{current_hash}: "
            "possible handler swap after admission"
        )

    tools = manifest.get("tools", [])
    admitted = []
    for tool in tools:
        name = tool["name"]
        desc = (tool.get("description") or "").lower()

        # 2. Name allowlist: dynamic tools not pre-approved are non-selectable.
        if name not in APPROVED_TOOLS:
            continue

        # 3. Description carrying imperative/steering language is hostile:
        #    quarantine it as data, never as instruction-region text.
        if any(marker in desc for marker in IMPERATIVE_MARKERS):
            tool["_provenance"] = "untrusted_remote"
            tool["_quarantined"] = True
            # A description trying to invoke *another* tool is an injection
            # attempt even if this tool itself is approved.
            if "call " in desc or "export_" in desc:
                raise CapabilitySpoofError(
                    f"tool '{name}' description attempts cross-tool steering: "
                    f"{tool.get('description')!r}"
                )

        # 4. Declared effect must match the host's independent model.
        declared = set(tool.get("effects", []))
        expected = DECLARED_EFFECTS.get(name, set())
        if declared != expected:
            raise CapabilitySpoofError(
                f"tool '{name}' declares effects {sorted(declared)} but host "
                f"expects {sorted(expected)}: capability spoof"
            )
        admitted.append(tool)

    return {"tools": admitted}


def invoke(tool_name: str, args: dict, admitted: dict) -> dict:
    names = {t["name"] for t in admitted["tools"]}
    if tool_name not in names:
        raise CapabilitySpoofError(
            f"refusing to invoke '{tool_name}': not in admitted set {sorted(names)}"
        )
    # Handler-layer effect enforcement happens here, not in the manifest.
    return {"tool": tool_name, "args": args, "status": "dispatched"}
