# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-across-an-mcp-tool-boundary-when-the-server-re-derives-output-from-clean-inputs.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-across-an-mcp-tool-boundary-when-the-server-re-derives-output-from-clean-inputs.warrant.json
# Markdown SHA-256:   c8605e4213c2fd60e84a9575daeaf15722f1708c4b50be2293b3f8b4839a7dfe
# Code AST SHA-256:   f168ebe93fa4806959a4df4176e83e91e90543138bc2d4c203e13b52c1bbda4e
# Verified Classes:   TaintContractError, TaintContract, TaintSet, ToolResponse
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import FrozenSet


class TaintContractError(RuntimeError):
    """Raised when a tool response cannot be safely assigned a taint level."""


class TaintContract(Enum):
    TRANSPARENT = "transparent"   # output is pure function of input, no content carryover
    PRESERVING = "preserving"     # output may echo input content; inherit input taint
    ABSORBING = "absorbing"       # output re-derived from trusted store; may clear


@dataclass(frozen=True)
class TaintSet:
    sources: FrozenSet[str] = field(default_factory=frozenset)

    def union(self, other: "TaintSet") -> "TaintSet":
        return TaintSet(self.sources | other.sources)

    def is_clean(self) -> bool:
        return not self.sources


@dataclass(frozen=True)
class ToolResponse:
    tool: str
    contract: TaintContract
    input_taint: TaintSet
    server_authenticated: bool
    key_attacker_controlled: bool
    content: str


def assign_response_taint(resp: ToolResponse) -> TaintSet:
    """Compute the taint of a tool response under the declared contract.

    Defaults to PRESERVING when the contract is missing, because the client
    cannot prove the tool is non-content-preserving.
    """
    if resp.contract is TaintContract.TRANSPARENT:
        # Pure function: output carries exactly the input's taint.
        return resp.input_taint

    if resp.contract is TaintContract.PRESERVING:
        # May echo input content: taint is inherited, never cleared.
        return resp.input_taint

    if resp.contract is TaintContract.ABSORBING:
        # Clearing is only sound if the re-derivation source is trusted
        # AND the lookup key was not chosen by the attacker.
        if not resp.server_authenticated:
            raise TaintContractError(
                f"tool {resp.tool!r} declared ABSORBING but server is "
                f"unauthenticated; cannot clear taint"
            )
        if resp.key_attacker_controlled:
            raise TaintContractError(
                f"tool {resp.tool!r} declared ABSORBING but its lookup key "
                f"was attacker-controlled; re-derivation is not authoritative"
            )
        return TaintSet()

    raise TaintContractError(
        f"tool {resp.tool!r} has no declared taint contract; "
        f"defaulting to PRESERVING is required but contract is unknown"
    )


def promote_to_trusted(resp: ToolResponse) -> bool:
    """Return True only if the response may be treated as trusted fact."""
    taint = assign_response_taint(resp)
    if not taint.is_clean():
        return False
    if resp.contract is TaintContract.ABSORBING and not resp.server_authenticated:
        raise TaintContractError(
            f"cannot promote {resp.tool!r}: unauthenticated absorbing response"
        )
    return True
