A2AConnectGet started

Examples

Real agent → agent examples you can run

Four executable demos. No API keys. Each starts multiple AgentPeer instances, handshakes, offers tasks, streams progress, and prints an audit trail.

shell — run all
python3 -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
pytest
python demos/support_desk.py
python demos/incident_handoff.py
python demos/two_agents.py
python demos/quickstart.py
01

Support desk handoff

Desk → intake → billing specialist → reply

A real support ticket (duplicate invoice) is classified, disputed, and answered across four agents on one bus.

billing · 4 agents · audit

run
python demos/support_desk.py

Full source: demos/support_desk.py

  1. 1. Agents start on a shared in-memory bus
  2. 2. Orchestrator hellos each peer
  3. 3. offer_task chains results agent → agent
  4. 4. Audit log prints the lifecycle
demos/support_desk.py
#!/usr/bin/env python3
"""Executable agent→agent example: support intake → billing specialist → reply.

Run from repo root:
  pip install -e ".[dev]"
  python demos/support_desk.py
"""

from __future__ import annotations

import asyncio
import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))

from a2aconnect import AgentPeer, MemoryAuditLog, create_bus, from_async_fn  # noqa: E402


TICKET = {
    "id": "TCK-1842",
    "customer": "Northwind Logistics",
    "channel": "email",
    "subject": "Invoice charged twice for March seats",
    "body": (
        "We were billed twice for our March seat renewal. "
        "Invoice INV-9031 and INV-9031-DUP both show $4,200. Please refund the duplicate."
    ),
}


async def intake_run(input, ctx):
    ticket = input or {}
    await ctx.report_progress(percent=30, message="Classifying ticket")
    text = f"{ticket.get('subject', '')} {ticket.get('body', '')}".lower()
    if "invoice" in text or "refund" in text or "billed" in text:
        route = "billing.dispute"
        priority = "high"
    else:
        route = "general"
        priority = "normal"
    await ctx.emit_event(name="ticket.classified", data={"route": route, "priority": priority})
    await ctx.report_progress(percent=100, message="Routed")
    return {
        "ticket_id": ticket.get("id"),
        "customer": ticket.get("customer"),
        "route": route,
        "priority": priority,
        "summary": ticket.get("subject"),
        "excerpt": (ticket.get("body") or "")[:160],
    }


async def billing_run(input, ctx):
    case = input or {}
    await ctx.report_progress(percent=25, message="Looking up invoices")
    await asyncio.sleep(0.03)
    await ctx.emit_event(
        name="invoice.matched",
        data={"primary": "INV-9031", "duplicate": "INV-9031-DUP", "amount": 4200},
    )
    await ctx.report_progress(percent=70, message="Preparing refund")
    decision = {
        "ticket_id": case.get("ticket_id"),
        "customer": case.get("customer"),
        "action": "refund_duplicate",
        "refund_amount_usd": 4200,
        "invoice_to_void": "INV-9031-DUP",
        "reason": "Duplicate seat renewal charge confirmed",
        "sla_hours": 24 if case.get("priority") == "high" else 72,
    }
    await ctx.report_progress(percent=100, message="Decision ready")
    return decision


async def reply_run(input, ctx):
    decision = input or {}
    await ctx.report_progress(percent=50, message="Drafting customer reply")
    reply = "\n".join(
        [
            f"Hi {decision.get('customer', 'there')},",
            "",
            f"Thanks for flagging ticket {decision.get('ticket_id')}.",
            f"We confirmed a duplicate charge and will refund "
            f"${decision.get('refund_amount_usd')} by voiding {decision.get('invoice_to_void')}.",
            f"Expected completion within {decision.get('sla_hours')} hours.",
            "",
            "— Support via A2AConnect agent handoff",
        ]
    )
    await ctx.report_progress(percent=100, message="Reply ready")
    return {"reply": reply, "action": decision.get("action")}


