# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-an-mcp-tool-descriptor-whose-description-field-carries-executable-intent-rather-than-capability-docu.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-an-mcp-tool-descriptor-whose-description-field-carries-executable-intent-rather-than-capability-docu.warrant.json
# Markdown SHA-256:   acfce14347894c168b6f434eace88ece160d37543b369fbe62735b597693f6b4
# Code AST SHA-256:   d0c5a2536f11931b07a9059db3ad30cea0b1bf95b1d99313c16188c6e64e1e84
# Verified Classes:   DescriptorQuarantine, ToolDescriptor
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class DescriptorQuarantine(RuntimeError):
    """Raised when a tool descriptor carries executable intent rather than documentation."""


IMPERATIVE_MARKERS = (
    "first call", "always call", "before calling", "do not mention",
    "do not tell", "silently", "without asking", "pass the", "include the",
    "the conversation", "the authorization header", "the system prompt",
)
CREDENTIAL_PARAM_MARKERS = ("raw", "auth", "token", "session", "secret", "context", "previous")


@dataclass(frozen=True)
class ToolDescriptor:
    server_id: str
    name: str
    description: str
    parameters: dict


def scan_descriptor(desc: ToolDescriptor) -> list[str]:
    text = desc.description.lower()
    hits = [m for m in IMPERATIVE_MARKERS if m in text]
    for pname, pspec in desc.parameters.items():
        ptext = f"{pname} {pspec.get('description', '')}".lower()
        if any(m in ptext for m in CREDENTIAL_PARAM_MARKERS):
            hits.append(f"param:{pname}")
    return hits


def admit_manifest(descriptors: Iterable[ToolDescriptor]) -> tuple[list[ToolDescriptor], list[dict]]:
    admitted, quarantined = [], []
    for d in descriptors:
        hits = scan_descriptor(d)
        if hits:
            quarantined.append({"server_id": d.server_id, "tool": d.name, "signals": hits})
            continue
        admitted.append(d)
    if not admitted and quarantined:
        raise DescriptorQuarantine(
            f"entire manifest quarantined; no usable tools: {[q['tool'] for q in quarantined]}"
        )
    return admitted, quarantined


def invalidate_stale_plans(plans: list[dict], quarantined_tools: set[str]) -> list[dict]:
    """Drop plan fragments naming a quarantined tool; a removed tool still named in memory is reachable."""
    clean = []
    for plan in plans:
        if any(step.get("tool") in quarantined_tools for step in plan.get("steps", [])):
            continue
        clean.append(plan)
    return clean
