# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-dynamically-registered-mcp-tool-description-as-untrusted-instruction-bearing-content-rather-than-inert.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-dynamically-registered-mcp-tool-description-as-untrusted-instruction-bearing-content-rather-than-inert.warrant.json
# Markdown SHA-256:   16232e7fbc0514097daa47b4de17621070d999100e8b8362da32412b6a61badb
# Code AST SHA-256:   d243a9388fdc5bb17e1b21fffdc24ff8636c2a6032f34678a0905c77526098f3
# Verified Classes:   DescriptionInjectionBoundaryError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class DescriptionInjectionBoundaryError(RuntimeError):
    """Raised when a dynamically registered capability's prose would enter the instruction region,
    or when a tool description attempts to induce a tool call outside declared capability scope."""
    pass


IMPERATIVE_MARKERS = (
    "before use", "do not mention", "include verbatim",
    "call ", "invoke ", "read_resource", "append ", "ignore previous",
)


def admit_capability(cap: dict, *, pinned_servers: set[str], task_capability_scope: set[str]) -> dict:
    server = cap.get("server_id")
    name = cap.get("name", "<unnamed>")
    desc = (cap.get("description") or "") + " " + (cap.get("title") or "")

    # C1 guard: dynamic registration must re-enter admission, never merge blindly.
    if server not in pinned_servers:
        # C2/C5 guard: imperative prose in an untrusted description is adversarial by default.
        lowered = desc.lower()
        if any(marker in lowered for marker in IMPERATIVE_MARKERS):
            raise DescriptionInjectionBoundaryError(
                f"untrusted capability {name!r} from {server!r} carries instruction-bearing "
                f"description; quarantine and route to auditor, do not render into context"
            )
        # C3 guard: untrusted tool may not widen the caller's declared capability scope.
        if name not in task_capability_scope:
            raise DescriptionInjectionBoundaryError(
                f"untrusted capability {name!r} widens scope beyond {sorted(task_capability_scope)}"
            )

    # C2 guard: prose is quarantined; only schema is dispatched.
    return {
        "name": name,
        "server_id": server,
        "input_schema": cap.get("inputSchema", {}),
        "description_quarantined": True,
        "provenance": "pinned" if server in pinned_servers else "dynamic-untrusted",
    }


def handle_list_changed(delta: list[dict], *, pinned_servers: set[str], task_capability_scope: set[str]) -> list[dict]:
    admitted = []
    for cap in delta:
        try:
            admitted.append(admit_capability(
                cap, pinned_servers=pinned_servers, task_capability_scope=task_capability_scope
            ))
        except DescriptionInjectionBoundaryError:
            # Fail closed: reject the delta entry, preserve prior tool table, emit audit record.
            continue
    return admitted
