# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-to-mcp-gateway-identity-propagation-as-a-non-delegable-invariant-rather-than-a-transport-detail.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-to-mcp-gateway-identity-propagation-as-a-non-delegable-invariant-rather-than-a-transport-detail.warrant.json
# Markdown SHA-256:   06fafecd88f050e89bd135f33b394f6cc1213aaf140fac8609f7e8c17d45e3e5
# Code AST SHA-256:   38329f4480e3990c2f14e2bd2fd5cf7957ba5eba107e8c1d31bfd13c5326a115
# Verified Classes:   IdentityBindingViolation, McpSession
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class IdentityBindingViolation(RuntimeError):
    """Raised when an outbound MCP call would execute under a principal
    or scope that does not match the originating A2A task assertion."""
    pass


class McpSession:
    def __init__(self, principal: str, granted_scope: set[str]):
        self.principal = principal
        self.granted_scope = set(granted_scope)


def dispatch_tool_call(
    task_assertion: dict,
    session: McpSession,
    tool_name: str,
    required_scope: str,
    enforcement_mode: bool,
) -> dict:
    asserted = task_assertion["sub"]
    asserted_scope = set(task_assertion["scope"].split())

    # Invariant 1: the session must not be broader than the assertion
    # unless the gateway is genuinely gating this call itself.
    if not enforcement_mode and session.principal != asserted:
        raise IdentityBindingViolation(
            f"session principal {session.principal!r} != asserted {asserted!r} "
            f"for task {task_assertion.get('task_id')}; refusing to dispatch "
            f"{tool_name} under widened identity"
        )

    # Invariant 2: required scope must be covered by the *asserted* scope,
    # never merely by the session's broader grant.
    if required_scope not in asserted_scope:
        raise IdentityBindingViolation(
            f"asserted principal {asserted!r} lacks {required_scope!r} "
            f"(has {sorted(asserted_scope)}); tool {tool_name} denied — "
            f"this denial is terminal, do not retry on another session"
        )

    # Invariant 3: even in enforcement mode, the session must actually
    # hold the scope, or the call cannot proceed.
    if required_scope not in session.granted_scope:
        raise IdentityBindingViolation(
            f"session {session.principal!r} lacks {required_scope!r}; "
            f"cannot dispatch {tool_name}"
        )

    return {"tool": tool_name, "principal": asserted, "binding_ok": True}