async def main() -> None:
    bus = create_bus()
    audit = MemoryAuditLog()

    intake = AgentPeer(
        profile={
            "id": "intake",
            "name": "Intake Agent",
            "capabilities": [{"name": "support.classify", "version": "1"}],
        },
        transport=bus.create_transport("intake"),
        handlers={"support.classify": from_async_fn(intake_run)},
    )
    billing = AgentPeer(
        profile={
            "id": "billing",
            "name": "Billing Specialist",
            "capabilities": [{"name": "billing.dispute", "version": "1"}],
        },
        transport=bus.create_transport("billing"),
        handlers={"billing.dispute": from_async_fn(billing_run)},
    )
    reply_agent = AgentPeer(
        profile={
            "id": "reply",
            "name": "Reply Agent",
            "capabilities": [{"name": "support.reply", "version": "1"}],
        },
        transport=bus.create_transport("reply"),
        handlers={"support.reply": from_async_fn(reply_run)},
    )
    desk = AgentPeer(
        profile={"id": "desk", "name": "Support Desk", "capabilities": []},
        transport=bus.create_transport("desk"),
        audit=audit,
    )

    for peer in (intake, billing, reply_agent, desk):
        peer.start()

    print("\n=== A2AConnect — support desk (agent → agent) ===\n")
    print(f"Ticket: {TICKET['id']} — {TICKET['subject']}\n")

    await desk.hello("intake")
    await desk.hello("billing")
    await desk.hello("reply")

    classified = await desk.offer_task(
        to="intake",
        goal="Classify and route support ticket",
        input=TICKET,
        required_capabilities=["support.classify"],
        timeout_ms=10_000,
    )
    if classified.get("status") != "completed":
        raise SystemExit(f"intake failed: {classified}")
    print("1) Intake classified:")
    print(json.dumps(classified["result"]["output"], indent=2))

    dispute = await desk.offer_task(
        to="billing",
        goal="Resolve billing dispute from classified ticket",
        input=classified["result"]["output"],
        required_capabilities=["billing.dispute"],
        timeout_ms=10_000,
    )
    if dispute.get("status") != "completed":
        raise SystemExit(f"billing failed: {dispute}")
    print("\n2) Billing decision:")
    print(json.dumps(dispute["result"]["output"], indent=2))

    reply = await desk.offer_task(
        to="reply",
        goal="Draft customer reply from billing decision",
        input=dispute["result"]["output"],
        required_capabilities=["support.reply"],
        timeout_ms=10_000,
    )
    if reply.get("status") != "completed":
        raise SystemExit(f"reply failed: {reply}")
    print("\n3) Customer reply:\n")
    print(reply["result"]["output"]["reply"])

    print("\n--- Audit (agent→agent) ---")
    for event in audit.events:
        print(f"  {event.type:<22} peer={event.peer_id or '-'}")

    await asyncio.gather(desk.stop(), intake.stop(), billing.stop(), reply_agent.stop())
    await bus.close()
    print("\n=== support_desk ok ===\n")


if __name__ == "__main__":
    asyncio.run(main())
02

Incident commander → SRE

Ops → planner → graph-style investigator

A P1 checkout incident is planned, then investigated with progress events and a concrete rollback recommendation.

SRE · graph-style · P1

run
python demos/incident_handoff.py

Full source: demos/incident_handoff.py

  1. 1. Agents start on a shared in-memory bus
  2. 2. Orchestrator hellos each peer
  3. 3. offer_task chains results agent → agent
  4. 4. Audit log prints the lifecycle
demos/incident_handoff.py
#!/usr/bin/env python3
"""Executable agent→agent example: incident commander → SRE investigator.

Run:
  python demos/incident_handoff.py
"""

from __future__ import annotations

import asyncio
import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))

from a2aconnect import (  # noqa: E402
    AgentPeer,
    MemoryAuditLog,
    create_bus,
    create_graph_style_adapter,
    from_async_fn,
)


INCIDENT = {
    "id": "INC-2207",
    "service": "checkout-api",
    "severity": "p1",
    "symptom": "checkout 5xx spike to 18% in us-west-2",
    "started_at": "2026-11-21T22:10:00Z",
}


async def plan_run(input, ctx):
    incident = input or {}
    await ctx.report_progress(percent=40, message="Building investigation plan")
    plan = {
        "incident_id": incident.get("id"),
        "service": incident.get("service"),
        "checks": [
            "error_budget burn for checkout-api",
            "deploy markers in last 60m",
            "dependency health: payments-gateway",
        ],
        "hypothesis": "recent deploy or payments-gateway latency",
        "owner_capability": "sre.investigate",
    }
    await ctx.emit_event(name="incident.planned", data={"checks": len(plan["checks"])})
    await ctx.report_progress(percent=100, message="Plan ready")
    return plan


