# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-mcp-scope-attenuation-has-silently-failed-at-the-tool-boundary-the-write-through-shadow-scope-and-the-audit-log-that.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-mcp-scope-attenuation-has-silently-failed-at-the-tool-boundary-the-write-through-shadow-scope-and-the-audit-log-that.warrant.json
# Markdown SHA-256:   d80233ecff046f8a32576e448302cf92d33a3d328a54df7f3902d7d4d77a9fb7
# Code AST SHA-256:   d09e3839764e911ad03aac19c0b3bb2b5079fc78ac34ef3145ab093aa915154c
# Verified Classes:   ScopeAttenuationError, Tool, Session
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ScopeAttenuationError(RuntimeError):
    """Raised when a handler's materialized capability set exceeds its effective scope."""
    pass


@dataclass(frozen=True)
class Tool:
    name: str
    primary_scope: frozenset
    effect_closure: frozenset  # transitive effects reachable from the handler
    handler: object = field(repr=False)


@dataclass(frozen=True)
class Session:
    grant: frozenset


def dispatch(session: Session, tool: Tool, args: dict) -> dict:
    # Admission: the tool's FULL effect closure must be covered by the grant.
    if not tool.effect_closure <= session.grant:
        missing = tool.effect_closure - session.grant
        return {"decision": "deny", "missing": sorted(missing)}

    # Attenuation: materialize ONLY the intersection, never the full grant.
    effective = session.grant & tool.effect_closure

    # Invariant: the handler must receive exactly `effective`, not `session.grant`.
    materialized = frozenset(tool.handler.capabilities(args))
    if materialized != effective:
        raise ScopeAttenuationError(
            f"tool={tool.name} materialized={sorted(materialized)} "
            f"effective={sorted(effective)} grant={sorted(session.grant)} "
            f"-- handler inherited grant beyond effect closure"
        )

    return {
        "decision": "allow",
        "requested": sorted(tool.effect_closure),
        "granted": sorted(effective),
        "materialized": sorted(materialized),
    }
