Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:A2aproject A2a java Client

From Leeroopedia
Knowledge Sources
Domains Client, Message_Exchange
Last Updated 2026-10-29 00:00 GMT

Overview

Concrete primary client API for communicating with A2A agents, providing message sending, task management, streaming subscription, and push notification configuration across all transport protocols.

Description

The `Client` class is the main entry point for A2A client applications. It provides a transport-agnostic API for:

  • Message exchange: `sendMessage()` sends messages in blocking or streaming mode depending on `ClientConfig.isStreaming()` and `AgentCapabilities.streaming()`
  • Task management: `getTask()`, `listTasks()`, `cancelTask()` for task lifecycle queries
  • Stream subscription: `subscribeToTask()` enables resubscription to ongoing tasks after disconnection
  • Push notifications: `createTaskPushNotificationConfiguration()`, `getTaskPushNotificationConfiguration()`, `listTaskPushNotificationConfigurations()`, `deleteTaskPushNotificationConfigurations()`
  • Extended card: `getExtendedAgentCard()` retrieves the agent's extended card at runtime

The client implements `AutoCloseable` and should be used with try-with-resources to ensure proper cleanup of HTTP connections, gRPC channels, and other resources.

In streaming mode, `sendMessage()` returns immediately and events are delivered asynchronously to registered consumers as `ClientEvent` instances (`MessageEvent`, `TaskEvent`, `TaskUpdateEvent`). In blocking mode, `sendMessage()` blocks until the agent completes the task, then invokes consumers with the final result.

The `ClientTaskManager` internally tracks task state across streaming events, merging `TaskStatusUpdateEvent` and `TaskArtifactUpdateEvent` updates to maintain the complete current task state accessible via `TaskUpdateEvent.getTask()`.

Usage

  • Blocking request-response: Default mode — send a message, block for the response
  • Streaming updates: Enable `ClientConfig.setStreaming(true)` to receive incremental `TaskUpdateEvent` instances
  • Resubscription: Use `subscribeToTask()` to resume receiving events for an ongoing task after reconnection
  • Multi-subscriber fan-out: Multiple clients can subscribe to the same task; the server fans out events to all subscribers

Code Reference

Source Location

  • Repository: a2a-java
  • File: `client/base/src/main/java/org/a2aproject/sdk/client/Client.java`
  • Lines: L186-722

Signature

public class Client extends AbstractClient {
    Client(AgentCard agentCard, ClientConfig clientConfig, ClientTransport clientTransport,
           List<BiConsumer<ClientEvent, AgentCard>> consumers,
           @Nullable Consumer<Throwable> streamingErrorHandler);

    // Builder
    public static ClientBuilder builder(AgentCard agentCard);

    // Message sending
    void sendMessage(@NonNull Message request,
                      @NonNull List<BiConsumer<ClientEvent, AgentCard>> consumers,
                      @Nullable Consumer<Throwable> streamingErrorHandler,
                      @Nullable ClientCallContext context) throws A2AClientException;

    void sendMessage(@NonNull Message request,
                      @Nullable TaskPushNotificationConfig pushNotificationConfiguration,
                      @Nullable Map<String, Object> metadata,
                      @Nullable ClientCallContext context) throws A2AClientException;

    void sendMessage(@NonNull MessageSendParams messageSendParams,
                      @NonNull List<BiConsumer<ClientEvent, AgentCard>> consumers,
                      @Nullable Consumer<Throwable> streamingErrorHandler,
                      @Nullable ClientCallContext context) throws A2AClientException;

    // Task management
    Task getTask(TaskQueryParams request, @Nullable ClientCallContext context) throws A2AClientException;
    ListTasksResult listTasks(ListTasksParams request, @Nullable ClientCallContext context) throws A2AClientException;
    Task cancelTask(CancelTaskParams request, @Nullable ClientCallContext context) throws A2AClientException;

    // Stream subscription
    void subscribeToTask(@NonNull TaskIdParams request,
                         @NonNull List<BiConsumer<ClientEvent, AgentCard>> consumers,
                         @Nullable Consumer<Throwable> streamingErrorHandler,
                         @Nullable ClientCallContext context) throws A2AClientException;