async def investigate_run(input, ctx):
    plan = input or {}
    findings = []
    for i, check in enumerate(plan.get("checks", []), start=1):
        await ctx.report_progress(percent=int(i / max(len(plan["checks"]), 1) * 80), message=check)
        await asyncio.sleep(0.02)
        if "deploy" in check:
            findings.append({"check": check, "result": "deploy d-9841 rolled out 22 minutes ago"})
        elif "payments" in check:
            findings.append({"check": check, "result": "payments-gateway p95 +240ms in us-west-2"})
        else:
            findings.append({"check": check, "result": "error budget burn 4.2× baseline"})
    await ctx.emit_event(name="incident.root_cause", data={"likely": "payments-gateway latency after deploy d-9841"})
    await ctx.report_progress(percent=100, message="Investigation complete")
    return {
        "incident_id": plan.get("incident_id"),
        "service": plan.get("service"),
        "findings": findings,
        "recommendation": "Rollback checkout-api d-9841 or shed traffic from payments-gateway us-west-2",
    }


async def main() -> None:
    bus = create_bus()
    audit = MemoryAuditLog()

    planner = AgentPeer(
        profile={
            "id": "commander",
            "name": "Incident Commander",
            "capabilities": [{"name": "incident.plan", "version": "1"}],
        },
        transport=bus.create_transport("commander"),
        handlers={"incident.plan": from_async_fn(plan_run)},
    )
    sre_adapter = create_graph_style_adapter(node_name="investigate", run=investigate_run)
    sre = AgentPeer(
        profile={
            "id": "sre",
            "name": "SRE Investigator",
            "capabilities": [{"name": "sre.investigate", "version": "1"}],
        },
        transport=bus.create_transport("sre"),
        handlers={"sre.investigate": sre_adapter.to_handler()},
    )
    ops = AgentPeer(
        profile={"id": "ops", "name": "Ops Orchestrator", "capabilities": []},
        transport=bus.create_transport("ops"),
        audit=audit,
    )

    planner.start()
    sre.start()
    ops.start()

    print("\n=== A2AConnect — incident handoff (agent → agent) ===\n")
    print(json.dumps(INCIDENT, indent=2), "\n")

    await ops.hello("commander")
    await ops.hello("sre")

    plan = await ops.offer_task(
        to="commander",
        goal="Plan investigation for P1 checkout incident",
        input=INCIDENT,
        required_capabilities=["incident.plan"],
    )
    if plan.get("status") != "completed":
        raise SystemExit(plan)
    print("1) Commander plan:")
    print(json.dumps(plan["result"]["output"], indent=2))

    probe = await ops.offer_task(
        to="sre",
        goal="Execute investigation plan",
        input=plan["result"]["output"],
        required_capabilities=["sre.investigate"],
    )
    if probe.get("status") != "completed":
        raise SystemExit(probe)
    print("\n2) SRE findings:")
    print(json.dumps(probe["result"]["output"], indent=2))

    print("\n--- Audit ---")
    for event in audit.events:
        print(f"  {event.type:<22} peer={event.peer_id or '-'}")

    await asyncio.gather(ops.stop(), planner.stop(), sre.stop())
    await bus.close()
    print("\n=== incident_handoff ok ===\n")


if __name__ == "__main__":
    asyncio.run(main())
03

Cross-runtime research brief

Orchestrator → researcher → writer

Graph-style research and crew-style writing share the same A2AConnect protocol — no shared agent SDK.

LangGraph-shaped · CrewAI-shaped

run
python demos/two_agents.py

Full source: demos/two_agents.py

  1. 1. Agents start on a shared in-memory bus
  2. 2. Orchestrator hellos each peer
  3. 3. offer_task chains results agent → agent
  4. 4. Audit log prints the lifecycle
demos/two_agents.py
#!/usr/bin/env python3
"""A2AConnect cross-runtime demo (Python).

Orchestrator (custom) → Researcher (graph-style) → Writer (crew-style).

Run: python demos/two_agents.py
"""

from __future__ import annotations

import asyncio
import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))

