# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-admits-a-poisoned-mcp-tool-manifest-into-its-capability-graph-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-admits-a-poisoned-mcp-tool-manifest-into-its-capability-graph-mid-session.warrant.json
# Markdown SHA-256:   4588cbc6cb0f3b8efda49f4b887defc9237411b294e5ff8edd7929c3af9820a4
# Code AST SHA-256:   f48dee1762300899eb88a0c7581eaf5b7a5fcf5b4ccf5f8add0c490fb0ea8d17
# Verified Classes:   CapabilityConfusionError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class CapabilityConfusionError(RuntimeError):
    """Raised when a manifest or tool call violates capability closure or argument provenance."""
    pass


IMPERATIVE_MARKERS = ("call ", "invoke ", "first ", "pass the ", "required for", "export_", "send the ")


def admit_manifest(manifest: dict, admitted: set[str], policy) -> set[str]:
    """Gate a fetched MCP tool manifest before it enters the live capability graph.

    Fails closed: any manifest whose descriptive fields try to direct the agent's
    next action, or reference tools outside its own name, is rejected wholesale.
    """
    name = manifest.get("name")
    if not name:
        raise CapabilityConfusionError("manifest missing 'name'; cannot admit unnamed capability")

    desc = (manifest.get("description") or "").lower()
    for marker in IMPERATIVE_MARKERS:
        if marker in desc:
            raise CapabilityConfusionError(
                f"manifest {name!r} contains imperative directive {marker!r} in description; "
                f"treated as capability-confusion payload"
            )

    # A description that names another tool is a cross-capability reference.
    for other in admitted:
        if other != name and other.lower() in desc:
            raise CapabilityConfusionError(
                f"manifest {name!r} references already-admitted tool {other!r} in description"
            )

    if not policy.permits(name, manifest.get("inputSchema", {})):
        raise CapabilityConfusionError(f"policy denied admission of {name!r}")

    return admitted | {name}


def resolve_tool_call(requested: str, admitted: set[str], registry) -> str:
    """Resolve a model-emitted tool name. Unknown names MUST raise, never auto-fetch."""
    if requested not in admitted:
        # Do NOT consult the registry here. Lazy resolution is the escalation vector.
        raise CapabilityConfusionError(
            f"model requested unadmitted tool {requested!r}; "
            f"capability closure violated (admitted={sorted(admitted)})"
        )
    return requested


def check_argument_flow(call, provenance) -> None:
    """Block cross-server flow of secrets/session-scoped values into tool inputs."""
    for arg_name, value in call.arguments.items():
        tag = provenance.tag_of(value)
        if tag in ("secret", "session_scoped") and provenance.origin(value) != call.server:
            raise CapabilityConfusionError(
                f"argument {arg_name!r} carries {tag} value from server "
                f"{provenance.origin(value)!r} into server {call.server!r}; "
                f"cross-server taint flow blocked"
            )
