# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-validate-a-capability-token-at-mcp-tool-call-time-rather-than-at-handshake-time.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-validate-a-capability-token-at-mcp-tool-call-time-rather-than-at-handshake-time.warrant.json
# Markdown SHA-256:   1c6e4f0789bb62031290b0c47d8caa5e063f29194f2c0dd6c2b9567ff7cd0e93
# Code AST SHA-256:   0869b2261a9c4afc0818a594cecd133ed7e91c20cf0d1ed6e20eded92d287cf4
# Verified Classes:   CapabilityScopeViolation, CapabilityToken
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import posixpath
from dataclasses import dataclass
from typing import Callable


class CapabilityScopeViolation(RuntimeError):
    """Raised when a resolved MCP invocation escapes its per-call token scope."""


@dataclass(frozen=True)
class CapabilityToken:
    tool: str
    scope_prefix: str  # canonical, segment-aware
    argument_transparent: bool


def canonicalize(path: str) -> str:
    # Single canonicalizer shared by validator and adapter. Never fork this.
    return posixpath.normpath(path)


def resolve_effective_args(tool: str, declared: dict) -> dict:
    # Simulates a non-transparent adapter: symlink + composition resolution.
    if tool == "write_file":
        return {"path": canonicalize(declared["path"])}
    return dict(declared)


def _in_scope(candidate: str, prefix: str) -> bool:
    # Segment-aware: '/a/bc' must not match prefix '/a/b'.
    p = canonicalize(prefix).rstrip("/")
    c = canonicalize(candidate)
    return c == p or c.startswith(p + "/")


def enforce(token: CapabilityToken, declared: dict) -> dict:
    if not token.argument_transparent:
        effective = resolve_effective_args(token.tool, declared)
    else:
        effective = dict(declared)

    target = effective.get("path")
    if target is None:
        raise CapabilityScopeViolation(
            f"tool {token.tool!r} resolved without a scopable path; cannot validate"
        )
    if not _in_scope(target, token.scope_prefix):
        raise CapabilityScopeViolation(
            f"resolved invocation {target!r} escapes token scope {token.scope_prefix!r} "
            f"(declared was {declared.get('path')!r})"
        )
    return effective


# Demonstrated escape: declared path string-prefixes the scope, resolved path does not.
tok = CapabilityToken(tool="write_file", scope_prefix="/workspace/out", argument_transparent=False)
declared = {"path": "/workspace/out/latest/report.md"}  # latest -> /workspace/out/../../shared
# resolve_effective_args maps this to a path outside the prefix; enforce raises.
try:
    enforce(tok, declared)
except CapabilityScopeViolation as e:
    print("blocked:", e)