    // Push notifications
    TaskPushNotificationConfig createTaskPushNotificationConfiguration(
        TaskPushNotificationConfig request, @Nullable ClientCallContext context) throws A2AClientException;
    TaskPushNotificationConfig getTaskPushNotificationConfiguration(
        GetTaskPushNotificationConfigParams request, @Nullable ClientCallContext context) throws A2AClientException;
    ListTaskPushNotificationConfigsResult listTaskPushNotificationConfigurations(
        ListTaskPushNotificationConfigsParams request, @Nullable ClientCallContext context) throws A2AClientException;
    void deleteTaskPushNotificationConfigurations(
        DeleteTaskPushNotificationConfigParams request, @Nullable ClientCallContext context) throws A2AClientException;

    // Extended card
    AgentCard getExtendedAgentCard(@Nullable String tenant, @Nullable ClientCallContext context) throws A2AClientException;

    // Resource management
    void close();
}

Import

import org.a2aproject.sdk.client.Client;

I/O Contract

Inputs

Name Type Required Description
request Message Yes (sendMessage) User message created via A2A.toUserMessage()
consumers List<BiConsumer<ClientEvent, AgentCard>> For streaming Event consumer callbacks
pushNotificationConfiguration TaskPushNotificationConfig No Webhook config for task updates
metadata Map<String, Object> No Custom metadata attached to request
request TaskIdParams Yes (subscribeToTask) Task ID to subscribe to
request TaskQueryParams Yes (getTask) Task ID to query
request CancelTaskParams Yes (cancelTask) Task ID to cancel

Outputs

Name Type Description
Events ClientEvent MessageEvent, TaskEvent, TaskUpdateEvent delivered to consumers
getTask() returns Task Current task state
listTasks() returns ListTasksResult Matching tasks
cancelTask() returns Task Canceled task state
A2AClientException Exception Communication or protocol errors

Usage Examples

Blocking Message Exchange

import org.a2aproject.sdk.A2A;
import org.a2aproject.sdk.client.Client;
import org.a2aproject.sdk.client.ClientEvent;
import org.a2aproject.sdk.client.MessageEvent;

AgentCard card = A2A.getAgentCard("http://localhost:9999");

try (Client client = Client.builder(card)
    .withTransport(JSONRPCTransport.class, new JSONRPCTransportConfigBuilder())
    .addConsumer((event, c) -> {
        if (event instanceof MessageEvent me) {
            System.out.println("Agent says: " + me.getMessage().parts());
        }
    })
    .build()) {

    // Blocks until agent completes
    client.sendMessage(A2A.toUserMessage("Tell me a joke"));
}

Streaming with Task Updates

ClientConfig streamingConfig = new ClientConfig.Builder()
    .setStreaming(true)
    .build();

try (Client client = Client.builder(card)
    .withTransport(JSONRPCTransport.class, new JSONRPCTransportConfigBuilder())
    .clientConfig(streamingConfig)
    .addConsumer((event, c) -> {
        if (event instanceof TaskUpdateEvent tue) {
            TaskState state = tue.getTask().status().state();
            System.out.println("Task state: " + state);

            if (tue.getUpdateEvent() instanceof TaskArtifactUpdateEvent update) {
                System.out.println("New content: " + update.artifact().parts());
            }
        }
    })
    .streamingErrorHandler(throwable ->
        System.err.println("Stream error: " + throwable))
    .build()) {

    // Returns immediately; events arrive asynchronously
    client.sendMessage(A2A.toUserMessage("Summarize this document"));
}

Resubscription After Disconnection

// Subscribe to an existing task's event stream
client.subscribeToTask(
    new TaskIdParams("task-123"),
    List.of((event, c) -> {
        if (event instanceof TaskUpdateEvent tue) {
            System.out.println("Resumed - status: " + tue.getTask().status().state());
        }
    }),
    throwable -> System.err.println("Subscribe error: " + throwable),
    null  // no custom context
);

Related Pages

Implements Principle

Requires Environment

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment