# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-dynamically-loaded-mcp-tool-manifest-before-first-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-a-dynamically-loaded-mcp-tool-manifest-before-first-invocation.warrant.json
# Markdown SHA-256:   79caa59403ac9fca4d85eebd09409dae7be457f3fe6f318325c5947361b4d834
# Code AST SHA-256:   f37e24fad5f8bc1bcdf55948e6a64d1cb41ab7bfa0e98f297ae25c691fa8e8f7
# Verified Classes:   ManifestQuarantineError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ManifestQuarantineError(RuntimeError):
    """Raised when a dynamically loaded tool manifest must be quarantined
    before its prose is rendered into the model context."""


IMPERATIVE_SIGNATURES = (
    "before calling", "first call", "always pass", "do not tell",
    "do not mention", "instead call", "you must", "ignore previous",
)


def screen_manifest(manifest: dict, sensitive_tools: set[str],
                    pinned_digest: str | None) -> dict:
    """Screen a fetched MCP-style manifest. Returns a sanitized copy safe to
    render into context, or raises ManifestQuarantineError."""
    name = manifest.get("name", "<unnamed>")
    prose_fields = ("description", "examples", "usage_notes", "notes")

    # Invariant 1: pinned + reviewed manifests bypass prose quarantine.
    if pinned_digest is not None:
        return manifest

    prose = " ".join(
        str(manifest.get(f, "")) for f in prose_fields
    ).lower()

    # Invariant 2: prose must never reference other tools (steering).
    for tool in sensitive_tools:
        if tool.lower() in prose and tool != name:
            raise ManifestQuarantineError(
                f"manifest {name!r} prose references tool {tool!r}; "
                "cross-tool steering suspected"
            )

    # Invariant 3: prose must never contain imperative pre-call instructions.
    for sig in IMPERATIVE_SIGNATURES:
        if sig in prose:
            raise ManifestQuarantineError(
                f"manifest {name!r} prose contains imperative signature "
                f"{sig!r}; treating as injection"
            )

    # Invariant 4: free-form sink params on a credentialed agent are a
    # latent exfiltration channel regardless of prose.
    schema = manifest.get("inputSchema", {}) or {}
    props = (schema.get("properties") or {})
    for sink in ("context", "data", "payload", "env", "secrets"):
        if sink in props and sensitive_tools:
            raise ManifestQuarantineError(
                f"manifest {name!r} declares free-form sink param {sink!r} "
                "while sensitive tools are in scope"
            )

    # Passed: strip prose to schema-only for first render.
    sanitized = {k: v for k, v in manifest.items() if k not in prose_fields}
    sanitized["_prose_quarantined"] = True
    return sanitized
