Skip to main content

A2aClient

Struct A2aClient 

Source
pub struct A2aClient { /* private fields */ }
Expand description

A client for communicating with A2A-compliant agents.

All A2A protocol methods are available as async methods. Create a client via ClientBuilder or the A2aClient::from_card shorthand.

§Example

use a2a_protocol_client::ClientBuilder;

let client = ClientBuilder::new("http://localhost:8080").build()?;

Implementations§

Source§

impl A2aClient

Source

pub fn from_card(card: &AgentCard) -> Result<A2aClient, ClientError>

Creates a client from an AgentCard using the recommended defaults.

Uses the first interface the card lists that this client supports, as ClientBuilder::from_card does (spec §8.3.2).

§Errors

Returns crate::error::ClientError::InvalidEndpoint if the agent card URL is malformed or the transport cannot be constructed.

Source

pub const fn config(&self) -> &ClientConfig

Returns a reference to the active client configuration.

Source

pub const fn honours_idempotency(&self) -> bool

Whether the agent is known to honour an idempotency key (a2a_protocol_types::idempotency): its card advertised the extension (ClientBuilder::from_card), or the builder was told so with ClientBuilder::with_peer_honouring_idempotency. Only then is a keyed send retried after an ambiguous failure, and only then does Delegation attach a key of its own.

Source§

impl A2aClient

Source

pub async fn get_extended_agent_card(&self) -> Result<AgentCard, ClientError>

Fetches the full (private) agent card, authenticating the request.

Calls GetExtendedAgentCard. The returned card may include private skills, security schemes, or additional interfaces not exposed in the public /.well-known/agent-card.json.

The caller must have registered auth credentials via crate::auth::AuthInterceptor or equivalent before calling this method.

A client built from a card checks later calls against the capabilities and security requirements this card declares, in place of the public card’s (spec §3.1.11, §13.3).

§Errors

Returns ClientError on transport or protocol errors, ClientError::InvalidAgentResponse for a card that breaks the rules a server publishes one by (AgentCard::validate), and ClientError::Protocol for a card with no signature, or none that verifies, when the client verifies cards (ClientBuilder::with_card_signature_keys, set by ClientBuilder::from_signed_card; both need the signing feature). In each case nothing is adopted from it.

Source§

impl A2aClient

Source

pub async fn follow_task( &self, id: impl Into<String>, poll_every: Duration, ) -> Result<TaskFollow<'_>, ClientError>

Follows task id until it ends, for a client that holds no stream for it: after a send that returned a task in TASK_STATE_AUTH_REQUIRED (spec §7.6.2), or INPUT_REQUIRED, or return_immediately.

Subscribes (SubscribeToTask) when the agent can stream, and polls GetTask every poll_every when it cannot: its card does not declare streaming, or it answers the subscription UnsupportedOperation (as it does for a task already terminal). A subscription that is cut is reopened from the last event id and, when that does not work, followed by polling: see TaskFollow::next. Registering a webhook, the spec’s third way, is create_push_config with a WebhookReceiver on your side.

§Errors

The subscription’s error, other than the two that make it poll.

Source§

impl A2aClient

Source

pub async fn renew_lease( &self, params: TaskQueryParams, ) -> Result<Task, ClientError>

Renews the lease of a task this client delegated with one (a2a_protocol_types::lease, ADR 0020) and returns the task: a GetTask that activates the lease extension, beside any extensions this client already asks for.

A WebSocket transport sends A2A-Extensions only with its upgrade, so over WebSocket this renews only when the connection asked for the lease extension (WebSocketTransportConfig::with_extensions).

§Errors

As get_task.

Source

pub async fn renew_lease_status( &self, params: TaskQueryParams, ) -> Result<Task, ClientError>

renew_lease, asking for the lease alone (LEASE_RENEWAL_ONLY_URI, ADR 0044): a server that knows it answers with the task’s id, context and status, without history, artifacts or metadata, so the renewal costs neither side the task’s content. A server that does not know it answers the whole task. A delegation’s own renewals use this.

§Errors

As get_task.

Source§

impl A2aClient

Source

pub async fn create_push_config( &self, config: TaskPushNotificationConfig, ) -> Result<TaskPushNotificationConfig, ClientError>

Registers or replaces a push notification configuration for a task.

Calls CreateTaskPushNotificationConfig. Returns the configuration as stored by the server (including the server-assigned id).

§Errors

Returns ClientError::Protocol with a2a_protocol_types::ErrorCode::PushNotificationNotSupported if the agent does not support push notifications, and ClientError::InsecureWebhook — before sending anything — if the webhook URL is http:// to a non-loopback host and the client was built with require_https_webhooks. Without that, such a URL is sent and a warning logged (spec §13.2).

Source

pub async fn set_push_config( &self, config: TaskPushNotificationConfig, ) -> Result<TaskPushNotificationConfig, ClientError>

👎Deprecated since 0.16.0:

use create_push_config; removed no earlier than 0.17.0

create_push_config, under the name it had before 0.16.0. The wire method is CreateTaskPushNotificationConfig (ADR 0053).

§Errors

As create_push_config.

Source

pub async fn get_push_config( &self, task_id: impl Into<String>, id: impl Into<String>, ) -> Result<TaskPushNotificationConfig, ClientError>

Retrieves a push notification configuration by task ID and config ID.

Calls GetTaskPushNotificationConfig.

§Errors

Returns ClientError on transport or protocol errors.

Source

pub async fn list_push_configs( &self, params: ListPushConfigsParams, ) -> Result<ListPushConfigsResponse, ClientError>

Lists push notification configurations for a task with pagination.

Calls ListTaskPushNotificationConfigs.

