Skip to main content

vtcode_a2a/
client.rs

1//! A2A client for interacting with remote A2A agents.
2//! Provides helper methods for discovery, task operations, and streaming.
3
4use std::sync::{
5    Arc,
6    atomic::{AtomicU64, Ordering},
7};
8
9use anyhow::Context;
10use futures::{Stream, StreamExt};
11use reqwest::{Client, RequestBuilder};
12use serde_json::Value;
13use std::fmt;
14use std::time::Duration;
15
16use crate::agent_card::AgentCard;
17use crate::errors::{A2aError, A2aErrorCode, A2aResult};
18use crate::rpc::{
19    JsonRpcRequest, ListTasksParams, METHOD_MESSAGE_SEND, METHOD_MESSAGE_STREAM, METHOD_TASKS_CANCEL, METHOD_TASKS_GET,
20    METHOD_TASKS_LIST, METHOD_TASKS_PUSH_CONFIG_GET, METHOD_TASKS_PUSH_CONFIG_SET, MessageSendParams,
21    SendStreamingMessageResponse, StreamingEvent, TaskIdParams, TaskPushNotificationConfig, TaskQueryParams,
22};
23use crate::types::Task;
24
25/// HTTP client for interacting with A2A agents
26#[derive(Clone)]
27pub struct A2aClient {
28    base_url: String,
29    http: Client,
30    request_id: Arc<AtomicU64>,
31    auth_token: Option<String>,
32}
33
34impl fmt::Debug for A2aClient {
35    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
36        formatter
37            .debug_struct("A2aClient")
38            .field("base_url", &self.base_url)
39            .field("http", &self.http)
40            .field("request_id", &self.request_id)
41            .field("auth_token", &self.auth_token.as_ref().map(|_| "REDACTED"))
42            .finish()
43    }
44}
45
46/// Connect and request budgets used by [`A2aClient::new`].
47///
48/// `vtcode-a2a` is a Layer 0 crate with no internal VT Code dependencies, so it
49/// cannot read `[timeouts]` itself. Callers that own configuration resolve these
50/// and pass them in through [`A2aClient::with_timeouts`]; the constants below are
51/// the safe defaults for callers that do not.
52const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
53const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
54
55impl A2aClient {
56    /// Create a new client with default HTTP timeouts.
57    ///
58    /// Redirects stay disabled: the bearer token must never be replayed to an
59    /// origin the remote agent redirects to.
60    pub fn new(base_url: impl Into<String>) -> A2aResult<Self> {
61        Self::with_timeouts(base_url, DEFAULT_CONNECT_TIMEOUT, DEFAULT_REQUEST_TIMEOUT)
62    }
63
64    /// Create a client with explicit connect and request timeouts.
65    ///
66    /// A client built with no timeout at all can block forever on a remote agent
67    /// that accepts the connection and then stalls, so both budgets are required
68    /// rather than optional.
69    pub fn with_timeouts(
70        base_url: impl Into<String>,
71        connect_timeout: Duration,
72        request_timeout: Duration,
73    ) -> A2aResult<Self> {
74        use reqwest::redirect::Policy;
75
76        let http = Client::builder()
77            .timeout(request_timeout)
78            .connect_timeout(connect_timeout)
79            .redirect(Policy::none())
80            .build()
81            .context("Failed to build HTTP client")
82            .map_err(|e| A2aError::Internal(e.to_string()))?;
83
84        Ok(Self {
85            base_url: base_url.into().trim_end_matches('/').to_string(),
86            http,
87            request_id: Arc::new(AtomicU64::new(1)),
88            auth_token: None,
89        })
90    }
91
92    /// Attach a bearer token to RPC and streaming requests.
93    pub fn with_bearer_token(mut self, token: impl Into<String>) -> Self {
94        self.auth_token = Some(token.into());
95        self
96    }
97
98    fn next_id(&self) -> String {
99        let id = self.request_id.fetch_add(1, Ordering::Relaxed);
100        format!("a2a-{id}")
101    }
102
103    fn rpc_url(&self) -> String {
104        format!("{}/a2a", self.base_url)
105    }
106
107    fn stream_url(&self) -> String {
108        format!("{}/a2a/stream", self.base_url)
109    }
110
111    fn agent_card_url(&self) -> String {
112        format!("{}/.well-known/agent-card.json", self.base_url)
113    }
114
115    fn with_authentication(&self, request: RequestBuilder) -> RequestBuilder {
116        match self.auth_token.as_deref() {
117            Some(token) => request.bearer_auth(token),
118            None => request,
119        }
120    }
121
122    /// Fetch the remote agent card
123    pub async fn agent_card(&self) -> A2aResult<AgentCard> {
124        let resp = self
125            .http
126            .get(self.agent_card_url())
127            .send()
128            .await
129            .context("Failed to fetch agent card")
130            .map_err(|e| A2aError::Internal(e.to_string()))?;
131
132        let status = resp.status();
133        if !status.is_success() {
134            return Err(A2aError::rpc(
135                A2aErrorCode::InvalidAgentResponse,
136                format!("Agent card request failed with status {status}"),
137            ));
138        }
139
140        let card = resp
141            .json::<AgentCard>()
142            .await
143            .context("Invalid agent card response")
144            .map_err(|e| A2aError::Internal(e.to_string()))?;
145        Ok(card)
146    }
147
148    /// Send a message/send RPC
149    pub async fn send_message(&self, params: MessageSendParams) -> A2aResult<Task> {
150        let result_value = self.call_rpc(METHOD_MESSAGE_SEND, Some(serde_json::to_value(&params)?)).await?;
151        let task: Task = serde_json::from_value(result_value)
152            .context("Failed to deserialize task")
153            .map_err(|e| A2aError::Internal(e.to_string()))?;
154        Ok(task)
155    }
156
157    /// Send a message/stream RPC and consume streaming events
158    pub async fn stream_message(
159        &self,
160        params: MessageSendParams,
161    ) -> A2aResult<impl Stream<Item = A2aResult<StreamingEvent>>> {
162        let req =
163            JsonRpcRequest::with_string_id(METHOD_MESSAGE_STREAM, Some(serde_json::to_value(&params)?), self.next_id());
164
165        let request = self
166            .http
167            .post(self.stream_url())
168            .header("accept", "text/event-stream")
169            .json(&req);
170        let response = self
171            .with_authentication(request)
172            .send()
173            .await
174            .context("Failed to open streaming request")
175            .map_err(|e| A2aError::Internal(e.to_string()))?;
176
177        let status = response.status();
178        if !status.is_success() {
179            return Err(A2aError::rpc(
180                A2aErrorCode::InvalidAgentResponse,
181                format!("Streaming request failed with status {status}"),
182            ));
183        }
184
185        let byte_stream = response.bytes_stream();
186
187        let stream = async_stream::try_stream! {
188            let mut buffer = Vec::new();
189            futures::pin_mut!(byte_stream);
190
191            while let Some(chunk) = byte_stream.next().await {
192                let chunk = chunk.context("Failed to read streaming chunk")
193                    .map_err(|e| A2aError::Internal(e.to_string()))?;
194                buffer.extend_from_slice(&chunk);
195
196                while let Some(pos) = find_double_newline(&buffer) {
197                    let event_bytes = buffer.drain(..pos + 2).collect::<Vec<u8>>();
198                    if let Some(event) = parse_sse_event(&event_bytes)? {
199                        yield event;
200                    }
201                }
202            }
203
204            if !buffer.is_empty() {
205                #[allow(clippy::collapsible_if, reason = "Intentional compatibility, platform, or test-only suppression.")]
206                if let Some(event) = parse_sse_event(&buffer)? {
207                    yield event;
208                }
209            }
210        };
211
212        Ok(stream)
213    }
214
215    /// Get a task by ID
216    pub async fn get_task(&self, task_id: String) -> A2aResult<Task> {
217        let params = serde_json::to_value(TaskQueryParams { id: task_id, history_length: None })?;
218        let result_value = self.call_rpc(METHOD_TASKS_GET, Some(params)).await?;
219        let task: Task = serde_json::from_value(result_value)
220            .context("Failed to deserialize task")
221            .map_err(|e| A2aError::Internal(e.to_string()))?;
222        Ok(task)
223    }
224
225    /// List tasks with filters
226    pub async fn list_tasks(&self, params: Option<ListTasksParams>) -> A2aResult<Value> {
227        let result_value = self
228            .call_rpc(METHOD_TASKS_LIST, params.map(serde_json::to_value).transpose()?)
229            .await?;
230        Ok(result_value)
231    }
232
233    /// Cancel a task
234    pub async fn cancel_task(&self, task_id: String) -> A2aResult<Task> {
235        let params = serde_json::to_value(TaskIdParams { id: task_id })?;
236        let result_value = self.call_rpc(METHOD_TASKS_CANCEL, Some(params)).await?;
237        let task: Task = serde_json::from_value(result_value)
238            .context("Failed to deserialize task")
239            .map_err(|e| A2aError::Internal(e.to_string()))?;
240        Ok(task)
241    }
242
243    /// Set push notification config
244    pub async fn set_push_config(&self, config: TaskPushNotificationConfig) -> A2aResult<bool> {
245        let value = self
246            .call_rpc(METHOD_TASKS_PUSH_CONFIG_SET, Some(serde_json::to_value(config)?))
247            .await?;
248        // Server returns {"success": true}
249        let success = value.get("success").and_then(|v| v.as_bool()).unwrap_or(false);
250        Ok(success)
251    }
252
253    /// Get push notification config
254    pub async fn get_push_config(&self, task_id: String) -> A2aResult<Option<TaskPushNotificationConfig>> {
255        let params = serde_json::to_value(TaskIdParams { id: task_id })?;
256        let value = self.call_rpc(METHOD_TASKS_PUSH_CONFIG_GET, Some(params)).await?;
257        if value.is_null() {
258            return Ok(None);
259        }
260        let cfg: TaskPushNotificationConfig = serde_json::from_value(value)
261            .context("Failed to deserialize push notification config")
262            .map_err(|e| A2aError::Internal(e.to_string()))?;
263        Ok(Some(cfg))
264    }
265
266    async fn call_rpc(&self, method: &str, params: Option<Value>) -> A2aResult<Value> {
267        let request = JsonRpcRequest::with_string_id(method, params, self.next_id());
268
269        let request = self.http.post(self.rpc_url()).json(&request);
270        let resp = self
271            .with_authentication(request)
272            .send()
273            .await
274            .context("RPC request failed")
275            .map_err(|e| A2aError::Internal(e.to_string()))?;
276
277        let status = resp.status();
278        let json: Value = resp
279            .json()
280            .await
281            .context("Failed to parse RPC response")
282            .map_err(|e| A2aError::Internal(e.to_string()))?;
283
284        if !status.is_success() {
285            return Err(A2aError::rpc(
286                A2aErrorCode::InvalidAgentResponse,
287                format!("RPC failed with status {status}: {json:?}"),
288            ));
289        }
290
291        // Deserialize JSON-RPC envelope
292        let rpc_response: crate::rpc::JsonRpcResponse = serde_json::from_value(json.clone())
293            .context("Invalid JSON-RPC response")
294            .map_err(|e| A2aError::Internal(e.to_string()))?;
295
296        if let Some(result) = rpc_response.result {
297            Ok(result)
298        } else if let Some(err) = rpc_response.error {
299            Err(A2aError::rpc(err.code.into(), err.message))
300        } else {
301            Err(A2aError::rpc(A2aErrorCode::InvalidAgentResponse, "Empty RPC response"))
302        }
303    }
304}
305
306/// Find the position of the first double newline delimiter ("\n\n")
307fn find_double_newline(buf: &[u8]) -> Option<usize> {
308    buf.windows(2).position(|w| w == b"\n\n")
309}
310
311/// Parse a single SSE event from raw bytes
312fn parse_sse_event(bytes: &[u8]) -> A2aResult<Option<StreamingEvent>> {
313    // SSE events are lines starting with "data: " and separated by blank line
314    let text = std::str::from_utf8(bytes)
315        .context("Invalid UTF-8 in SSE event")
316        .map_err(|e| A2aError::Internal(e.to_string()))?;
317
318    for line in text.lines() {
319        if let Some(payload) = line.strip_prefix("data: ") {
320            // Parse the streaming response wrapper
321            let wrapper: SendStreamingMessageResponse = serde_json::from_str(payload)
322                .context("Failed to deserialize streaming event")
323                .map_err(|e| A2aError::Internal(e.to_string()))?;
324            return Ok(Some(wrapper.event));
325        }
326    }
327
328    Ok(None)
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334
335    #[test]
336    fn test_find_double_newline() {
337        let data = b"data: x\n\nrest";
338        assert_eq!(find_double_newline(data), Some(7));
339    }
340
341    #[test]
342    fn test_parse_sse_event_empty() {
343        let res = parse_sse_event(b"event: ping\n\n").unwrap();
344        assert!(res.is_none());
345    }
346
347    #[tokio::test]
348    async fn request_budget_bounds_a_stalled_endpoint() {
349        // Regression: the client used a bare `Client::builder()` with no timeout,
350        // so a remote agent that accepted the connection and then stalled would
351        // hang the caller forever. A short request budget must surface an error
352        // instead of hanging. `198.51.100.0/24` (TEST-NET-2) is reserved and
353        // unroutable, so this exercises the timeout path without a live server.
354        let client =
355            A2aClient::with_timeouts("http://198.51.100.1:9", Duration::from_millis(50), Duration::from_millis(100))
356                .expect("client builds");
357
358        let outcome = tokio::time::timeout(Duration::from_secs(10), client.agent_card()).await;
359        let error = outcome
360            .expect("the request budget must fire well before the outer guard")
361            .expect_err("an unroutable endpoint must not succeed");
362        assert!(!error.to_string().is_empty(), "failure must carry a diagnostic");
363    }
364
365    #[test]
366    fn default_constructor_uses_bounded_budgets() {
367        assert_eq!(DEFAULT_CONNECT_TIMEOUT, Duration::from_secs(5));
368        assert_eq!(DEFAULT_REQUEST_TIMEOUT, Duration::from_secs(30));
369        A2aClient::new("https://example.invalid").expect("client builds");
370    }
371}