# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-tool-call-it-is-technically-permitted-to-make-the-scope-inheritance-gap-in-mcp-runtime-policy-enforcement.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-tool-call-it-is-technically-permitted-to-make-the-scope-inheritance-gap-in-mcp-runtime-policy-enforcement.warrant.json
# Markdown SHA-256:   5e30d988eae2f8345a5568da42c96774dc43666bd709becefd41555ee3a82426
# Code AST SHA-256:   97594883fde51cc840a82030b1b6ec783be07c975273fc9b6886ece79fa9e216
# Verified Classes:   ScopeInheritanceViolation, ToolPolicy
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ScopeInheritanceViolation(RuntimeError):
    """Raised when a tool call passes declaration-level admissibility but
    escapes the granted resource set via its arguments, or when an unlisted
    tool attempts to inherit a permissive default rate budget."""
    pass


class ToolPolicy:
    def __init__(self, declared_scope, referent_arg, granted_resources, rate_budget):
        self.declared_scope = declared_scope      # e.g. "fs:read"
        self.referent_arg = referent_arg          # e.g. "path", or None if opaque
        self.granted_resources = granted_resources  # set of allowed referents/subtrees
        self.rate_budget = rate_budget            # explicit; None means unclassified


def enforce(tool_name, policy, arguments, session_grant, rate_state):
    # Condition (a): declared scope must be granted.
    if policy.declared_scope not in session_grant:
        raise ScopeInheritanceViolation(
            f"{tool_name}: declared scope {policy.declared_scope!r} not in session grant"
        )

    # Condition (c): unlisted tools are denied, never defaulted.
    if policy.rate_budget is None:
        raise ScopeInheritanceViolation(
            f"{tool_name}: no explicit rate budget; refusing default inheritance"
        )
    if rate_state.exceeded(tool_name, policy.rate_budget):
        raise ScopeInheritanceViolation(
            f"{tool_name}: rate budget {policy.rate_budget} exceeded"
        )

    # Condition (b): resolve the referent argument into the granted set.
    if policy.referent_arg is None:
        # Opaque referent: cannot prove containment, so deny.
        raise ScopeInheritanceViolation(
            f"{tool_name}: argument referent unresolvable; deny-with-escalation"
        )
    referent = arguments.get(policy.referent_arg)
    if referent is None or referent not in policy.granted_resources:
        raise ScopeInheritanceViolation(
            f"{tool_name}: argument {policy.referent_arg}={referent!r} "
            f"escapes granted resource set"
        )
    return True
