a2a-rs 0.4.0

Rust implementation of the Agent-to-Agent (A2A) Protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
//! HTTP client adapter for the A2A protocol using ConnectRPC

use async_trait::async_trait;
use futures::stream::Stream;
use reqwest::{
    Client,
    header::{HeaderMap, HeaderValue},
};
use std::{pin::Pin, sync::Arc, time::Duration};

#[cfg(feature = "tracing")]
use tracing::{debug, instrument};

use crate::{
    adapter::error::HttpClientError,
    adapter::transport::codec::stream_response_to_item,
    domain::{
        A2AError, AgentCard, ListTasksParams, ListTasksResult, Message, Task,
        TaskPushNotificationConfig,
        generated::{
            A2aServiceClient, CancelTaskRequest, DeleteTaskPushNotificationConfigRequest,
            GetExtendedAgentCardRequest, GetTaskPushNotificationConfigRequest, GetTaskRequest,
            ListTaskPushNotificationConfigsRequest, ListTasksRequest, SendMessageConfiguration,
            SendMessageRequest, SubscribeToTaskRequest, TaskState, send_message_response,
        },
    },
    port::{StreamEvent, Transport},
};

fn map_connect_err(err: connectrpc::ConnectError) -> A2AError {
    let code = match err.code {
        connectrpc::ErrorCode::NotFound => crate::domain::error::TASK_NOT_FOUND,
        connectrpc::ErrorCode::Unimplemented => crate::domain::error::METHOD_NOT_FOUND,
        connectrpc::ErrorCode::InvalidArgument => crate::domain::error::INVALID_PARAMS,
        connectrpc::ErrorCode::Internal => crate::domain::error::INTERNAL_ERROR,
        connectrpc::ErrorCode::FailedPrecondition => {
            crate::domain::error::AUTHENTICATED_EXTENDED_CARD_NOT_CONFIGURED
        }
        _ => {
            let code_val = err.code as i32;
            if code_val != 0 {
                code_val
            } else {
                crate::domain::error::INTERNAL_ERROR
            }
        }
    };
    A2AError::JsonRpc {
        code,
        message: err.message.clone().unwrap_or_default(),
        data: None,
    }
}

/// HTTP client for interacting with the A2A protocol via ConnectRPC
pub struct HttpClient {
    /// Base URL of the A2A API
    base_url: String,
    /// reqwest Client for standard GET operations like agent card
    client: Client,
    /// ConnectRPC Client
    connect_client: A2aServiceClient<connectrpc::client::HttpClient>,
    /// Authorization token, if any
    auth_token: Option<String>,
    /// Timeout in seconds
    timeout: u64,
}

impl HttpClient {
    /// Create a new HTTP client with the given base URL
    pub fn new(base_url: String) -> Self {
        let uri = base_url.parse::<http::Uri>().expect("Invalid base URL");
        let is_https = uri.scheme_str() == Some("https");

        let transport = if is_https {
            let _ = rustls::crypto::ring::default_provider().install_default();
            let mut root_store = rustls::RootCertStore::empty();
            root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
            let tls_config = rustls::ClientConfig::builder()
                .with_root_certificates(root_store)
                .with_no_client_auth();
            connectrpc::client::HttpClient::with_tls(Arc::new(tls_config))
        } else {
            connectrpc::client::HttpClient::plaintext()
        };

        let mut config = connectrpc::client::ClientConfig::new(uri);
        config = config.default_timeout(Duration::from_secs(30));

        let connect_client = A2aServiceClient::new(transport, config);

        Self {
            base_url,
            client: Client::new(),
            connect_client,
            auth_token: None,
            timeout: 30,
        }
    }

    /// Create a new HTTP client with authentication
    pub fn with_auth(base_url: String, auth_token: String) -> Self {
        let uri = base_url.parse::<http::Uri>().expect("Invalid base URL");
        let is_https = uri.scheme_str() == Some("https");

        let transport = if is_https {
            let _ = rustls::crypto::ring::default_provider().install_default();
            let mut root_store = rustls::RootCertStore::empty();
            root_store.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
            let tls_config = rustls::ClientConfig::builder()
                .with_root_certificates(root_store)
                .with_no_client_auth();
            connectrpc::client::HttpClient::with_tls(Arc::new(tls_config))
        } else {
            connectrpc::client::HttpClient::plaintext()
        };

        let mut config = connectrpc::client::ClientConfig::new(uri);
        config = config
            .default_timeout(Duration::from_secs(30))
            .default_header("authorization", format!("Bearer {}", auth_token));

        let connect_client = A2aServiceClient::new(transport, config);

        Self {
            base_url,
            client: Client::new(),
            connect_client,
            auth_token: Some(auth_token),
            timeout: 30,
        }
    }

    /// Set the timeout for requests
    pub fn with_timeout(mut self, timeout: u64) -> Self {
        self.timeout = timeout;
        *self.connect_client.config_mut() = self
            .connect_client
            .config()
            .clone()
            .default_timeout(Duration::from_secs(timeout));
        self
    }