from a2aconnect import (  # noqa: E402
    AgentPeer,
    MemoryAuditLog,
    create_bus,
    create_crew_style_adapter,
    create_graph_style_adapter,
    with_outbound_buffer,
)


def log(agent: str, message: str) -> None:
    print(f"[{agent}] {message}")


async def main() -> None:
    bus = create_bus()
    audit = MemoryAuditLog()

    async def research_run(input, ctx):
        topic = str((input or {}).get("topic") if isinstance(input, dict) else ctx.offer["goal"])
        log("researcher", f'graph-style invoke for "{topic}"')
        await ctx.report_progress(percent=25, message="Gathering sources")
        await ctx.emit_event(name="source.found", data={"title": f"{topic} overview"})
        await asyncio.sleep(0.04)
        await ctx.report_progress(percent=100, message="Done")
        return {
            "topic": topic,
            "bullets": [
                f"{topic}: enterprises need mixed-runtime handoff",
                "LF A2A owns the peer wire standard; A2AConnect ships adapters + DX",
                "Policy and audit hooks close the production gap",
            ],
            "runtime": "graph-style",
        }

    async def write_run(input, ctx):
        notes = input or {}
        topic = notes.get("topic", "topic")
        bullets = notes.get("bullets", [])
        log("writer", f'crew-style role drafting "{topic}" (from {notes.get("runtime", "peer")})')
        await ctx.report_progress(percent=50, message="Drafting")
        await asyncio.sleep(0.04)
        brief = "\n".join(
            [
                f"# Brief: {topic}",
                "",
                *[f"- {b}" for b in bullets],
                "",
                "_Generated via A2AConnect cross-runtime handoff (graph-style → crew-style)._",
            ]
        )
        await ctx.report_progress(percent=100, message="Brief ready")
        return {"brief": brief, "runtime": "crew-style"}

    research_adapter = create_graph_style_adapter(node_name="research", run=research_run)
    write_adapter = create_crew_style_adapter(role="brief-writer", run=write_run)

    class AllowlistPolicy:
        async def before_offer(self, *, from_agent, to, offer):
            if to in {"researcher", "writer"}:
                return {"allow": True}
            return {"allow": False, "reason": f"Peer {to} is not allowlisted"}

    researcher = AgentPeer(
        profile={
            "id": "researcher",
            "name": "Researcher",
            "version": "0.1.0",
            "description": "Graph-style runtime adapter",
            "capabilities": [{"name": "research.web", "version": "1"}],
        },
        transport=with_outbound_buffer(bus.create_transport("researcher")),
        handlers={"research.web": research_adapter.to_handler()},
        on_message=lambda m: log("researcher", f"← {m['type']} from {m['from']}")
        if str(m["type"]).startswith(("task.", "hello", "event"))
        else None,
    )

    writer = AgentPeer(
        profile={
            "id": "writer",
            "name": "Writer",
            "version": "0.1.0",
            "description": "Crew-style runtime adapter",
            "capabilities": [{"name": "write.brief", "version": "1"}],
        },
        transport=with_outbound_buffer(bus.create_transport("writer")),
        handlers={"write.brief": write_adapter.to_handler()},
        on_message=lambda m: log("writer", f"← {m['type']} from {m['from']}")
        if str(m["type"]).startswith(("task.", "hello"))
        else None,
    )

    orchestrator = AgentPeer(
        profile={
            "id": "orchestrator",
            "name": "Orchestrator",
            "version": "0.1.0",
            "description": "Custom Python orchestrator",
            "capabilities": [],
        },
        transport=bus.create_transport("orchestrator"),
        audit=audit,
        policy=AllowlistPolicy(),
        on_message=lambda m: log("orchestrator", f"← {m['type']} from {m['from']}")
        if m["type"]
        in {"hello.ack", "task.accept", "task.progress", "task.result", "event"}
        else None,
    )

    researcher.start()
    writer.start()
    orchestrator.start()

    print("\n=== A2AConnect — cross-runtime E2E demo (Python) ===\n")
    print("Runtimes: custom orchestrator → graph-style researcher → crew-style writer\n")

    await orchestrator.hello("researcher")
    await orchestrator.hello("writer")
    await asyncio.sleep(0.02)

    remotes = ", ".join(r.agent_id for r in orchestrator.list_remotes())
    log("orchestrator", f"Sessions: {remotes}")

    research = await orchestrator.offer_task(
        to="researcher",
        goal="Research agent interop",
        input={"topic": "agent interop runtimes"},
        required_capabilities=["research.web"],
        timeout_ms=10_000,
        retries=1,
    )
    if research.get("status") != "completed":
        print("Research failed:", research)
        raise SystemExit(1)

    log("orchestrator", "Research complete")
    print(json.dumps(research["result"]["output"], indent=2))

    write = await orchestrator.offer_task(
        to="writer",
        goal="Write a short brief from research notes",
        input=research["result"]["output"],
        required_capabilities=["write.brief"],
        timeout_ms=10_000,
    )
    if write.get("status") != "completed":
        print("Write failed:", write)
        raise SystemExit(1)

    log("orchestrator", "Brief complete\n")
    print(write["result"]["output"]["brief"])

    print("\n--- Audit trail ---")
    for event in audit.events:
        task = f" task={event.task_id[:12]}…" if event.task_id else ""
        print(f"  {event.type:<22} peer={event.peer_id or '-'}{task}")

    print("\n=== demo ok ===\n")

    await asyncio.gather(orchestrator.stop(), researcher.stop(), writer.stop())
    await bus.close()