§Errors

Returns ClientError on transport or protocol errors.

Source

pub async fn delete_push_config( &self, task_id: impl Into<String>, id: impl Into<String>, ) -> Result<(), ClientError>

Deletes a push notification configuration.

Calls DeleteTaskPushNotificationConfig.

The result is google.protobuf.Empty, so besides the spec’s {} a success may also arrive as a JSON-RPC response with no result, a null result, or an HTTP+JSON 2xx with no body — the forms a2a-go v2.5.0 sends. All of them are Ok(()).

§Errors

Returns ClientError on transport or protocol errors.

Source§

impl A2aClient

Source

pub async fn send_message( &self, params: MessageSendParams, ) -> Result<SendMessageResponse, ClientError>

Sends a message to the agent and waits for a complete response.

Calls the SendMessage JSON-RPC method. The agent may respond with either a completed Task or an immediate Message.

Client-level configuration (e.g. return_immediately, history_length) is automatically merged into the request parameters. Per-request values take precedence.

With ClientBuilder::with_blocking_over_stream on, an agent whose card declares streaming is sent to as a stream and answered with the stored task, so a load balancer’s idle timeout does not cut a long turn.

§Errors

Returns ClientError on transport, serialization, or protocol errors.

§Retrying an ambiguous failure

A send whose connection drops after the request is on the wire is not retried by default, because re-sending it could start a second task. Attach a key with a2a_protocol_types::idempotency::set_key and the retry becomes safe against a peer that honours it: the server returns the task the first attempt created instead of starting a second. Servers advertise support as IDEMPOTENCY_EXTENSION_URI on their agent card, and the client requires that evidence before it will retry a keyed send — a peer that never advertised it may simply ignore the key and run the send twice. ClientBuilder::from_card reads the advertisement; a client built for a bare endpoint asserts it with ClientBuilder::with_peer_honouring_idempotency.

Source

pub async fn stream_message( &self, params: MessageSendParams, ) -> Result<EventStream, ClientError>

Sends a message and returns a streaming EventStream of progress events.

Calls the SendStreamingMessage JSON-RPC method. The agent responds with an SSE stream of a2a_protocol_types::StreamResponse events.

§Errors

Returns ClientError on transport or protocol errors.

Source§

impl A2aClient

Source

pub async fn get_task( &self, params: TaskQueryParams, ) -> Result<Task, ClientError>

Retrieves a task by ID.

Calls the GetTask JSON-RPC method.

§Errors

Returns ClientError::Protocol with a2a_protocol_types::ErrorCode::TaskNotFound if no task with the given ID exists.

Source

pub async fn list_tasks( &self, params: ListTasksParams, ) -> Result<TaskListResponse, ClientError>

Lists tasks visible to the caller.

Calls the ListTasks JSON-RPC method. Results are paginated; use params.page_token to fetch subsequent pages.

status_timestamp_after is sent in the form spec §5.6.1 puts every timestamp in, UTC with a Z suffix: a value with an offset (+02:00) or a lower-case t/z is rewritten to it, at millisecond precision, before any binding sends it (the gRPC conversion always did). Until 2026-10-23 the JSON bindings sent it as given.

§Errors

Returns ClientError on transport or protocol errors, and, without sending anything, ClientError::Protocol with InvalidParams when status_timestamp_after is not an ISO 8601 date-time.

Source

pub async fn cancel_task( &self, id: impl Into<String>, ) -> Result<Task, ClientError>

Requests cancellation of a running task.

Calls the CancelTask JSON-RPC method. Returns the task in its post-cancellation state.

§Errors

Returns ClientError::Protocol with a2a_protocol_types::ErrorCode::TaskNotCancelable if the task cannot be canceled in its current state.

Source

pub async fn subscribe_to_task( &self, id: impl Into<String>, ) -> Result<EventStream, ClientError>

Subscribes to the SSE stream for an in-progress task.

Calls the SubscribeToTask method. Useful after an unexpected disconnection from a SendStreamingMessage call.

Events emitted while disconnected are not replayed; use subscribe_to_task_from with the last event id to have them replayed.

§Errors

Returns ClientError::Protocol with a2a_protocol_types::ErrorCode::TaskNotFound if the task is not in a streaming-eligible state.

Source

pub async fn subscribe_to_task_from( &self, id: impl Into<String>, last_event_id: impl Into<String>, ) -> Result<EventStream, ClientError>

Resubscribes to a task, asking the server to replay every event after last_event_id before the live stream.

last_event_id is what EventStream::last_event_id returned on the stream that broke, or what ClientError::IncompleteStream carries. It is sent as the Last-Event-ID header; a server that keeps an event log (this repository’s does, over JSON-RPC and HTTP+JSON) replays from exactly there, after the Task snapshot. The offset is exclusive, and a server that cannot resume ignores the header and sends the snapshot and the live stream, as subscribe_to_task does.

let mut stream = client.subscribe_to_task(task_id).await?;
loop {
    match stream.next().await {
        Some(Ok(_event)) => { /* handle */ }
        Some(Err(ClientError::IncompleteStream { last_event_id: Some(id), .. })) => {
            stream = client.subscribe_to_task_from(task_id, id).await?;
        }
        Some(Err(e)) => return Err(e),
        None => break,
    }
}
§Errors

As subscribe_to_task.

Trait Implementations§

Source§

impl Debug for A2aClient

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> FutureExt for T

§

fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
§

fn with_current_context(self) -> WithContext<Self> ⓘ

Attaches the current Context to this type, returning a WithContext wrapper. Read more
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> IntoRequest<T> for T

§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
§

impl<L> LayerExt<L> for L

§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in [Layered].
§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more