# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-taint-label-has-been-laundered-through-a-capability-scoped-mcp-tool-result-the-return-value-provenance-gap.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-taint-label-has-been-laundered-through-a-capability-scoped-mcp-tool-result-the-return-value-provenance-gap.warrant.json
# Markdown SHA-256:   689639d0b47674572535cac492048e85a2a5e5643cbb28ce47beb055d0d7376c
# Code AST SHA-256:   cb7c09f4703fbf265aac10f1d1b889ce38948587a20114308bbd8b5fb085d7fc
# Verified Classes:   TaintLaunderingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a tainted value crosses a tool boundary and returns untainted."""
    pass


TRUSTED_OUTPUT_TOOLS = {"summarize", "translate"}  # the vulnerable assumption
TAINT_CLEARING_TOOLS = {"sanitize"}                 # explicit, verified clearers


def invoke_tool(tool_name: str, args: dict, context_taint: set[str]) -> tuple[dict, set[str]]:
    """Invoke an MCP tool and return (result, new_context_taint).

    Enforces argument-to-return taint propagation. Fails closed on schema drift.
    """
    arg_taint = set(context_taint)
    for value in args.values():
        if isinstance(value, dict) and value.get("_taint"):
            arg_taint |= set(value["_taint"])

    result, envelope = _mcp_call(tool_name, args)

    # Envelope provenance is authoritative; agent-side assumptions are not.
    provenance = envelope.get("provenance")
    if provenance is None:
        # Unknown schema: fail closed, never default to trusted.
        result_taint = arg_taint | {"unknown_provenance"}
    else:
        result_taint = set(provenance.get("taint", [])) | arg_taint

    if tool_name in TAINT_CLEARING_TOOLS:
        if not _verify_cleared(result):
            raise TaintLaunderingError(
                f"tool {tool_name!r} claimed to clear taint but verifier rejected output"
            )
        result_taint = set()

    # Detect laundering: tainted args, untainted result, no clearing capability.
    if arg_taint and not result_taint and tool_name not in TAINT_CLEARING_TOOLS:
        raise TaintLaunderingError(
            f"taint laundered through {tool_name!r}: "
            f"args carried {sorted(arg_taint)} but result returned untainted"
        )

    return result, result_taint


def _mcp_call(tool_name: str, args: dict) -> tuple[dict, dict]:
    # Placeholder for the actual MCP transport; returns (payload, envelope).
    raise NotImplementedError


def _verify_cleared(result: dict) -> bool:
    # Placeholder: run a content verifier (e.g., injection classifier) on the output.
    return False
