# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-capability-attenuation-across-chained-mcp-server-hops-when-a-composed-tool-re-exports-a-downstream-capability-under-a-broade.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-capability-attenuation-across-chained-mcp-server-hops-when-a-composed-tool-re-exports-a-downstream-capability-under-a-broade.warrant.json
# Markdown SHA-256:   7ecbb30bf9b6723273aa0a7a47b695bba1c2c6f281e4c42fbb618c71648fe85d
# Code AST SHA-256:   ce5e5e7b2aee2a825236d09835d293d12a8c570ddb98d98e4210adb7d99885b5
# Verified Classes:   CapabilityAttenuationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CapabilityAttenuationError(RuntimeError):
    """Raised when a composed MCP tool call would exceed the caller's granted scope."""


def dispatch_composed_tool(
    caller_scope: dict,
    server_grant: dict,
    requested_args: dict,
    downstream_server: str,
) -> None:
    """
    Enforce the composition-seam invariant: effective authority is the
    intersection of caller scope, composing-server grant, and the requested
    resource. Refuse to dispatch if the request escapes the caller's scope,
    even though the intermediate server's own grant would permit it.
    """
    requested_path = requested_args.get("root")
    if requested_path is None:
        raise CapabilityAttenuationError(
            f"composed tool on {downstream_server} requires 'root'; none supplied"
        )

    caller_prefix = caller_scope.get("path")
    server_prefix = server_grant.get("path")

    if caller_prefix is None or server_prefix is None:
        raise CapabilityAttenuationError(
            f"missing path scope: caller={caller_prefix!r} server={server_prefix!r}"
        )

    # The caller's grant must cover the request. The server's broader grant
    # does NOT launder authority on the caller's behalf.
    if not requested_path.startswith(caller_prefix.rstrip("*").rstrip("/")):
        raise CapabilityAttenuationError(
            f"scope escape: caller={caller_prefix!r} requested={requested_path!r} "
            f"via {downstream_server} (server grant {server_prefix!r} does not "
            f"widen caller authority)"
        )

    # Only reached when the request is within the caller's attenuated scope.
    _invoke_downstream(downstream_server, requested_args)


def _invoke_downstream(server: str, args: dict) -> None:
    # Placeholder for the actual MCP transport call.
    return None
