# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-scope-laundering-across-mcp-tool-composition-when-a-single-server-hosts-both-read-and-write-tools.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-scope-laundering-across-mcp-tool-composition-when-a-single-server-hosts-both-read-and-write-tools.warrant.json
# Markdown SHA-256:   f1d519b3adb37622b46e5798deea7bf98d7ad4f39a06b0f41e3856ea40aa6733
# Code AST SHA-256:   0a51a18322381de97ab36b8a8bb6bc90e7caa58c4a0eaa94510a0f008306e935
# Verified Classes:   ScopeLaunderingError, Scope, Reference
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ScopeLaunderingError(RuntimeError):
    """Raised when a mutating tool's resolved target exceeds the resource
    reach of the scope that authorized the call, or when a reference
    argument was produced by a tool whose scope does not cover the target."""


@dataclass(frozen=True)
class Scope:
    verb: str
    resource: str  # e.g. "project=P'" ; empty string means unqualified

    def covers(self, verb: str, resource: str) -> bool:
        if self.verb != verb:
            return False
        if not self.resource:
            # Unqualified scope: cannot be intersected with a resource.
            # Treated as non-covering for enforcement purposes.
            return False
        return self.resource == resource


@dataclass(frozen=True)
class Reference:
    """A value passed between tools. Tracks the scope that produced it."""
    value: str
    produced_by_tool: str
    produced_under: Scope
    target_resource: str  # resolved server-side


def authorize_mutation(
    token_scopes: FrozenSet[Scope],
    required_verb: str,
    reference: Reference,
) -> None:
    # Guardrail 1: the reference must have been produced under a scope
    # whose resource reach includes the resolved target. Otherwise the
    # read tool laundered a reference across a resource boundary.
    if not reference.produced_under.covers(required_verb, reference.target_resource):
        raise ScopeLaunderingError(
            f"reference {reference.value!r} produced by {reference.produced_by_tool} "
            f"under scope {reference.produced_under!r} does not cover target "
            f"resource {reference.target_resource!r} for verb {required_verb!r}"
        )

    # Guardrail 2: the caller's token must hold a resource-qualified scope
    # for the resolved target, not merely the verb.
    if not any(s.covers(required_verb, reference.target_resource) for s in token_scopes):
        raise ScopeLaunderingError(
            f"no resource-qualified scope for verb {required_verb!r} on "
            f"resource {reference.target_resource!r}; token holds "
            f"{sorted((s.verb, s.resource) for s in token_scopes)}"
        )


# Trace of the observed failure:
#   list_documents(project=P) under Scope("docs:list", "project=P")
#     returns Reference("D", "list_documents", Scope("docs:list","project=P"), target="project=P'")
#   update_document_metadata(doc_id="D") under token {Scope("docs:write","")}
# Guardrail 1 fires: Scope("docs:list","project=P") does not cover "project=P'".
# Guardrail 2 would also fire: Scope("docs:write","") is unqualified.
try:
    authorize_mutation(
        token_scopes=frozenset({Scope("docs:write", "")}),
        required_verb="docs:write",
        reference=Reference(
            value="D",
            produced_by_tool="list_documents",
            produced_under=Scope("docs:list", "project=P"),
            target_resource="project=P'",
        ),
    )
except ScopeLaunderingError as exc:
    print(f"blocked: {exc}")
