# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-taint-boundary-when-an-mcp-tool-response-mutates-the-reasoning-state-it-is-about-to-trust.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-taint-boundary-when-an-mcp-tool-response-mutates-the-reasoning-state-it-is-about-to-trust.warrant.json
# Markdown SHA-256:   7da2579a11c5f1b57b5d853f4145c7b2dfa386930cd14974cc85454e9107462e
# Code AST SHA-256:   7fb5a16feb7a25c1fdb864ac8873eeb0c5a6f1cc7eadecd4b36366ecc676a98b
# Verified Classes:   TaintLaunderingError, TurnTaintTracker
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintLaunderingError(RuntimeError):
    """Raised when a side-effecting tool call is attempted while the
    current turn's taint bit is set by an untrusted MCP response and has
    not been cleared by a trusted re-verification event."""
    pass


class TurnTaintTracker:
    def __init__(self):
        self.tainted = False
        self.cleared_by = None

    def ingest_tool_response(self, source_trust: str, payload: str) -> None:
        # Any untrusted payload entering context taints the whole turn,
        # not just the bytes. The model may paraphrase it into its plan.
        if source_trust == "untrusted":
            self.tainted = True
            self.cleared_by = None

    def clear_via_trusted_verification(self, verifier: str) -> None:
        # Only a trusted-class re-verification may clear the bit.
        if verifier not in {"trusted_server", "schema_validator", "human_auditor"}:
            raise TaintLaunderingError(
                f"illegal taint clear attempted by {verifier!r}; "
                "only trusted re-verification may clear turn taint"
            )
        self.tainted = False
        self.cleared_by = verifier

    def guard_side_effect(self, tool_name: str, args: dict) -> None:
        # The model's plan may look clean; the taint bit is the truth.
        if self.tainted:
            raise TaintLaunderingError(
                f"blocked side-effecting call {tool_name!r} with args {args!r}: "
                "turn taint set by untrusted MCP response and not cleared "
                "by a trusted re-verification event"
            )


def execute_agent_turn(tracker: TurnTaintTracker, mcp_response: dict,
                       next_action: dict) -> None:
    tracker.ingest_tool_response(
        source_trust=mcp_response["trust"],
        payload=mcp_response["content"][0]["text"],
    )
    # Model has summarized the response into its plan by now; the plan is
    # model-authored and therefore looks trusted. Enforce on the bit.
    if next_action["side_effecting"]:
        tracker.guard_side_effect(next_action["tool"], next_action["args"])
