# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-propagates-taint-across-an-mcp-tool-boundary-without-a-capability-downgrade.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-propagates-taint-across-an-mcp-tool-boundary-without-a-capability-downgrade.warrant.json
# Markdown SHA-256:   f9696bac2add2279b207f55324a2fcc1f75b6fe32d09d573217f6f3ad6696767
# Code AST SHA-256:   8a5d21e484aab80693bd5ba9cab62696f5bc73323ab768dc97664f465f0efdb1
# Verified Classes:   TaintCapabilityEscalation
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TaintCapabilityEscalation(RuntimeError):
    """Raised when a tainted argument enters a call whose effective
    capability set exceeds the caller's, with no delegation grant."""
    pass


def enforce_boundary(
    arg_taint: str,
    declared_caps: frozenset,
    requested_caps: frozenset,
    caller_caps: frozenset,
    delegation: frozenset = frozenset(),
) -> frozenset:
    # Step 1: narrow to what this call will actually exercise.
    if not requested_caps:
        # Argument shape could not be statically attributed (e.g. a
        # free-form command string). Under taint, assume the worst.
        effective = declared_caps
    else:
        effective = declared_caps & requested_caps

    # Step 2: delegation gate, independent of taint.
    uncovered = effective - caller_caps - delegation
    if uncovered:
        raise TaintCapabilityEscalation(
            f"effective caps {sorted(effective)} exceed caller "
            f"{sorted(caller_caps)}; uncovered={sorted(uncovered)}"
        )

    # Step 3: taint policy keyed on EFFECTIVE caps, not declared.
    if arg_taint == "UNTRUSTED_EXTERNAL" and "fs.write" in effective:
        raise TaintCapabilityEscalation(
            "tainted argument would exercise fs.write via effective caps "
            f"{sorted(effective)}; declared={sorted(declared_caps)}"
        )

    return effective