    /// Get the headers for a request (used for reqwest)
    fn get_headers(&self) -> Result<HeaderMap, A2AError> {
        let mut headers = HeaderMap::new();
        headers.insert(
            reqwest::header::CONTENT_TYPE,
            HeaderValue::from_static("application/json"),
        );

        if let Some(token) = &self.auth_token {
            let auth_value = HeaderValue::from_str(&format!("Bearer {}", token)).map_err(|e| {
                A2AError::Internal(format!("Invalid auth token for HTTP header: {}", e))
            })?;
            headers.insert(reqwest::header::AUTHORIZATION, auth_value);
        }

        Ok(headers)
    }

    /// Get the base URL of the client
    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    /// Fetch the agent card from the agent's `/agent-card` endpoint (plain HTTP GET)
    pub async fn get_agent_card(&self) -> Result<AgentCard, A2AError> {
        let url = if self.base_url.ends_with('/') {
            format!("{}agent-card", self.base_url)
        } else {
            match reqwest::Url::parse(&self.base_url) {
                Ok(parsed) => {
                    if !parsed.path().ends_with('/') {
                        match parsed.join("/agent-card") {
                            Ok(resolved) => resolved.to_string(),
                            Err(_) => format!("{}/agent-card", self.base_url),
                        }
                    } else {
                        match parsed.join("agent-card") {
                            Ok(resolved) => resolved.to_string(),
                            Err(_) => format!("{}/agent-card", self.base_url),
                        }
                    }
                }
                Err(_) => format!("{}/agent-card", self.base_url),
            }
        };

        #[cfg(feature = "tracing")]
        debug!("Fetching agent card from URL: {}", url);

        let response = self
            .client
            .get(&url)
            .headers(self.get_headers()?)
            .timeout(Duration::from_secs(self.timeout))
            .send()
            .await
            .map_err(HttpClientError::Reqwest)?;

        if response.status().is_success() {
            let card: AgentCard = response.json().await.map_err(|e| {
                A2AError::Internal(format!("Failed to parse agent card JSON: {}", e))
            })?;
            Ok(card)
        } else {
            let status = response.status();
            let body = response.text().await.unwrap_or_default();
            Err(HttpClientError::Response {
                status: status.as_u16(),
                message: body,
            }
            .into())
        }
    }

    /// Fetch the extended agent card using ConnectRPC
    pub async fn get_extended_agent_card(
        &self,
        tenant: Option<String>,
    ) -> Result<AgentCard, A2AError> {
        let request = GetExtendedAgentCardRequest {
            tenant: tenant.unwrap_or_default(),
            ..Default::default()
        };
        let response = self
            .connect_client
            .get_extended_agent_card(request)
            .await
            .map_err(map_connect_err)?;
        Ok(response.into_owned())
    }
}

#[async_trait]
impl Transport for HttpClient {
    fn protocol(&self) -> &str {
        "CONNECTRPC"
    }

