# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-a-tainted-argument-through-a-re-routed-mcp-tool-call.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-a-tainted-argument-through-a-re-routed-mcp-tool-call.warrant.json
# Markdown SHA-256:   fabb55225dd2138ac04de1c07dbe74b40e425323b5f3ecb2f917688976c0891f
# Code AST SHA-256:   bfed675ef58c7a7fa02338c13443d6c6049d1a86188bae52fa3b0039e987e530
# Verified Classes:   TrustClass, TaintViolation, LedgerEntry, ProvenanceLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum


class TrustClass(Enum):
    UNTRUSTED_SOURCE = 1
    TRUSTED_LOCAL = 2
    PRIVILEGED_SINK = 3


class TaintViolation(RuntimeError):
    """Raised when an argument derived from an untrusted source reaches a privileged sink."""


@dataclass
class LedgerEntry:
    fingerprint: str
    source_class: TrustClass
    origin_tool: str


@dataclass
class ProvenanceLedger:
    entries: list[LedgerEntry] = field(default_factory=list)

    def record(self, value_fingerprint: str, source_class: TrustClass, origin_tool: str) -> None:
        self.entries.append(LedgerEntry(value_fingerprint, source_class, origin_tool))

    def derivation_sources(self, argument_value: str) -> list[LedgerEntry]:
        # Conservative: any ledger fingerprint that is a substring of the argument
        # counts as a derivation source. Paraphrase-resistant for surviving tokens
        # (addresses, URLs, IDs) which is exactly the payload that matters.
        return [e for e in self.entries if e.fingerprint and e.fingerprint in argument_value]


def route_tool_call(
    tool_name: str,
    sink_class: TrustClass,
    arguments: dict[str, str],
    ledger: ProvenanceLedger,
) -> None:
    if sink_class is not TrustClass.PRIVILEGED_SINK:
        return
    for field_name, value in arguments.items():
        for entry in ledger.derivation_sources(value):
            if entry.source_class is TrustClass.UNTRUSTED_SOURCE:
                raise TaintViolation(
                    f"argument '{field_name}' of privileged tool '{tool_name}' "
                    f"derives from untrusted source '{entry.origin_tool}' "
                    f"(fingerprint={entry.fingerprint!r}); declassify or re-derive "
                    f"from trusted-local sources before retrying"
                )
    # All arguments clean: privileged call may proceed.
    return None
