# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-mcp-tool-poisoning-detection-when-schema-anomalies-and-dependency-graph-taints-disagree.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-mcp-tool-poisoning-detection-when-schema-anomalies-and-dependency-graph-taints-disagree.warrant.json
# Markdown SHA-256:   84767f3b0415f5e9f90baccd152922559cf1765e192afcc7d7aa44d17d2b7bf3
# Code AST SHA-256:   21f26b78a557f54d0d71cd71864f2e3214b43c24bc791024977fa90d3b8fe6ea
# Verified Classes:   TaintCompositionError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class TaintCompositionError(RuntimeError):
    """Raised when a privileged sink is reachable from external content
    through schema-derived edges that carry no sanitizer declaration."""
    pass


SANITIZERS = {"strip_html", "redact_pii", "normalize_whitespace"}
PRIVILEGED_SINKS = {"send_email", "exec", "write_file", "http_post"}
EXTERNAL_SOURCES = {"read_note", "fetch_url", "read_file"}


def taint_closure(graph, source, sink, sanitizer_set=SANITIZERS):
    """
    graph: dict[tool_name -> list[(downstream_tool, edge_kind)]]
    edge_kind: "raw" (payload passed through) or "derived" (schema-derived field)
    Returns set of unsanitized paths from source to sink.
    """
    paths = []
    stack = [(source, [source], False)]
    while stack:
        node, path, sanitized = stack.pop()
        if node == sink and not sanitized:
            paths.append(path)
            continue
        for nxt, kind in graph.get(node, []):
            if nxt in path:
                continue
            next_sanitized = sanitized or (node in sanitizer_set)
            # taint-preserving: "derived" does NOT drop taint unless sanitizer
            stack.append((nxt, path + [nxt], next_sanitized))
    return paths


def admit_tool_call(graph, source, sink):
    if sink not in PRIVILEGED_SINKS:
        return True
    if source not in EXTERNAL_SOURCES:
        return True
    paths = taint_closure(graph, source, sink)
    if paths:
        raise TaintCompositionError(
            f"unsanitized taint path(s) from {source!r} to privileged sink "
            f"{sink!r}: {paths}. A clean per-node verdict is inadmissible; "
            f"joint analysis required."
        )
    return True


# Observed failure reproduction:
graph = {
    "read_note": [("summarize", "raw")],
    "summarize": [("send_email", "derived")],  # schema-derived, NOT a sanitizer
    "send_email": [],
}
try:
    admit_tool_call(graph, "read_note", "send_email")
except TaintCompositionError as e:
    print("BLOCKED:", e)