if __name__ == "__main__":
    asyncio.run(main())
04

Minimal research handoff

Orchestrator → researcher

Smallest agent→agent path: hello, offer_task on research.web, print findings + audit.

minimal · research.web

run
python demos/quickstart.py

Full source: demos/quickstart.py

  1. 1. Agents start on a shared in-memory bus
  2. 2. Orchestrator hellos each peer
  3. 3. offer_task chains results agent → agent
  4. 4. Audit log prints the lifecycle
demos/quickstart.py
#!/usr/bin/env python3
"""Minimal A2AConnect quickstart — orchestrator hands research to a peer.

Run from repo root:
  pip install -e ".[dev]"
  python demos/quickstart.py
"""

from __future__ import annotations

import asyncio
import json
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))

from a2aconnect import AgentPeer, MemoryAuditLog, create_bus  # noqa: E402
from a2aconnect.adapters import from_async_fn  # noqa: E402


async def research_run(input, ctx):
    topic = (input or {}).get("topic", ctx.offer["goal"])
    await ctx.report_progress(percent=40, message=f"Researching {topic}")
    await ctx.emit_event(name="source.found", data={"title": f"{topic} overview"})
    await asyncio.sleep(0.05)
    await ctx.report_progress(percent=100, message="Done")
    return {
        "topic": topic,
        "findings": [
            f"{topic}: mixed-runtime fleets need a shared handoff layer",
            "LF A2A is the peer wire standard; A2AConnect is the interop runtime",
            "Policy and audit hooks make production fleets operable",
        ],
    }


async def main() -> None:
    bus = create_bus()
    audit = MemoryAuditLog()

    researcher = AgentPeer(
        profile={
            "id": "researcher",
            "name": "Researcher",
            "capabilities": [{"name": "research.web", "version": "1"}],
        },
        transport=bus.create_transport("researcher"),
        handlers={"research.web": from_async_fn(research_run)},
    )
    orchestrator = AgentPeer(
        profile={"id": "orchestrator", "name": "Orchestrator", "capabilities": []},
        transport=bus.create_transport("orchestrator"),
        audit=audit,
    )

    researcher.start()
    orchestrator.start()

    await orchestrator.hello("researcher")
    outcome = await orchestrator.offer_task(
        to="researcher",
        goal="Research agent interop",
        input={"topic": "agent interop runtimes"},
        required_capabilities=["research.web"],
        timeout_ms=10_000,
    )

    if outcome.get("status") != "completed":
        print("FAILED:", json.dumps(outcome, indent=2, default=str))
        raise SystemExit(1)

    print("Research result:")
    print(json.dumps(outcome["result"]["output"], indent=2))
    print("\nAudit trail:")
    for event in audit.events:
        print(f"  {event.type:<22} peer={event.peer_id or '-'}")

    await asyncio.gather(orchestrator.stop(), researcher.stop())
    await bus.close()
    print("\n=== quickstart ok ===")


if __name__ == "__main__":
    asyncio.run(main())