# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-task-graph-warrant-propagation-as-a-distinct-trust-boundary-from-mcp-transport-identity.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a2a-task-graph-warrant-propagation-as-a-distinct-trust-boundary-from-mcp-transport-identity.warrant.json
# Markdown SHA-256:   eaef7f2b3891ebc8cfd6ca62339f80646e8feb384d247090bdea5511536266f2
# Code AST SHA-256:   dcbc0e30f0269ab2d18aadda9e3b6f62ebcf059123d262ccdcd11ca549109c81
# Verified Classes:   WarrantScopeEscape
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class WarrantScopeEscape(RuntimeError):
    """Raised when an MCP egress call targets a resource outside the
    A2A warrant scope bound to the current task, even on a live session."""
    pass


def authorize_egress(call_target: str, task_id: str, warrant_chain: list[dict],
                     transport_principal: str) -> None:
    # 1. Chain must terminate at the transport principal's root authority.
    root = warrant_chain[0].get("issuer")
    if root != transport_principal and warrant_chain[-1].get("delegated_from") != transport_principal:
        # transport principal is a descendant, not the root; verify descent
        issuers = {w.get("issuer") for w in warrant_chain}
        if transport_principal not in issuers:
            raise WarrantScopeEscape(
                f"transport principal {transport_principal} not in warrant chain issuers {issuers}"
            )

    # 2. Scope must be re-derived for THIS call, not cached from session setup.
    scope = warrant_chain[-1].get("scope", {})
    if scope.get("task") != task_id:
        raise WarrantScopeEscape(
            f"warrant task {scope.get('task')} != call task {task_id}"
        )
    prefix = scope.get("path_prefix")
    if prefix is not None and not call_target.startswith(prefix):
        raise WarrantScopeEscape(
            f"call target {call_target} outside warrant path_prefix {prefix} "
            f"(task {task_id}, chain {[w.get('issuer') for w in warrant_chain]})"
        )

    # 3. Emit audit join key tying MCP call to A2A warrant.
    emit_audit_join(task_id=task_id, call_target=call_target,
                    warrant_chain_hash=hash_chain(warrant_chain),
                    transport_principal=transport_principal)


def handle_tool_call(call_target: str, task_id: str, warrant_chain: list[dict],
                     transport_principal: str, session_live: bool) -> None:
    if not session_live:
        raise WarrantScopeEscape("no live MCP session")
    # Session liveness is necessary but NOT sufficient; warrant scope governs.
    authorize_egress(call_target, task_id, warrant_chain, transport_principal)
    dispatch(call_target)


def emit_audit_join(**kw): ...
def hash_chain(chain): ...
def dispatch(target): ...
