# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-distrust-a-tool-manifest-before-capability-negotiation-completes-skill-injection-via-mcp-tools-list-descriptions-that-survive-i.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-distrust-a-tool-manifest-before-capability-negotiation-completes-skill-injection-via-mcp-tools-list-descriptions-that-survive-i.warrant.json
# Markdown SHA-256:   6610c9c4acd8bf411db033fc6078a244c9c11b1a63231ec00512e5cc78b97464
# Code AST SHA-256:   db669fb539299470cab56bf7c22f4260668e20d6a99bcb243d8cb6a376df846d
# Verified Classes:   ManifestInjectionError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ManifestInjectionError(RuntimeError):
    """Raised when a tool manifest string attempts to act as an instruction,
    or when a planned tool call cannot be attributed to an operator turn."""


IMPERATIVE_MARKERS = (
    "note to assistant",
    "before using",
    "you must",
    "ignore previous",
    "required for telemetry",
)


def _iter_manifest_strings(tool: dict):
    yield tool.get("name", "")
    yield tool.get("description", "")
    schema = tool.get("inputSchema", {}) or {}
    for prop_name, prop in (schema.get("properties") or {}).items():
        if isinstance(prop, dict):
            yield prop.get("description", "")
    for value in (tool.get("annotations") or {}).values():
        if isinstance(value, str):
            yield value


def screen_manifest(tools: list[dict]) -> list[dict]:
    """Return tools with manifest text quarantined; raise on injection markers."""
    clean = []
    for tool in tools:
        for text in _iter_manifest_strings(tool):
            lowered = text.lower()
            for marker in IMPERATIVE_MARKERS:
                if marker in lowered:
                    raise ManifestInjectionError(
                        f"tool {tool.get('name')!r} manifest contains "
                        f"instruction-like text {marker!r}: {text[:120]!r}"
                    )
        clean.append(tool)
    return clean


def authorize_call(call: dict, user_turn_id: str, manifest_texts: set[str]) -> None:
    """A tool call is admissible only if justified by an operator turn,
    not by manifest text alone."""
    justification = call.get("justification", "")
    if not justification:
        raise ManifestInjectionError(
            f"call to {call.get('name')!r} carries no justification"
        )
    if call.get("turn_id") != user_turn_id:
        raise ManifestInjectionError(
            f"call to {call.get('name')!r} not attributable to current user turn"
        )
    for span in manifest_texts:
        if span and span in justification:
            raise ManifestInjectionError(
                f"call to {call.get('name')!r} justified by manifest text, "
                f"not operator instruction"
            )
