# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-treats-a-sanitized-mcp-tool-output-as-trusted-because-the-taint-label-was-dropped-at-the-json-serialization-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-treats-a-sanitized-mcp-tool-output-as-trusted-because-the-taint-label-was-dropped-at-the-json-serialization-boundary.warrant.json
# Markdown SHA-256:   4b9603e19ae40a550ce3382a4240acc572823b26873d2f52cfa9c630b6a89715
# Code AST SHA-256:   4741061ca044881b22ab61699bfd525f64935f12b98600cf4b715fd47562a5c9
# Verified Classes:   TaintBoundaryViolation, UnsanctionedSanitization, TaintedValue
# Defensive Guards:   6 fail-closed invariants (zero external deps)

raw = await session.call_tool(name, args)
result = json.loads(raw.content[0].text)   # payload extracted, provenance lost
return result                               # plain dict, no taint label

import json
import hashlib
from dataclasses import dataclass, field
from typing import Any, Callable, Optional


class TaintBoundaryViolation(RuntimeError):
    """Raised when a value crosses a transport boundary without provenance."""
    pass


class UnsanctionedSanitization(RuntimeError):
    """Raised when taint is cleared without a policy pass or audit record."""
    pass


@dataclass
class TaintedValue:
    payload: Any
    provenance: str
    sanitized: bool = False
    audit: list = field(default_factory=list)

    def content_hash(self) -> str:
        return hashlib.sha256(
            json.dumps(self.payload, sort_keys=True).encode()
        ).hexdigest()


# A policy is a callable that returns True iff the payload is safe to untaint.
ContentPolicy = Callable[[Any], bool]


def reconstruct_from_transport(
    wire_text: str,
    source: str,
    *,
    envelope_provenance: Optional[str] = None,
) -> TaintedValue:
    """
    The ONLY sanctioned way to turn wire bytes into a runtime value.
    Fails closed: if the envelope carries no provenance, the value is
    still tainted, labeled with the transport source. It is NEVER
    returned as a plain value.
    """
    try:
        payload = json.loads(wire_text)
    except json.JSONDecodeError as e:
        raise TaintBoundaryViolation(
            f"unparseable transport payload from {source}: {e}"
        ) from e

    provenance = envelope_provenance or f"untrusted:transport:{source}"
    if not provenance.startswith(("untrusted:", "trusted:")):
        raise TaintBoundaryViolation(
            f"provenance on envelope from {source} is malformed: {provenance!r}"
        )
    return TaintedValue(payload=payload, provenance=provenance)


def sanitize(
    value: TaintedValue,
    policy: ContentPolicy,
    *,
    auditor: str,
) -> TaintedValue:
    """
    The ONLY sanctioned way to clear taint. Requires a policy pass and
    emits an audit record. Refuses to sanitize a value that arrived
    from an untrusted transport without policy approval.
    """
    if not isinstance(value, TaintedValue):
        # A plain value here means someone bypassed reconstruct_from_transport.
        raise TaintBoundaryViolation(
            "sanitize() received a plain value; taint was dropped upstream"
        )
    if not policy(value.payload):
        raise UnsanctionedSanitization(
            f"policy rejected payload {value.content_hash()} from "
            f"{value.provenance}; cannot clear taint"
        )
    value.audit.append(
        {"event": "sanitized", "hash": value.content_hash(),
         "provenance": value.provenance, "auditor": auditor}
    )
    value.sanitized = True
    return value


def route_to_privileged_sink(value: Any, sink: Callable[[Any], Any]) -> Any:
    """
    Privileged sinks (shell, file write, sub-agent system prompt) must
    only accept sanitized TaintedValues. A plain value reaching here is
    a boundary violation, not a trusted literal.
    """
    if not isinstance(value, TaintedValue):
        raise TaintBoundaryViolation(
            "privileged sink received a plain value; reconstruction "
            "boundary was bypassed and taint was lost"
        )
    if not value.sanitized:
        raise UnsanctionedSanitization(
            f"privileged sink received unsanitized value from "
            f"{value.provenance} (hash {value.content_hash()})"
        )
    return sink(value.payload)
