# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-tool-output-as-tainted-and-why-taint-labels-do-not-survive-the-second-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-mcp-tool-output-as-tainted-and-why-taint-labels-do-not-survive-the-second-hop.warrant.json
# Markdown SHA-256:   50321053cb2a105c2bc9ebd05e7f48d0f6205d97a56f23c47d850bd5bbc5c64e
# Code AST SHA-256:   d6df45b55291b82e4f78d54f57ab87c28056c57883c380d7d62cc90415e81b42
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a value derived from untrusted tool output is about to
    cross into an action-typed MCP argument without re-derived provenance."""
    pass


ACTION_TYPED_TOOLS = {"shell", "file_write", "http_post", "sql_exec", "delete"}


def assert_argument_provenance(
    tool_name: str,
    argument_name: str,
    value: str,
    provenance: set[str],
    untrusted_sources: set[str],
) -> None:
    """Enforce the second-hop taint invariant.

    provenance: the set of source object ids the value derives from.
    untrusted_sources: source ids flagged untrusted at ingestion.

    A value is admissible into an action-typed argument only if its
    provenance is disjoint from untrusted_sources OR the value was
    re-derived by verbatim substring match against a trusted source.
    A model-authored summary has provenance == {"self:summary"} and is
    therefore *not* a trust upgrade; it is laundering.
    """
    if tool_name not in ACTION_TYPED_TOOLS:
        return  # read-only tools cannot be exploited via argument injection

    tainted = provenance & untrusted_sources
    if not tainted:
        return

    if "self:summary" in provenance:
        raise TaintLaunderingError(
            f"Refusing {tool_name}.{argument_name}={value!r}: value derives "
            f"from model-authored summary of untrusted sources {sorted(tainted)}. "
            f"Re-derive from the original tool result verbatim or escalate to user."
        )

    raise TaintLaunderingError(
        f"Refusing {tool_name}.{argument_name}={value!r}: provenance includes "
        f"untrusted sources {sorted(tainted)} and no verbatim re-derivation "
        f"attestation was supplied."
    )


def compose_action_call(tool_name: str, args: dict[str, str], provenance_map: dict[str, set[str]], untrusted: set[str]) -> dict:
    for name, value in args.items():
        assert_argument_provenance(tool_name, name, value, provenance_map.get(name, set()), untrusted)
    return {"tool": tool_name, "arguments": args}