    #[cfg_attr(
        feature = "tracing",
        instrument(skip(self, message), fields(task_id, session_id, history_length))
    )]
    async fn send_task_message(
        &self,
        task_id: &str,
        message: &Message,
        session_id: Option<&str>,
        history_length: Option<u32>,
    ) -> Result<Task, A2AError> {
        let mut msg = message.clone();
        msg.task_id = task_id.to_string();
        if let Some(sid) = session_id {
            msg.context_id = sid.to_string();
        }

        let config = SendMessageConfiguration {
            history_length: history_length.map(|l| l as i32),
            ..Default::default()
        };

        let request = SendMessageRequest {
            message: ::buffa::MessageField::some(msg),
            configuration: ::buffa::MessageField::some(config),
            ..Default::default()
        };

        let response = self
            .connect_client
            .send_message(request)
            .await
            .map_err(map_connect_err)?;
        let owned_response = response.into_owned();

        match owned_response.payload {
            Some(send_message_response::Payload::Task(task)) => Ok(*task),
            _ => Err(A2AError::Internal(
                "Expected task in SendMessageResponse payload".to_string(),
            )),
        }
    }

    #[cfg_attr(
        feature = "tracing",
        instrument(skip(self), fields(task_id, history_length))
    )]
    async fn get_task(&self, task_id: &str, history_length: Option<u32>) -> Result<Task, A2AError> {
        let request = GetTaskRequest {
            id: task_id.to_string(),
            history_length: history_length.map(|l| l as i32),
            ..Default::default()
        };
        let response = self
            .connect_client
            .get_task(request)
            .await
            .map_err(map_connect_err)?;
        Ok(response.into_owned())
    }

    #[cfg_attr(feature = "tracing", instrument(skip(self), fields(task_id)))]
    async fn cancel_task(&self, task_id: &str) -> Result<Task, A2AError> {
        let request = CancelTaskRequest {
            id: task_id.to_string(),
            ..Default::default()
        };
        let response = self
            .connect_client
            .cancel_task(request)
            .await
            .map_err(map_connect_err)?;
        Ok(response.into_owned())
    }

    async fn set_task_push_notification(
        &self,
        config: &TaskPushNotificationConfig,
    ) -> Result<TaskPushNotificationConfig, A2AError> {
        let request = config.clone();
        let response = self
            .connect_client
            .create_task_push_notification_config(request)
            .await
            .map_err(map_connect_err)?;
        Ok(response.into_owned())
    }

    async fn get_task_push_notification(
        &self,
        task_id: &str,
    ) -> Result<TaskPushNotificationConfig, A2AError> {
        let request = ListTaskPushNotificationConfigsRequest {
            task_id: task_id.to_string(),
            ..Default::default()
        };
        let response = self
            .connect_client
            .list_task_push_notification_configs(request)
            .await
            .map_err(map_connect_err)?;
        let configs = response.into_owned().configs;
        if let Some(config) = configs.into_iter().next() {
            Ok(config)
        } else {
            Err(A2AError::TaskNotFound(format!(
                "No push notification config found for task {}",
                task_id
            )))
        }
    }

    #[cfg_attr(feature = "tracing", instrument(skip(self, params)))]
    async fn list_tasks(&self, params: &ListTasksParams) -> Result<ListTasksResult, A2AError> {
        let mut request = ListTasksRequest {
            context_id: params.context_id.clone().unwrap_or_default(),
            status: ::buffa::EnumValue::from(
                params.status.unwrap_or(TaskState::TASK_STATE_UNSPECIFIED),
            ),
            page_size: params.page_size,
            page_token: params.page_token.clone().unwrap_or_default(),
            history_length: params.history_length,
            include_artifacts: params.include_artifacts,
            ..Default::default()
        };
        if let Some(ref t_str) = params.status_timestamp_after {
            if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(t_str) {
                let utc_dt = dt.with_timezone(&chrono::Utc);
                request.status_timestamp_after =
                    ::buffa::MessageField::some(::buffa_types::google::protobuf::Timestamp {
                        seconds: utc_dt.timestamp(),
                        nanos: utc_dt.timestamp_subsec_nanos() as i32,
                        ..Default::default()
                    });
            }
        }

        let response = self
            .connect_client
            .list_tasks(request)
            .await
            .map_err(map_connect_err)?;
        let owned = response.into_owned();
        Ok(ListTasksResult {
            tasks: owned.tasks,
            total_size: owned.total_size,
            page_size: owned.page_size,
            next_page_token: owned.next_page_token,
        })
    }

    async fn list_push_notification_configs(
        &self,
        task_id: &str,
    ) -> Result<Vec<TaskPushNotificationConfig>, A2AError> {
        let request = ListTaskPushNotificationConfigsRequest {
            task_id: task_id.to_string(),
            ..Default::default()
        };
        let response = self
            .connect_client
            .list_task_push_notification_configs(request)
            .await
            .map_err(map_connect_err)?;
        Ok(response.into_owned().configs)
    }

    async fn get_push_notification_config(
        &self,
        task_id: &str,
        config_id: &str,
    ) -> Result<TaskPushNotificationConfig, A2AError> {
        let request = GetTaskPushNotificationConfigRequest {
            task_id: task_id.to_string(),
            id: config_id.to_string(),
            ..Default::default()
        };
        let response = self
            .connect_client
            .get_task_push_notification_config(request)
            .await
            .map_err(map_connect_err)?;
        Ok(response.into_owned())
    }

    async fn delete_push_notification_config(
        &self,
        task_id: &str,
        config_id: &str,
    ) -> Result<(), A2AError> {
        let request = DeleteTaskPushNotificationConfigRequest {
            task_id: task_id.to_string(),
            id: config_id.to_string(),
            ..Default::default()
        };
        self.connect_client
            .delete_task_push_notification_config(request)
            .await
            .map_err(map_connect_err)?;
        Ok(())
    }

    async fn subscribe_to_task(
        &self,
        task_id: &str,
        _history_length: Option<u32>,
        // ConnectRPC streaming has no SSE `Last-Event-ID`; resumption is not
        // supported on this transport, so the hint is ignored.
        _last_event_id: Option<&str>,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<StreamEvent, A2AError>> + Send>>, A2AError> {
        let request = SubscribeToTaskRequest {
            id: task_id.to_string(),
            ..Default::default()
        };
        let stream = self
            .connect_client
            .subscribe_to_task(request)
            .await
            .map_err(map_connect_err)?;

        let mapped = futures::stream::unfold(stream, |mut s| async move {
            match s.message().await {
                Ok(Some(view)) => {
                    let resp = view.to_owned_message();
                    if let Some(item) = stream_response_to_item(resp) {
                        Some((Ok(StreamEvent::untagged(item)), s))
                    } else {
                        Some((
                            Err(A2AError::Internal(
                                "Empty or unhandled stream response payload".to_string(),
                            )),
                            s,
                        ))
                    }
                }
                Ok(None) => None,
                Err(e) => Some((Err(map_connect_err(e)), s)),
            }
        });

        Ok(Box::pin(mapped))
    }
}