Advanced
Topics that aren't part of the day-to-day A2A path: human-in-the-loop, transparent reconnects on streaming drops, plugging in a custom executor, and the error hierarchy.
Human-in-the-Loop via input_required#
When a server-side executor calls requires_input(...) mid-task, the A2A server transitions the task to TASK_STATE_INPUT_REQUIRED and surfaces the prompt to the client. The AG2 client invokes the local agent's hitl_hook with the prompt and continues the same turn with the reply — the server prompt does not leak into the final response text.
A2AConfig.input_required_timeout caps how long the client waits on the hook. None (default) waits indefinitely — which matches the behaviour of ConversationContext.input in regular agents.
See Human in the Loop for the underlying hitl_hook contract.
Streaming Reconnect#
Streaming connections drop. Network blips, load balancer recycles, idle timeouts — the SSE channel breaks, and the client needs to recover without losing partially-streamed artifacts.
The A2A client keeps internal drive state across drops: on A2AClientError mid-stream it issues a fresh subscribe against the same task_id and continues from where it failed. The new stream opens with the task as it stands, so text produced while the client was disconnected is recovered from that snapshot. Artifacts are reconciled by artifact_id (messages by message_id): an update that restates what was already received adds nothing, and a completed artifact is never applied twice. An update that would change an artifact already closed with last_chunk is either a replay or a server breaking the spec (§4.2.2), so it is not applied as it streams: once the run settles, the client reads the task back with one GetTask and takes that artifact's stored content, which is what a polling client sees. Application code sees a single uninterrupted reply.
If the task finished while the stream was down, the server refuses the subscription; the client then reads the final task with get_task and builds the reply from it, so a dropped connection at the very end does not fail the call.
The client can only resubscribe once it knows the task id, which arrives with the first event. A connection lost before that raises A2AReconnectError without retrying: sending the message again would start a second task.
| Field | Default | Purpose |
|---|---|---|
max_reconnects | 3 | Total reconnect attempts before giving up with A2AReconnectError |
reconnect_backoff | 0.5 | Seconds to wait before the first attempt; doubles on each following one (no jitter) |
When attempts are exhausted the client raises A2AReconnectError(attempts=N). Catch it to fall back to a polling re-fetch via get_task if you need recovery beyond the streaming budget.
Custom AgentExecutor#
A2AServer defaults to wrapping the supplied Agent in AG2's standard AgentExecutor. When you need behaviour that doesn't fit Agent.ask — a HITL-first turn, a multi-agent pipeline, a non-standard task lifecycle — drop in your own executor:
The executor owns the entire request lifecycle: parsing the inbound message, emitting status updates and artifacts to the event_queue, and signalling terminal state. The wrapped agent passed to A2AServer(agent_stub, ...) is still used for card metadata (name, description, etc.) — make it a stub if a real agent doesn't fit your design.
Errors#
All A2A errors live in ag2.a2a.errors and inherit from A2AError. Catch A2AError for everything; catch the specifics when you want to react differently.
| Exception | Raised when |
|---|---|
A2AError | Base class — catch this for any A2A failure |
A2AInvalidCardError | The card is missing data required to connect (no supported_interfaces, no usable URL) |
A2AIncompatibleProtocolVersionError | The interface AG2 selected declares an A2A protocol version older than 1.0 — err.protocol_version and err.transport hold what was advertised |
A2AClientToolsNotSupportedError | Client passed tools= but the server card doesn't advertise the urn:ag2:client-tools:v1 extension |
A2AExtensionNotSupportedError | Client activated an extension URI the card doesn't advertise, or the card marks one required=True that the client didn't activate — err.uris holds the unreconciled URIs (see Extensions) |
A2ACardSignatureError | A card failed JWS verification — err.source says which card (see Card Signing) |
A2AStaleCardSignatureError | Server-side: a build_* call was handed an already-signed card whose capability flags AG2 has to flip, with no card_signer to re-sign it (see Card Signing) |
A2AReconnectError | Streaming reconnect attempts exhausted — err.attempts holds the count |
A2ATaskTerminalError | Base for the terminal-state errors below; carries err.task with the final Task (status, history, artifacts) |
A2ATaskFailedError | Task ended in TASK_STATE_FAILED |
A2ATaskRejectedError | Task ended in TASK_STATE_REJECTED |
A2ATaskCancelledError | Task ended in TASK_STATE_CANCELED — err.task.artifacts holds the partial text received before the cancellation |
A2ATaskAuthRequiredError | Task stopped in TASK_STATE_AUTH_REQUIRED, an interrupted state rather than a terminal one (spec §4.1.3). Per A2A spec §7.6 the agent expects credentials out-of-band — apply them and retry |
Catch A2ATaskTerminalError to handle any terminal failure uniformly; switch on the concrete subclass when the recovery path differs (e.g. retry with auth on AuthRequired, surface the error to the operator on Failed / Rejected, treat Cancelled as an operator or server decision rather than a fault).
Testing Helpers#
ag2.a2a.testing provides utilities for in-process A2A tests — no real socket, no port binding.
| Helper | Purpose |
|---|---|
make_test_client_factory(server, url=..., card=..., timeout=...) | httpx.AsyncClient factory dispatching JSON-RPC into the server's ASGI app via httpx.ASGITransport |
make_test_rest_client_factory(server, url=..., card=..., timeout=...) | Same idea for REST — builds the REST app and a card declaring only the REST interface |
pick_free_port(host="127.0.0.1") | Probe a free TCP port. Used by gRPC tests since gRPC has no in-process transport equivalent |
ToolRoundsConfig(*rounds) | Script a served agent one tool round at a time — a Turn, or a TestConfig for a round that streams before it ends — for tests where the client runs tools and the server continues the task |
ObservedAgentExecutor(agent, *observers) | Serve agent with observers that see the request's whole task lifecycle, including WORKING and the terminal status, which observers on the agent miss because they only run during the model turn. They see what this request puts on the wire: a task parked in INPUT_REQUIRED and cancelled afterwards, or one cancelled through another replica, is closed by the SDK outside the request, so read its final state with get_task |
TaskStatusRecorder() | Observer recording every A2ATaskStatusUpdate state in delivery order; await recorder.wait_for(state) waits for one |
TurnGate() | A server tool, gate.hold, that keeps the task working until gate.release(), so a test can cancel or inspect it mid-turn |
The server builds a fresh LLM client for every request, so a single TestConfig would replay its first turn after each client-tool round trip. ToolRoundsConfig picks the round from the conversation history instead:
To assert on the server side of a task's lifecycle, serve the agent through ObservedAgentExecutor:
Pass card= when the default build_card(agent, url=url) can't express what the test needs — a custom extensions list, for instance. It defaults to None, which keeps the auto-built card.