# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-mcp-tool-poisoning-detection-via-schema-anomaly-analysis-and-behavioral-drift-monitoring.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-mcp-tool-poisoning-detection-via-schema-anomaly-analysis-and-behavioral-drift-monitoring.warrant.json
# Markdown SHA-256:   d17c2d125c31ae72433a9543e367c94cdf9e41959293a147977578f0080dcd8f
# Code AST SHA-256:   14d22c9ac60b727fb502edd35e64207bbf5655020dfe13e5c65d48563da95883
# Verified Classes:   SchemaPriorMisuseError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class SchemaPriorMisuseError(RuntimeError):
    """Raised when a schema anomaly is treated as a verdict instead of a probe trigger."""
    pass


LOAD_BEARING_PARAMS = {"url", "webhook", "callback", "endpoint", "exfil_target"}


def classify_tool(tool: dict, behavioral_baseline: dict | None) -> str:
    """
    Return one of: 'quarantine', 'probe', 'clear', 'unprobed'.

    Invariant: a clean schema may only yield 'clear' when a behavioral
    baseline exists for this server. Otherwise it is 'unprobed'.
    """
    schema = tool.get("inputSchema", {})
    props = set(schema.get("properties", {}).keys())
    annotations = tool.get("annotations", {}) or {}

    # Load-bearing schema anomaly: an undocumented writable/egress surface.
    egress_surface = props & LOAD_BEARING_PARAMS
    read_only_lie = (
        annotations.get("readOnlyHint") is True
        and bool(props & {"path", "url", "content", "command"})
    )
    load_bearing = bool(egress_surface) or read_only_lie

    if load_bearing:
        # Schema evidence narrows the probe set; it never decides alone.
        if behavioral_baseline is None:
            raise SchemaPriorMisuseError(
                f"tool {tool.get('name')!r} has load-bearing schema anomaly "
                f"(egress={sorted(egress_surface)}, read_only_lie={read_only_lie}) "
                "but no behavioral baseline was supplied; refusing to emit a "
                "schema-only verdict"
            )
        confirmed = behavioral_baseline.get("egress_unlisted") or behavioral_baseline.get(
            "structural_divergence_on_anomalous_param"
        )
        return "quarantine" if confirmed else "probe"

    # Clean schema: not benignity, only absence of a prior.
    if behavioral_baseline is None:
        return "unprobed"
    if behavioral_baseline.get("egress_unlisted") or behavioral_baseline.get(
        "structural_divergence_on_anomalous_param"
    ):
        # Behavior contradicts a clean schema -> still malicious.
        return "quarantine"
    return "clear"


def gate_session(tools: list[dict], baselines: dict[str, dict]) -> dict[str, str]:
    verdicts = {}
    for tool in tools:
        name = tool.get("name")
        baseline = baselines.get(name)
        if baseline is None and tool.get("inputSchema", {}).get("properties"):
            # Force the caller to acknowledge the unprobed state.
            verdict = classify_tool(tool, None) if _has_load_bearing(tool) else "unprobed"
        else:
            verdict = classify_tool(tool, baseline)
        verdicts[name] = verdict
    return verdicts


def _has_load_bearing(tool: dict) -> bool:
    props = set(tool.get("inputSchema", {}).get("properties", {}).keys())
    ann = tool.get("annotations", {}) or {}
    return bool(props & LOAD_BEARING_PARAMS) or (
        ann.get("readOnlyHint") is True and bool(props & {"path", "url", "content", "command"})
    )
