a2a_client/lib.rs
1//! # a2a-client
2//!
3//! Reusable Rust library for building web-based frontends for A2A (Agent-to-Agent) Protocol agents.
4//!
5//! ## Overview
6//!
7//! This library provides components and utilities for creating web applications that interact
8//! with A2A protocol agents. It wraps the lower-level [`a2a-rs`](https://docs.rs/a2a-rs) clients
9//! with a web-friendly API and includes ready-to-use components for common use cases.
10//!
11//! ## Features
12//!
13//! - **Unified Client API** - Single interface for both HTTP and WebSocket transports
14//! - **SSE Streaming** - Server-Sent Events with automatic fallback to HTTP polling
15//! - **View Models** - Ready-to-use view models for tasks and messages
16//! - **Auto-reconnection** - Resilient WebSocket connections with retry logic
17//! - **Type-safe** - Leverages Rust's type system for protocol correctness
18//!
19//! ## Quick Start
20//!
21//! ### Basic HTTP Client
22//!
23//! ```rust,no_run
24//! use a2a_client::WebA2AClient;
25//! use a2a_rs::domain::Message;
26//! use a2a_rs::Transport;
27//!
28//! # #[tokio::main]
29//! # async fn main() -> anyhow::Result<()> {
30//! // Create a client connected to your A2A agent
31//! let client = WebA2AClient::new_http("http://localhost:8080".to_string());
32//!
33//! // Send a message
34//! let message = Message::user_text("Hello, agent!".to_string(), "msg-1".to_string());
35//!
36//! let task = client.transport.send_task_message("task-1", &message, None, None).await?;
37//! println!("Task ID: {}", task.id);
38//! # Ok(())
39//! # }
40//! ```
41//!
42//! ### With SSE Streaming via ConnectRPC
43//!
44//! ```rust
45//! use a2a_client::WebA2AClient;
46//!
47//! // Create client with HTTP (which handles ConnectRPC streaming automatically)
48//! let client = WebA2AClient::new_http("http://localhost:8080".to_string());
49//!
50//! println!("HTTP client configured for streaming!");
51//! ```
52//!
53//! ### SSE Streaming with Axum (requires `axum-components` feature)
54//!
55//! ```rust,ignore
56//! # #[cfg(feature = "axum-components")]
57//! # {
58//! use a2a_client::{WebA2AClient, components::create_sse_stream};
59//! use axum::{Router, routing::get, extract::{State, Path}};
60//! use std::sync::Arc;
61//!
62//! # #[tokio::main]
63//! # async fn main() -> anyhow::Result<()> {
64//! let client = Arc::new(WebA2AClient::new_http("http://localhost:8080".to_string()));
65//!
66//! let app = Router::new()
67//! .route("/stream/:task_id", get(stream_handler))
68//! .with_state(client);
69//!
70//! // Start your Axum server...
71//! # Ok(())
72//! # }
73//!
74//! async fn stream_handler(
75//! State(client): State<Arc<WebA2AClient>>,
76//! Path(task_id): Path<String>,
77//! ) -> axum::response::sse::Sse<impl futures::Stream<Item = Result<axum::response::sse::Event, std::convert::Infallible>>> {
78//! create_sse_stream(client, task_id)
79//! }
80//! # }
81//! ```
82//!
83//! ## Components
84//!
85//! - [`WebA2AClient`] - Main client wrapper for HTTP and WebSocket transports
86//! - [`components::TaskView`] - View model for displaying tasks in lists
87//! - [`components::MessageView`] - View model for displaying individual messages
88//! - [`components::create_sse_stream`] - SSE stream creation with auto-fallback (requires `axum-components`)
89//! - [`utils::formatters`] - Formatting utilities for A2A types
90//!
91//! ## Feature Flags
92//!
93//! - `axum-components` (default) - Enables Axum-specific SSE streaming components
94//!
95//! ## Integration
96//!
97//! This library integrates with:
98//! - [`a2a-rs`](https://docs.rs/a2a-rs) - Core A2A protocol implementation
99//! - [`a2a-agents`](https://docs.rs/a2a-agents) - Declarative agent framework
100//! - Any agent implementing the A2A Protocol v1.0.0
101//!
102//! ## Examples
103//!
104//! See the `examples/` directory for complete working examples of different use cases.
105
106pub mod components;
107pub mod error;
108pub mod utils;
109
110// Re-export commonly used types
111pub use error::{ClientError, Result};
112
113use std::pin::Pin;
114use std::sync::Arc;
115
116use a2a_rs::domain::A2AError;
117use a2a_rs::{HttpClient, RetryPolicy, StreamEvent, Transport, subscribe_resilient};
118use futures::Stream;
119
120/// Web-friendly A2A client that wraps both HTTP and WebSocket clients.
121///
122/// This is the main entry point for interacting with A2A agents from web applications.
123/// It provides a unified interface for both HTTP and WebSocket transports, with automatic
124/// fallback and retry logic.
125///
126/// # Examples
127///
128/// ## HTTP-only client
129///
130/// ```rust
131/// use a2a_client::WebA2AClient;
132///
133/// let client = WebA2AClient::new_http("http://localhost:8080".to_string());
134/// ```
135///
136/// ## Client configured for streaming
137///
138/// ```rust
139/// use a2a_client::WebA2AClient;
140///
141/// let client = WebA2AClient::new_http("http://localhost:8080".to_string());
142/// ```
143///
144/// ## Auto-detecting transports
145///
146/// ```rust,no_run
147/// use a2a_client::WebA2AClient;
148///
149/// # #[tokio::main]
150/// # async fn main() -> anyhow::Result<()> {
151/// let client = WebA2AClient::auto_connect("http://localhost:8080").await?;
152/// # Ok(())
153/// # }
154/// ```
155pub struct WebA2AClient {
156 /// The negotiated transport for A2A requests and streaming.
157 ///
158 /// Held behind an `Arc<dyn Transport>` so the client is agnostic to the
159 /// underlying wire protocol (ConnectRPC, JSON-RPC 2.0, …) and can share the
160 /// transport with a reconnecting subscription stream.
161 pub transport: Arc<dyn Transport>,
162}
163
164impl WebA2AClient {
165 /// Create a builder for configuring the client.
166 ///
167 /// # Examples
168 ///
169 /// ```rust
170 /// use a2a_client::WebA2AClient;
171 ///
172 /// let client = WebA2AClient::builder()
173 /// .http_url("http://localhost:8080")
174 /// .build();
175 /// ```
176 pub fn builder() -> WebA2AClientBuilder {
177 WebA2AClientBuilder::default()
178 }
179
180 /// Create a new client with HTTP transport only.
181 ///
182 /// # Arguments
183 ///
184 /// * `base_url` - Base URL of the A2A agent (e.g., `http://localhost:8080`)
185 ///
186 /// # Examples
187 ///
188 /// ```rust
189 /// use a2a_client::WebA2AClient;
190 ///
191 /// let client = WebA2AClient::new_http("http://localhost:8080".to_string());
192 /// ```
193 pub fn new_http(base_url: String) -> Self {
194 Self {
195 transport: Arc::new(HttpClient::new(base_url)),
196 }
197 }
198
199 /// Auto-connect to an agent by fetching its card and negotiating a transport.
200 ///
201 /// Fetches the agent card from the well-known endpoint and selects a transport
202 /// from the card's `supported_interfaces` (ConnectRPC preferred, JSON-RPC 2.0
203 /// as interop fallback). If the card can't be fetched or none of its interfaces
204 /// match a compiled-in transport, falls back to a ConnectRPC client on
205 /// `base_url` so the call still works against a bare agent URL.
206 ///
207 /// # Arguments
208 ///
209 /// * `base_url` - Base URL of the A2A agent
210 ///
211 /// # Examples
212 ///
213 /// ```rust,no_run
214 /// use a2a_client::WebA2AClient;
215 ///
216 /// # #[tokio::main]
217 /// # async fn main() -> anyhow::Result<()> {
218 /// let client = WebA2AClient::auto_connect("http://localhost:8080").await?;
219 /// # Ok(())
220 /// # }
221 /// ```
222 pub async fn auto_connect(base_url: &str) -> Result<Self> {
223 // Validate URL format up front so a malformed URL is a hard error.
224 let _ = reqwest::Url::parse(base_url).map_err(|e| ClientError::InvalidUrl {
225 url: base_url.to_string(),
226 reason: e.to_string(),
227 })?;
228
229 match a2a_rs::connect(base_url, &a2a_rs::default_registry()).await {
230 Ok(transport) => Ok(Self {
231 transport: Arc::from(transport),
232 }),
233 // Card fetch / negotiation failed — fall back to a direct ConnectRPC client.
234 Err(_) => Ok(Self::new_http(base_url.to_string())),
235 }
236 }
237
238 /// Subscribe to a task's updates as a protocol-neutral stream of
239 /// [`StreamEvent`]s.
240 ///
241 /// This is the **spec-compliant** path: a single A2A `SubscribeToTask` round
242 /// trip with no reconnection and no `Last-Event-ID` — what any A2A agent
243 /// expects. For automatic reconnection (and gap-free resume against an
244 /// a2a-rs server) use
245 /// [`subscribe_resilient`](WebA2AClient::subscribe_resilient).
246 pub async fn subscribe(
247 &self,
248 task_id: &str,
249 ) -> Result<Pin<Box<dyn Stream<Item = std::result::Result<StreamEvent, A2AError>> + Send>>>
250 {
251 self.transport
252 .subscribe_to_task(task_id, None, None)
253 .await
254 .map_err(Into::into)
255 }
256
257 /// Subscribe to a task's updates with automatic reconnect + exponential
258 /// backoff. The stream ends when the task reaches a terminal state (or
259 /// retries are exhausted).
260 ///
261 /// Reconnection itself is spec-compliant (it re-issues `SubscribeToTask`).
262 /// Resuming *without gaps* via `Last-Event-ID` is an **a2a-rs enhancement**
263 /// beyond the A2A v1.0 spec: it works against an a2a-rs server and degrades
264 /// gracefully (reconnect-from-current-state) against any spec-compliant one.
265 ///
266 /// This is the reusable core that [`create_sse_stream`](components::create_sse_stream)
267 /// builds on; framework-agnostic, so non-Axum frontends can consume it
268 /// directly.
269 pub fn subscribe_resilient(
270 &self,
271 task_id: &str,
272 policy: RetryPolicy,
273 ) -> Pin<Box<dyn Stream<Item = std::result::Result<StreamEvent, A2AError>> + Send>> {
274 subscribe_resilient(
275 self.transport.clone(),
276 task_id.to_string(),
277 None,
278 None,
279 policy,
280 )
281 }
282}
283/// Application state for Axum web applications.
284///
285/// This struct provides a convenient way to share the A2A client and
286/// configuration across Axum route handlers.
287///
288/// # Examples
289///
290/// ```rust
291/// use a2a_client::{WebA2AClient, AppState};
292/// use std::sync::Arc;
293///
294/// let client = WebA2AClient::new_http("http://localhost:8080".to_string());
295/// let state = Arc::new(
296/// AppState::new(client)
297/// .with_webhook_token("secret-token".to_string())
298/// );
299/// ```
300pub struct AppState {
301 /// The A2A client for interacting with agents
302 pub client: WebA2AClient,
303 /// Optional webhook authentication token
304 pub webhook_token: Option<String>,
305}
306
307impl AppState {
308 /// Create new application state with the given client.
309 ///
310 /// # Examples
311 ///
312 /// ```rust
313 /// use a2a_client::{WebA2AClient, AppState};
314 ///
315 /// let client = WebA2AClient::new_http("http://localhost:8080".to_string());
316 /// let state = AppState::new(client);
317 /// ```
318 pub fn new(client: WebA2AClient) -> Self {
319 Self {
320 client,
321 webhook_token: None,
322 }
323 }
324
325 /// Set the webhook authentication token.
326 ///
327 /// # Examples
328 ///
329 /// ```rust
330 /// use a2a_client::{WebA2AClient, AppState};
331 ///
332 /// let client = WebA2AClient::new_http("http://localhost:8080".to_string());
333 /// let state = AppState::new(client)
334 /// .with_webhook_token("secret-token".to_string());
335 /// ```
336 pub fn with_webhook_token(mut self, token: String) -> Self {
337 self.webhook_token = Some(token);
338 self
339 }
340}
341
342/// Builder for [`WebA2AClient`].
343///
344/// Provides a fluent API for configuring the client with optional WebSocket support.
345///
346/// # Examples
347///
348/// ```rust
349/// use a2a_client::WebA2AClient;
350///
351/// // HTTP-only client
352/// let client = WebA2AClient::builder()
353/// .http_url("http://localhost:8080")
354/// .build();
355/// ```
356#[derive(Default)]
357pub struct WebA2AClientBuilder {
358 http_url: Option<String>,
359}
360
361impl WebA2AClientBuilder {
362 /// Set the HTTP base URL.
363 ///
364 /// # Examples
365 ///
366 /// ```rust
367 /// use a2a_client::WebA2AClient;
368 ///
369 /// let client = WebA2AClient::builder()
370 /// .http_url("http://localhost:8080")
371 /// .build();
372 /// ```
373 pub fn http_url(mut self, url: impl Into<String>) -> Self {
374 self.http_url = Some(url.into());
375 self
376 }
377
378 /// Build the [`WebA2AClient`].
379 ///
380 /// # Panics
381 ///
382 /// Panics if `http_url` was not set.
383 ///
384 /// # Examples
385 ///
386 /// ```rust
387 /// use a2a_client::WebA2AClient;
388 ///
389 /// let client = WebA2AClient::builder()
390 /// .http_url("http://localhost:8080")
391 /// .build();
392 /// ```
393 pub fn build(self) -> WebA2AClient {
394 let http_url = self
395 .http_url
396 .expect("http_url is required for WebA2AClient");
397
398 WebA2AClient::new_http(http_url)
399 }
400}
401
402#[cfg(test)]
403mod tests {
404 use super::*;
405
406 #[test]
407 fn test_client_builder_http_only() {
408 let _client = WebA2AClient::builder()
409 .http_url("http://test.local")
410 .build();
411 }
412
413 #[test]
414 #[should_panic(expected = "http_url is required for WebA2AClient")]
415 fn test_client_builder_panics_without_http() {
416 let _client = WebA2AClient::builder().build();
417 }
418
419 #[test]
420 fn test_app_state_creation() {
421 let client = WebA2AClient::new_http("http://test.local".to_string());
422 let state = AppState::new(client);
423 assert!(state.webhook_token.is_none());
424 }
425
426 #[test]
427 fn test_app_state_with_token() {
428 let client = WebA2AClient::new_http("http://test.local".to_string());
429 let state = AppState::new(client).with_webhook_token("secret".to_string());
430 assert_eq!(state.webhook_token.as_deref(), Some("secret"));
431 }
432
433 #[tokio::test]
434 async fn test_auto_connect_invalid_url() {
435 let result = WebA2AClient::auto_connect("invalid-url-no-scheme").await;
436 assert!(result.is_err());
437 match result {
438 Err(ClientError::InvalidUrl { url, reason }) => {
439 assert_eq!(url, "invalid-url-no-scheme");
440 assert!(!reason.is_empty());
441 }
442 _ => panic!("Expected ClientError::InvalidUrl"),
443 }
444 }
445}