# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-mcp-tool-level-authorization-scopes-when-a-single-agent-turn-fans-out-across-tools-whose-declared-capability-sets-ove.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-mcp-tool-level-authorization-scopes-when-a-single-agent-turn-fans-out-across-tools-whose-declared-capability-sets-ove.warrant.json
# Markdown SHA-256:   755a873e4b816732eb07dd6b1863a799ed3350cd2c433ba8fce4dfb13cbde793
# Code AST SHA-256:   5251ef01596560c6890e956a189675cbb394183614e57fd26b152bc9a159a170
# Verified Classes:   ScopeIntersectionViolation, TaintTag, TaintedValue
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class ScopeIntersectionViolation(RuntimeError):
    """Raised when a tool argument's provenance scope is not contained
    within the target tool's declared authorization scope."""
    pass


@dataclass
class TaintTag:
    scope: str          # e.g. "/data/**" or "schema:analytics"
    source_tool: str


@dataclass
class TaintedValue:
    value: Any
    tags: list[TaintTag] = field(default_factory=list)


def scope_contains(outer: str, inner: str) -> bool:
    """Prefix/glob containment. Real impls must handle glob semantics;
    this is the minimal predicate the invariant depends on."""
    if outer.endswith("/**"):
        return inner.startswith(outer[:-3])
    return outer == inner


def authorize_argument(arg: TaintedValue, target_scope: str, target_tool: str) -> None:
    for tag in arg.tags:
        if not scope_contains(target_scope, tag.scope):
            raise ScopeIntersectionViolation(
                f"tool '{target_tool}' (scope={target_scope}) received argument "
                f"tainted by '{tag.source_tool}' (scope={tag.scope}); "
                f"{tag.scope} is not a subset of {target_scope} — cross-tool "
                f"argument-flow leak blocked. Operator must declare an explicit "
                f"taint-widening grant for ({tag.source_tool} -> {target_tool})."
            )


def dispatch(tool: str, target_scope: str, args: dict[str, TaintedValue]) -> Any:
    for name, arg in args.items():
        authorize_argument(arg, target_scope, tool)
    # ... actual MCP call ...
    return None
