1use crate::a2a::{
2 AgentCard, JsonRpcRequest, JsonRpcResponse, Message, MessageSendParams,
3 TaskArtifactUpdateEvent, TaskStatusUpdateEvent, UpdateEvent,
4};
5use adk_core::Result;
6use futures::stream::Stream;
7use serde_json::Value;
8use std::pin::Pin;
9
10pub struct A2aClient {
12 http_client: reqwest::Client,
13 agent_card: AgentCard,
14 credential: Option<adk_core::ScopedToken>,
15}
16
17fn bearer(
20 request: reqwest::RequestBuilder,
21 token: Option<&adk_core::ScopedToken>,
22 url: &str,
23) -> Result<reqwest::RequestBuilder> {
24 let Some(token) = token else {
25 return Ok(request);
26 };
27 let target = adk_core::Url::parse(url)
28 .map_err(|error| adk_core::AdkError::agent(format!("invalid A2A endpoint URL: {error}")))?;
29 Ok(request.bearer_auth(token.authorize_for(&target)?.expose()))
30}
31
32fn is_loopback(url: &adk_core::Url) -> bool {
34 matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"))
36}
37
38fn comparable_origin(url: &adk_core::Url) -> String {
40 let host = if is_loopback(url) {
41 "localhost".to_string()
42 } else {
43 url.host_str().unwrap_or_default().to_string()
44 };
45 format!("{}://{host}:{}", url.scheme(), url.port_or_known_default().unwrap_or_default())
46}
47
48pub fn check_card_endpoint(
75 card_url: &str,
76 endpoint: &str,
77 allowed_origins: &[String],
78) -> Result<()> {
79 let parse = |url: &str, what: &str| {
80 adk_core::Url::parse(url).map_err(|error| {
81 adk_core::AdkError::new(
82 adk_core::ErrorComponent::Server,
83 adk_core::ErrorCategory::InvalidInput,
84 "a2a.card_endpoint_invalid",
85 format!("invalid A2A {what} URL: {error}"),
86 )
87 })
88 };
89 let card = parse(card_url, "agent card")?;
90 let target = parse(endpoint, "endpoint")?;
91 let target_origin = comparable_origin(&target);
92 if target_origin == comparable_origin(&card) {
93 return Ok(());
94 }
95 let refused = |reason: String| {
96 Err(adk_core::AdkError::new(
97 adk_core::ErrorComponent::Server,
98 adk_core::ErrorCategory::Forbidden,
99 "a2a.card_endpoint_refused",
100 reason,
101 ))
102 };
103 let listed = allowed_origins.iter().any(|origin| {
104 adk_core::Url::parse(origin).is_ok_and(|origin| comparable_origin(&origin) == target_origin)
105 });
106 if !listed {
107 return refused(format!(
108 "the agent card from {} names an endpoint on {}; messages are sent only to the \
109 card's origin unless the endpoint's origin is allowed explicitly",
110 card.origin().ascii_serialization(),
111 target.origin().ascii_serialization(),
112 ));
113 }
114 if target.scheme() != "https" && !is_loopback(&target) {
115 return refused(format!(
116 "the agent card endpoint on {} must use https",
117 target.origin().ascii_serialization()
118 ));
119 }
120 Ok(())
121}
122
123impl A2aClient {
124 pub fn new(agent_card: AgentCard) -> Self {
130 Self { http_client: reqwest::Client::new(), agent_card, credential: None }
131 }
132
133 pub fn with_credential(mut self, token: adk_core::ScopedToken) -> Self {
140 self.credential = Some(token);
141 self
142 }
143
144 pub async fn resolve_agent_card(base_url: &str) -> Result<AgentCard> {
162 Self::resolve_agent_card_allowing(base_url, &[]).await
163 }
164
165 pub async fn resolve_agent_card_allowing(
182 base_url: &str,
183 allowed_origins: &[String],
184 ) -> Result<AgentCard> {
185 let base_url = base_url.trim_end_matches('/');
186 let client = reqwest::Client::new();
187 let fetch = |path: &'static str| client.get(format!("{base_url}{path}")).send();
188 let fetch_error = |e: reqwest::Error| {
189 adk_core::AdkError::agent(format!("Failed to fetch agent card: {e}"))
190 };
191
192 let read = |response: reqwest::Response| async move {
194 if response.status() == reqwest::StatusCode::NOT_FOUND {
195 return Ok(None);
196 }
197 if !response.status().is_success() {
198 return Err(adk_core::AdkError::agent(format!(
199 "Failed to fetch agent card: HTTP {}",
200 response.status()
201 )));
202 }
203 let body = response.bytes().await.map_err(fetch_error)?;
204 Ok(Some(serde_json::from_slice::<AgentCard>(&body)))
205 };
206
207 let current =
208 read(fetch("/.well-known/agent-card.json").await.map_err(fetch_error)?).await?;
209 let card = match current {
210 Some(Ok(card)) => card,
211 not_a_0_3_card => {
212 match read(fetch("/.well-known/agent.json").await.map_err(fetch_error)?).await? {
213 Some(Ok(card)) => card,
214 Some(Err(e)) => {
215 return Err(adk_core::AdkError::agent(format!(
216 "Failed to parse agent card: {e}"
217 )));
218 }
219 None => {
220 return Err(adk_core::AdkError::agent(match not_a_0_3_card {
221 Some(Err(e)) => format!("Failed to parse agent card: {e}"),
222 _ => "Failed to fetch agent card: HTTP 404 Not Found".to_string(),
223 }));
224 }
225 }
226 }
227 };
228
229 check_card_endpoint(base_url, &card.url, allowed_origins)?;
230 Ok(card)
231 }
232
233 pub async fn from_url(base_url: &str) -> Result<Self> {
236 let card = Self::resolve_agent_card(base_url).await?;
237 Ok(Self::new(card))
238 }
239
240 pub fn agent_card(&self) -> &AgentCard {
242 &self.agent_card
243 }
244
245 pub async fn send_message(&self, message: Message) -> Result<JsonRpcResponse> {
247 let request = JsonRpcRequest {
248 jsonrpc: "2.0".to_string(),
249 method: "message/send".to_string(),
250 params: Some(
251 serde_json::to_value(MessageSendParams { message, config: None })
252 .map_err(|e| adk_core::AdkError::agent(e.to_string()))?,
253 ),
254 id: Some(Value::String(uuid::Uuid::new_v4().to_string())),
255 };
256
257 let post = self.http_client.post(&self.agent_card.url);
258 let response = bearer(post, self.credential.as_ref(), &self.agent_card.url)?
259 .json(&request)
260 .send()
261 .await
262 .map_err(|e| adk_core::AdkError::agent(format!("Request failed: {e}")))?;
263
264 if !response.status().is_success() {
265 return Err(adk_core::AdkError::agent(format!(
266 "Request failed: HTTP {}",
267 response.status()
268 )));
269 }
270
271 let rpc_response: JsonRpcResponse = response
272 .json()
273 .await
274 .map_err(|e| adk_core::AdkError::agent(format!("Failed to parse response: {e}")))?;
275
276 Ok(rpc_response)
277 }
278
279 pub async fn send_streaming_message(
281 &self,
282 message: Message,
283 ) -> Result<Pin<Box<dyn Stream<Item = Result<UpdateEvent>> + Send>>> {
284 let stream_url = format!("{}/stream", self.agent_card.url.trim_end_matches('/'));
285
286 let request = JsonRpcRequest {
287 jsonrpc: "2.0".to_string(),
288 method: "message/stream".to_string(),
289 params: Some(
290 serde_json::to_value(MessageSendParams { message, config: None })
291 .map_err(|e| adk_core::AdkError::agent(e.to_string()))?,
292 ),
293 id: Some(Value::String(uuid::Uuid::new_v4().to_string())),
294 };
295
296 let post = self.http_client.post(&stream_url);
297 let response = bearer(post, self.credential.as_ref(), &stream_url)?
298 .json(&request)
299 .send()
300 .await
301 .map_err(|e| adk_core::AdkError::agent(format!("Request failed: {e}")))?;
302
303 if !response.status().is_success() {
304 return Err(adk_core::AdkError::agent(format!(
305 "Request failed: HTTP {}",
306 response.status()
307 )));
308 }
309
310 let stream = async_stream::stream! {
313 use futures::StreamExt;
314 let mut bytes_stream = response.bytes_stream();
315 let mut decoder = SseDecoder::default();
316 let mut finished = false;
317
318 while let Some(chunk_result) = bytes_stream.next().await {
319 let chunk = match chunk_result {
320 Ok(c) => c,
321 Err(e) => {
322 yield Err(adk_core::AdkError::agent(format!("Stream error: {e}")));
323 return;
324 }
325 };
326 let payloads = match decoder.push(&chunk) {
327 Ok(payloads) => payloads,
328 Err(e) => {
329 yield Err(e);
330 return;
331 }
332 };
333
334 for data in payloads {
335 if data.trim().is_empty() {
337 continue;
338 }
339 match serde_json::from_str::<JsonRpcResponse>(&data) {
340 Ok(rpc_response) => {
341 if let Some(result) = rpc_response.result {
342 if let Ok(status_event) = serde_json::from_value::<TaskStatusUpdateEvent>(result.clone()) {
343 finished |= ends_task(&status_event);
344 yield Ok(UpdateEvent::TaskStatusUpdate(status_event));
345 } else if let Ok(artifact_event) = serde_json::from_value::<TaskArtifactUpdateEvent>(result) {
346 yield Ok(UpdateEvent::TaskArtifactUpdate(artifact_event));
347 }
348 } else if let Some(error) = rpc_response.error {
349 yield Err(adk_core::AdkError::agent(format!(
350 "RPC error: {} ({})",
351 error.message, error.code
352 )));
353 return;
354 }
355 }
356 Err(e) => {
357 tracing::debug!("Failed to parse SSE data: {e}");
359 }
360 }
361 }
362 }
363
364 if !finished {
365 yield Err(truncated_stream_error());
366 }
367 };
368
369 Ok(Box::pin(stream))
370 }
371}
372
373fn ends_task(update: &TaskStatusUpdateEvent) -> bool {
376 use crate::a2a::TaskState;
377 update.final_update
378 || match update.status.state {
379 TaskState::Completed
380 | TaskState::Failed
381 | TaskState::Canceled
382 | TaskState::InputRequired
383 | TaskState::AuthRequired => true,
384 TaskState::Submitted | TaskState::Working => false,
385 }
386}
387
388pub(crate) fn truncated_stream_error() -> adk_core::AdkError {
390 adk_core::AdkError::agent(
391 "the A2A stream ended before the task reached a final status; the response is incomplete",
392 )
393}
394
395#[derive(Default)]
402pub(crate) struct SseDecoder {
403 buffer: Vec<u8>,
404 data: Vec<String>,
405}
406
407impl SseDecoder {
408 pub(crate) fn push(&mut self, chunk: &[u8]) -> Result<Vec<String>> {
414 self.buffer.extend_from_slice(chunk);
415 let mut events = Vec::new();
416 while let Some(end) = self.buffer.iter().position(|&byte| byte == b'\n' || byte == b'\r') {
417 let consumed = match (self.buffer[end], self.buffer.get(end + 1)) {
420 (b'\r', Some(b'\n')) => end + 2,
421 (b'\r', None) => break,
422 _ => end + 1,
423 };
424 let line: Vec<u8> = self.buffer.drain(..consumed).collect();
425 let line = std::str::from_utf8(&line[..end]).map_err(|error| {
426 adk_core::AdkError::agent(format!("the A2A stream is not valid UTF-8: {error}"))
427 })?;
428 if line.is_empty() {
429 if !self.data.is_empty() {
430 events.push(self.data.join("\n"));
431 self.data.clear();
432 }
433 } else if let Some(value) = line.strip_prefix("data:") {
434 self.data.push(value.strip_prefix(' ').unwrap_or(value).to_string());
435 }
436 }
437 Ok(events)
438 }
439}
440
441#[cfg(test)]
442mod tests {
443 use super::*;
444
445 #[test]
446 fn sse_lines_may_end_in_a_lone_cr_even_across_reads() {
447 let mut decoder = SseDecoder::default();
448 assert_eq!(
450 decoder.push(b"data: a\rdata: b\r\r:comment").unwrap(),
451 vec!["a\nb".to_string()]
452 );
453 assert!(decoder.push(b"\rdata: c\r").unwrap().is_empty());
455 assert!(decoder.push(b"\n").unwrap().is_empty());
456 assert_eq!(decoder.push(b"\r\n").unwrap(), vec!["c".to_string()]);
457 }
458
459 #[test]
460 fn a_card_endpoint_on_the_card_origin_is_accepted() {
461 let card = "https://agents.example.com/.well-known/agent-card.json";
462 assert!(check_card_endpoint(card, "https://agents.example.com/a2a", &[]).is_ok());
463 assert!(check_card_endpoint(card, "https://AGENTS.example.com:443/rpc", &[]).is_ok());
464 let local = "http://127.0.0.1:8080/.well-known/agent-card.json";
466 assert!(check_card_endpoint(local, "http://localhost:8080/a2a", &[]).is_ok());
467 assert!(check_card_endpoint(local, "http://[::1]:8080/a2a", &[]).is_ok());
468 }
469
470 #[test]
471 fn a_card_endpoint_on_another_origin_is_refused() {
472 let card = "https://agents.example.com/.well-known/agent-card.json";
473 for endpoint in [
474 "https://collector.example.net/a2a",
475 "http://agents.example.com/a2a",
476 "https://agents.example.com:8443/a2a",
477 "http://169.254.169.254/latest",
478 "http://localhost:8080/a2a",
479 ] {
480 let error = check_card_endpoint(card, endpoint, &[]).unwrap_err();
481 assert_eq!(error.code, "a2a.card_endpoint_refused", "{endpoint}");
482 }
483 let local = "http://127.0.0.1:8080/.well-known/agent-card.json";
484 assert!(check_card_endpoint(local, "http://127.0.0.1:9090/a2a", &[]).is_err());
485 }
486
487 #[test]
488 fn an_allowed_origin_must_use_https_unless_loopback() {
489 let card = "https://agents.example.com/.well-known/agent-card.json";
490 let allowed = vec![
491 "https://rpc.example.com".to_string(),
492 "http://plain.example.com".to_string(),
493 "http://localhost:9090".to_string(),
494 ];
495 assert!(check_card_endpoint(card, "https://rpc.example.com/a2a", &allowed).is_ok());
496 assert!(check_card_endpoint(card, "http://127.0.0.1:9090/a2a", &allowed).is_ok());
497 let error =
498 check_card_endpoint(card, "http://plain.example.com/a2a", &allowed).unwrap_err();
499 assert!(error.message.contains("must use https"), "{error}");
500 }
501
502 #[test]
503 fn a_refusal_names_origins_not_credentials() {
504 let error = check_card_endpoint(
505 "https://user:secret@agents.example.com/card",
506 "https://token:hunter2@collector.example.net/a2a?key=abc",
507 &[],
508 )
509 .unwrap_err();
510 for leaked in ["secret", "hunter2", "key=abc", "/a2a"] {
511 assert!(!error.message.contains(leaked), "{}", error.message);
512 }
513 }
514
515 #[test]
516 fn decoder_joins_data_lines_and_ignores_other_fields() {
517 let mut decoder = SseDecoder::default();
518 let events = decoder
519 .push(b"event: message\ndata: {\"a\":\ndata: 1}\n\n: comment\nevent: ping\n\n")
520 .unwrap();
521 assert_eq!(events, vec!["{\"a\":\n1}".to_string()]);
522 }
523
524 #[test]
525 fn decoder_keeps_a_character_split_across_reads() {
526 let frame = "data: Grüße ☕\r\n\r\n".as_bytes();
527 let split = "data: Gr".len() + 1;
528 let mut decoder = SseDecoder::default();
529 assert!(decoder.push(&frame[..split]).unwrap().is_empty());
530 assert_eq!(decoder.push(&frame[split..]).unwrap(), vec!["Grüße ☕".to_string()]);
531 }
532
533 #[test]
534 fn decoder_rejects_invalid_utf8() {
535 let mut decoder = SseDecoder::default();
536 assert!(decoder.push(b"data: \xff\n\n").is_err());
537 }
538
539 #[test]
540 fn only_final_or_stopping_statuses_end_a_task() {
541 use crate::a2a::{TaskState, TaskStatus};
542 let update = |state: TaskState, final_update: bool| TaskStatusUpdateEvent {
543 task_id: "task".to_string(),
544 context_id: None,
545 status: TaskStatus { state, message: None },
546 final_update,
547 };
548 assert!(!ends_task(&update(TaskState::Working, false)));
549 assert!(ends_task(&update(TaskState::Working, true)));
550 assert!(ends_task(&update(TaskState::InputRequired, false)));
551 assert!(ends_task(&update(TaskState::Completed, false)));
552 }
553}
554
555#[cfg(feature = "a2a-v1")]
558pub mod v1_client {
559 use a2a_protocol_types::events::StreamResponse;
567 use a2a_protocol_types::jsonrpc::JsonRpcRequest;
568 use a2a_protocol_types::params::SendMessageConfiguration;
569 use a2a_protocol_types::responses::{
570 ListPushConfigsResponse, SendMessageResponse, TaskListResponse,
571 };
572 use a2a_protocol_types::task::{Task, TaskState};
573 use a2a_protocol_types::{AgentCard, AgentInterface, Message, TaskPushNotificationConfig};
574 use reqwest::header::{HeaderMap, HeaderValue};
575 use serde_json::Value;
576 use std::time::Duration;
577
578 const A2A_VERSION_HEADER: &str = "a2a-version";
580
581 const A2A_VERSION: &str = "1.0";
583
584 const AGENT_CARD_PATH: &str = "/.well-known/agent-card.json";
586
587 const VERSION_NOT_SUPPORTED: i64 = -32009;
589
590 pub fn v1_interface<'a>(card: &'a AgentCard, binding: &str) -> Option<&'a AgentInterface> {
595 let of_binding =
596 || card.supported_interfaces.iter().filter(move |i| i.protocol_binding == binding);
597 of_binding()
598 .find(|i| i.protocol_version.split('.').next() == Some("1"))
599 .or_else(|| of_binding().find(|i| i.protocol_version.trim().is_empty()))
600 }
601
602 fn parse_send_message_result(result: Value) -> Result<SendMessageResponse, serde_json::Error> {
610 serde_json::from_value::<SendMessageResponse>(result.clone()).or_else(|oneof_error| {
611 serde_json::from_value::<Task>(result)
612 .map(SendMessageResponse::Task)
613 .map_err(|_| oneof_error)
614 })
615 }
616
617 pub type UpdateStream =
619 futures::stream::BoxStream<'static, Result<StreamResponse, V1ClientError>>;
620
621 pub(crate) fn parse_stream_payload(
624 data: &str,
625 ) -> Option<Result<StreamResponse, V1ClientError>> {
626 if data.trim().is_empty() {
627 return None;
628 }
629 if let Ok(update) = serde_json::from_str::<StreamResponse>(data) {
630 return Some(Ok(update));
631 }
632 let value = serde_json::from_str::<Value>(data).ok()?;
633 if let Some(result) = value.get("result")
634 && let Ok(update) = serde_json::from_value::<StreamResponse>(result.clone())
635 {
636 return Some(Ok(update));
637 }
638 let error = value.get("error")?;
639 Some(Err(V1ClientError::JsonRpc {
640 code: error.get("code").and_then(Value::as_i64).unwrap_or(0) as i32,
641 message: error
642 .get("message")
643 .and_then(Value::as_str)
644 .unwrap_or("unknown error")
645 .to_string(),
646 data: error.get("data").cloned(),
647 }))
648 }
649
650 fn parse_task_list(result: Value) -> Result<TaskListResponse, serde_json::Error> {
657 if result.is_array() {
658 let tasks: Vec<Task> = serde_json::from_value(result)?;
659 let count = u32::try_from(tasks.len()).unwrap_or(u32::MAX);
660 return Ok(TaskListResponse {
661 tasks,
662 next_page_token: String::new(),
663 page_size: count,
664 total_size: count,
665 });
666 }
667 serde_json::from_value(result)
668 }
669
670 fn parse_push_config_list(
677 result: Value,
678 ) -> Result<Vec<TaskPushNotificationConfig>, serde_json::Error> {
679 if result.is_array() {
680 return serde_json::from_value(result);
681 }
682 serde_json::from_value::<ListPushConfigsResponse>(result).map(|page| page.configs)
683 }
684
685 #[derive(Debug, Clone)]
687 pub struct RetryConfig {
688 pub max_retries: u32,
690 pub base_delay: Duration,
692 }
693
694 impl Default for RetryConfig {
695 fn default() -> Self {
696 Self { max_retries: 3, base_delay: Duration::from_secs(1) }
697 }
698 }
699
700 #[derive(Debug, thiserror::Error)]
702 pub enum V1ClientError {
703 #[error("HTTP error: {0}")]
705 Http(#[from] reqwest::Error),
706
707 #[error("JSON-RPC error {code}: {message}")]
709 JsonRpc { code: i32, message: String, data: Option<Value> },
710
711 #[error("version not supported: requested {requested}, server supports: {supported:?}")]
713 VersionNotSupported { requested: String, supported: Vec<String> },
714
715 #[error("serialization error: {0}")]
717 Serde(#[from] serde_json::Error),
718
719 #[error("credential refused: {0}")]
722 Credential(#[from] adk_core::AdkError),
723
724 #[error("unexpected HTTP status {status}: {body}")]
726 UnexpectedStatus { status: u16, body: String },
727
728 #[error("agent card refused: {0}")]
731 CardEndpoint(adk_core::AdkError),
732 }
733
734 fn check_interfaces(
737 card_url: &str,
738 card: &AgentCard,
739 allowed_origins: &[String],
740 ) -> Result<(), V1ClientError> {
741 card.supported_interfaces
742 .iter()
743 .filter(|interface| {
744 matches!(interface.protocol_binding.as_str(), "JSONRPC" | "HTTP+JSON")
745 })
746 .try_for_each(|interface| {
747 super::check_card_endpoint(card_url, &interface.url, allowed_origins)
748 })
749 .map_err(V1ClientError::CardEndpoint)
750 }
751
752 #[derive(Debug, Clone, Default)]
754 struct CachedCard {
755 card: Option<AgentCard>,
756 etag: Option<String>,
757 last_modified: Option<String>,
758 }
759
760 const CARD_FETCH_TIMEOUT: Duration = Duration::from_secs(30);
768
769 enum CardSource {
771 Url(String),
772 File(std::path::PathBuf),
773 }
774
775 fn card_source(source: &str) -> Result<CardSource, V1ClientError> {
780 let unsupported = || V1ClientError::UnexpectedStatus {
781 status: 0,
782 body: format!(
783 "unsupported agent card source {source:?}: use an http(s) URL or a file path"
784 ),
785 };
786 match source.split_once("://") {
787 None => Ok(CardSource::File(std::path::PathBuf::from(source))),
788 Some(("file", path)) => Ok(CardSource::File(std::path::PathBuf::from(path))),
789 Some((scheme, _))
790 if scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https") =>
791 {
792 let url = adk_core::Url::parse(source).map_err(|_| unsupported())?;
793 if url.path().ends_with(".json") {
794 Ok(CardSource::Url(source.to_string()))
795 } else {
796 Ok(CardSource::Url(format!(
797 "{}{AGENT_CARD_PATH}",
798 source.trim_end_matches('/')
799 )))
800 }
801 }
802 Some(_) => Err(unsupported()),
803 }
804 }
805
806 pub struct A2aV1Client {
807 http_client: reqwest::Client,
808 agent_card: AgentCard,
809 retry_config: RetryConfig,
810 cached_card: std::sync::Mutex<CachedCard>,
811 credential: Option<adk_core::ScopedToken>,
812 }
813
814 impl A2aV1Client {
815 pub fn new(agent_card: AgentCard) -> Self {
817 Self {
818 http_client: reqwest::Client::new(),
819 agent_card,
820 retry_config: RetryConfig::default(),
821 cached_card: std::sync::Mutex::new(CachedCard::default()),
822 credential: None,
823 }
824 }
825
826 pub fn with_retry(agent_card: AgentCard, retry_config: RetryConfig) -> Self {
828 Self {
829 http_client: reqwest::Client::new(),
830 agent_card,
831 retry_config,
832 cached_card: std::sync::Mutex::new(CachedCard::default()),
833 credential: None,
834 }
835 }
836
837 pub fn with_credential(mut self, token: adk_core::ScopedToken) -> Self {
844 self.credential = Some(token);
845 self
846 }
847
848 fn headers_for(&self, url: &str) -> Result<HeaderMap, V1ClientError> {
851 let mut headers = Self::default_headers();
852 if let Some(token) = &self.credential {
853 let target = adk_core::Url::parse(url).map_err(|error| {
854 adk_core::AdkError::agent(format!("invalid A2A endpoint URL: {error}"))
855 })?;
856 let secret = token.authorize_for(&target)?;
857 let mut value = HeaderValue::from_str(&format!("Bearer {}", secret.expose()))
858 .map_err(|_| {
859 adk_core::AdkError::agent("the brokered token is not a valid header value")
860 })?;
861 value.set_sensitive(true);
862 headers.insert(reqwest::header::AUTHORIZATION, value);
863 }
864 Ok(headers)
865 }
866
867 pub fn agent_card(&self) -> &AgentCard {
869 &self.agent_card
870 }
871
872 fn jsonrpc_url(&self) -> Option<&str> {
875 v1_interface(&self.agent_card, "JSONRPC").map(|i| i.url.as_str())
876 }
877
878 fn rest_url(&self) -> Option<&str> {
881 v1_interface(&self.agent_card, "HTTP+JSON").map(|i| i.url.as_str())
882 }
883
884 fn default_headers() -> HeaderMap {
886 let mut headers = HeaderMap::new();
887 headers.insert(A2A_VERSION_HEADER, HeaderValue::from_static(A2A_VERSION));
888 headers
889 }
890
891 pub async fn resolve_agent_card(base_url: &str) -> Result<AgentCard, V1ClientError> {
904 Self::resolve_agent_card_allowing(base_url, &[]).await
905 }
906
907 pub async fn resolve_agent_card_allowing(
914 base_url: &str,
915 allowed_origins: &[String],
916 ) -> Result<AgentCard, V1ClientError> {
917 let url = match card_source(base_url)? {
918 CardSource::File(path) => {
919 let json =
920 std::fs::read(&path).map_err(|error| V1ClientError::UnexpectedStatus {
921 status: 0,
922 body: format!(
923 "cannot read the agent card file {}: {error}",
924 path.display()
925 ),
926 })?;
927 return Ok(serde_json::from_slice(&json)?);
928 }
929 CardSource::Url(url) => url,
930 };
931 let client = reqwest::Client::builder()
932 .timeout(CARD_FETCH_TIMEOUT)
933 .build()
934 .map_err(V1ClientError::from)?;
935 let response = client.get(&url).headers(Self::default_headers()).send().await?;
936
937 if !response.status().is_success() {
938 let status = response.status().as_u16();
939 let body = response.text().await.unwrap_or_default();
940 return Err(V1ClientError::UnexpectedStatus { status, body });
941 }
942
943 let card: AgentCard = response.json().await?;
944 check_interfaces(&url, &card, allowed_origins)?;
945 Ok(card)
946 }
947
948 pub async fn resolve_agent_card_cached(
954 &self,
955 base_url: &str,
956 ) -> Result<Option<AgentCard>, V1ClientError> {
957 let url = format!("{}{AGENT_CARD_PATH}", base_url.trim_end_matches('/'));
958
959 let mut req = self.http_client.get(&url).headers(Self::default_headers());
960
961 {
963 let cache = self.cached_card.lock().unwrap();
964 if let Some(etag) = &cache.etag {
965 req = req.header("If-None-Match", etag.as_str());
966 }
967 if let Some(lm) = &cache.last_modified {
968 req = req.header("If-Modified-Since", lm.as_str());
969 }
970 }
971
972 let response = req.send().await?;
973
974 if response.status() == reqwest::StatusCode::NOT_MODIFIED {
975 return Ok(None);
976 }
977
978 if !response.status().is_success() {
979 let status = response.status().as_u16();
980 let body = response.text().await.unwrap_or_default();
981 return Err(V1ClientError::UnexpectedStatus { status, body });
982 }
983
984 let etag =
986 response.headers().get("etag").and_then(|v| v.to_str().ok()).map(String::from);
987 let last_modified = response
988 .headers()
989 .get("last-modified")
990 .and_then(|v| v.to_str().ok())
991 .map(String::from);
992
993 let card: AgentCard = response.json().await?;
994 check_interfaces(&url, &card, &[])?;
995
996 {
997 let mut cache = self.cached_card.lock().unwrap();
998 cache.card = Some(card.clone());
999 cache.etag = etag;
1000 cache.last_modified = last_modified;
1001 }
1002
1003 Ok(Some(card))
1004 }
1005
1006 async fn jsonrpc_call<T: serde::de::DeserializeOwned>(
1010 &self,
1011 method: &str,
1012 params: Value,
1013 ) -> Result<T, V1ClientError> {
1014 let url = self.jsonrpc_url().ok_or_else(|| V1ClientError::UnexpectedStatus {
1015 status: 0,
1016 body: "no JSONRPC interface in agent card".to_string(),
1017 })?;
1018
1019 let request = JsonRpcRequest::with_params(
1020 serde_json::json!(uuid::Uuid::new_v4().to_string()),
1021 method,
1022 params,
1023 );
1024
1025 let response = self.send_with_retry(url, &request).await?;
1026 let body: Value = response.json().await?;
1027
1028 if let Some(err) = body.get("error") {
1032 if err.get("code").and_then(Value::as_i64) == Some(VERSION_NOT_SUPPORTED) {
1033 return Err(Self::parse_version_error(err));
1034 }
1035 return Err(Self::parse_jsonrpc_error(&body));
1036 }
1037
1038 let result = body.get("result").cloned().unwrap_or(Value::Null);
1040 let parsed: T = serde_json::from_value(result)?;
1041 Ok(parsed)
1042 }
1043
1044 async fn send_with_retry(
1046 &self,
1047 url: &str,
1048 request: &JsonRpcRequest,
1049 ) -> Result<reqwest::Response, V1ClientError> {
1050 let mut last_err = None;
1051
1052 for attempt in 0..=self.retry_config.max_retries {
1053 if attempt > 0 {
1054 let delay = self.retry_config.base_delay * 2u32.pow(attempt - 1);
1055 tokio::time::sleep(delay).await;
1056 }
1057
1058 match self
1059 .http_client
1060 .post(url)
1061 .headers(self.headers_for(url)?)
1062 .json(request)
1063 .send()
1064 .await
1065 {
1066 Ok(resp) => {
1067 let status = resp.status().as_u16();
1068 if (status == 429 || status >= 500)
1070 && attempt < self.retry_config.max_retries
1071 {
1072 last_err = Some(V1ClientError::UnexpectedStatus {
1073 status,
1074 body: format!("retryable status on attempt {attempt}"),
1075 });
1076 continue;
1077 }
1078 return Ok(resp);
1079 }
1080 Err(e) => {
1081 if attempt < self.retry_config.max_retries && e.is_timeout() {
1082 last_err = Some(V1ClientError::Http(e));
1083 continue;
1084 }
1085 return Err(V1ClientError::Http(e));
1086 }
1087 }
1088 }
1089
1090 Err(last_err.unwrap_or_else(|| V1ClientError::UnexpectedStatus {
1091 status: 0,
1092 body: "retry exhausted".to_string(),
1093 }))
1094 }
1095
1096 async fn rest_post<T: serde::de::DeserializeOwned>(
1101 &self,
1102 path: &str,
1103 body: &Value,
1104 ) -> Result<T, V1ClientError> {
1105 let base = match self.rest_url() {
1106 Some(url) => url.to_string(),
1107 None => {
1108 return Err(V1ClientError::UnexpectedStatus {
1109 status: 0,
1110 body: "no HTTP+JSON interface in agent card".to_string(),
1111 });
1112 }
1113 };
1114 let url = format!("{}{path}", base.trim_end_matches('/'));
1115
1116 let response = self
1117 .http_client
1118 .post(&url)
1119 .headers(self.headers_for(&url)?)
1120 .header("content-type", "application/a2a+json")
1121 .json(body)
1122 .send()
1123 .await?;
1124
1125 if !response.status().is_success() {
1126 let status = response.status().as_u16();
1127 let body_text = response.text().await.unwrap_or_default();
1128 return Err(V1ClientError::UnexpectedStatus { status, body: body_text });
1129 }
1130
1131 let result: T = response.json().await?;
1132 Ok(result)
1133 }
1134
1135 async fn rest_get<T: serde::de::DeserializeOwned>(
1137 &self,
1138 path: &str,
1139 ) -> Result<T, V1ClientError> {
1140 let base = match self.rest_url() {
1141 Some(url) => url.to_string(),
1142 None => {
1143 return Err(V1ClientError::UnexpectedStatus {
1144 status: 0,
1145 body: "no HTTP+JSON interface in agent card".to_string(),
1146 });
1147 }
1148 };
1149 let url = format!("{}{path}", base.trim_end_matches('/'));
1150
1151 let response =
1152 self.http_client.get(&url).headers(self.headers_for(&url)?).send().await?;
1153
1154 if !response.status().is_success() {
1155 let status = response.status().as_u16();
1156 let body_text = response.text().await.unwrap_or_default();
1157 return Err(V1ClientError::UnexpectedStatus { status, body: body_text });
1158 }
1159
1160 let result: T = response.json().await?;
1161 Ok(result)
1162 }
1163
1164 async fn rest_delete(&self, path: &str) -> Result<(), V1ClientError> {
1166 let base = match self.rest_url() {
1167 Some(url) => url.to_string(),
1168 None => {
1169 return Err(V1ClientError::UnexpectedStatus {
1170 status: 0,
1171 body: "no HTTP+JSON interface in agent card".to_string(),
1172 });
1173 }
1174 };
1175 let url = format!("{}{path}", base.trim_end_matches('/'));
1176
1177 let response =
1178 self.http_client.delete(&url).headers(self.headers_for(&url)?).send().await?;
1179
1180 if !response.status().is_success() {
1181 let status = response.status().as_u16();
1182 let body_text = response.text().await.unwrap_or_default();
1183 return Err(V1ClientError::UnexpectedStatus { status, body: body_text });
1184 }
1185
1186 Ok(())
1187 }
1188
1189 fn parse_jsonrpc_error(body: &Value) -> V1ClientError {
1193 let err = match body.get("error") {
1194 Some(e) => e,
1195 None => {
1196 return V1ClientError::JsonRpc {
1197 code: 0,
1198 message: "unknown error".to_string(),
1199 data: Some(body.clone()),
1200 };
1201 }
1202 };
1203
1204 let code = err.get("code").and_then(|c| c.as_i64()).unwrap_or(0) as i32;
1205 let message =
1206 err.get("message").and_then(|m| m.as_str()).unwrap_or("unknown error").to_string();
1207 let data = err.get("data").cloned();
1208
1209 V1ClientError::JsonRpc { code, message, data }
1210 }
1211
1212 fn parse_version_error(err: &Value) -> V1ClientError {
1215 let data = err.get("data");
1216 let mut supported = Vec::new();
1217
1218 if let Some(data_arr) = data.and_then(|d| d.as_array()) {
1220 for info in data_arr {
1221 if let Some(meta) = info.get("metadata")
1222 && let Some(versions) = meta.get("supported").and_then(|v| v.as_str())
1223 {
1224 supported = versions.split(", ").map(String::from).collect();
1225 }
1226 }
1227 }
1228
1229 V1ClientError::VersionNotSupported { requested: A2A_VERSION.to_string(), supported }
1230 }
1231
1232 pub async fn send_message(
1247 &self,
1248 message: Message,
1249 ) -> Result<SendMessageResponse, V1ClientError> {
1250 self.send_message_with(message, None).await
1251 }
1252
1253 pub async fn send_message_with(
1260 &self,
1261 message: Message,
1262 configuration: Option<&SendMessageConfiguration>,
1263 ) -> Result<SendMessageResponse, V1ClientError> {
1264 let mut params = serde_json::json!({ "message": message });
1265 if let Some(configuration) = configuration {
1266 params["configuration"] = serde_json::to_value(configuration)?;
1267 }
1268 let result: Value = self.jsonrpc_call("SendMessage", params).await?;
1269 Ok(parse_send_message_result(result)?)
1270 }
1271
1272 pub async fn send_streaming_message(
1276 &self,
1277 message: Message,
1278 ) -> Result<reqwest::Response, V1ClientError> {
1279 let url = self.jsonrpc_url().ok_or_else(|| V1ClientError::UnexpectedStatus {
1280 status: 0,
1281 body: "no JSONRPC interface in agent card".to_string(),
1282 })?;
1283
1284 let request = JsonRpcRequest::with_params(
1285 serde_json::json!(uuid::Uuid::new_v4().to_string()),
1286 "SendStreamingMessage",
1287 serde_json::json!({ "message": message }),
1288 );
1289
1290 let response = self
1291 .http_client
1292 .post(url)
1293 .headers(self.headers_for(url)?)
1294 .json(&request)
1295 .send()
1296 .await?;
1297
1298 Ok(response)
1299 }
1300
1301 pub async fn get_task(
1303 &self,
1304 task_id: &str,
1305 history_length: Option<u32>,
1306 ) -> Result<Task, V1ClientError> {
1307 let mut params = serde_json::json!({ "id": task_id });
1308 if let Some(len) = history_length {
1309 params["historyLength"] = serde_json::json!(len);
1310 }
1311 self.jsonrpc_call("GetTask", params).await
1312 }
1313
1314 pub async fn cancel_task(&self, task_id: &str) -> Result<Task, V1ClientError> {
1316 self.jsonrpc_call("CancelTask", serde_json::json!({ "id": task_id })).await
1317 }
1318
1319 pub async fn list_tasks(
1321 &self,
1322 context_id: Option<&str>,
1323 status: Option<TaskState>,
1324 page_size: Option<u32>,
1325 page_token: Option<&str>,
1326 ) -> Result<TaskListResponse, V1ClientError> {
1327 let mut params = serde_json::json!({});
1328 if let Some(cid) = context_id {
1329 params["contextId"] = serde_json::json!(cid);
1330 }
1331 if let Some(s) = status {
1332 params["status"] = serde_json::to_value(s)?;
1333 }
1334 if let Some(ps) = page_size {
1335 params["pageSize"] = serde_json::json!(ps);
1336 }
1337 if let Some(pt) = page_token {
1338 params["pageToken"] = serde_json::json!(pt);
1339 }
1340 let result: Value = self.jsonrpc_call("ListTasks", params).await?;
1341 Ok(parse_task_list(result)?)
1342 }
1343
1344 pub async fn subscribe_to_task(
1348 &self,
1349 task_id: &str,
1350 ) -> Result<reqwest::Response, V1ClientError> {
1351 let url = self.jsonrpc_url().ok_or_else(|| V1ClientError::UnexpectedStatus {
1352 status: 0,
1353 body: "no JSONRPC interface in agent card".to_string(),
1354 })?;
1355
1356 let request = JsonRpcRequest::with_params(
1357 serde_json::json!(uuid::Uuid::new_v4().to_string()),
1358 "SubscribeToTask",
1359 serde_json::json!({ "id": task_id }),
1360 );
1361
1362 let response = self
1363 .http_client
1364 .post(url)
1365 .headers(self.headers_for(url)?)
1366 .json(&request)
1367 .send()
1368 .await?;
1369
1370 Ok(response)
1371 }
1372
1373 pub async fn stream_message(
1384 &self,
1385 message: Message,
1386 ) -> Result<UpdateStream, V1ClientError> {
1387 self.stream_message_with(message, None).await
1388 }
1389
1390 pub async fn stream_message_with(
1397 &self,
1398 message: Message,
1399 configuration: Option<&SendMessageConfiguration>,
1400 ) -> Result<UpdateStream, V1ClientError> {
1401 let mut body = serde_json::json!({ "message": message });
1402 if let Some(configuration) = configuration {
1403 body["configuration"] = serde_json::to_value(configuration)?;
1404 }
1405 match self.jsonrpc_url() {
1406 Some(url) => {
1407 let request = JsonRpcRequest::with_params(
1408 serde_json::json!(uuid::Uuid::new_v4().to_string()),
1409 "SendStreamingMessage",
1410 body,
1411 );
1412 let builder =
1413 self.http_client.post(url).headers(self.headers_for(url)?).json(&request);
1414 Self::open_stream(builder).await
1415 }
1416 None => {
1417 let url = self.rest_endpoint("/message:stream")?;
1418 let builder = self
1419 .http_client
1420 .post(&url)
1421 .headers(self.headers_for(&url)?)
1422 .header("content-type", "application/a2a+json")
1423 .json(&body);
1424 Self::open_stream(builder).await
1425 }
1426 }
1427 }
1428
1429 pub async fn subscribe(&self, task_id: &str) -> Result<UpdateStream, V1ClientError> {
1438 match self.jsonrpc_url() {
1439 Some(url) => {
1440 let request = JsonRpcRequest::with_params(
1441 serde_json::json!(uuid::Uuid::new_v4().to_string()),
1442 "SubscribeToTask",
1443 serde_json::json!({ "id": task_id }),
1444 );
1445 let builder =
1446 self.http_client.post(url).headers(self.headers_for(url)?).json(&request);
1447 Self::open_stream(builder).await
1448 }
1449 None => {
1450 let url = self.rest_endpoint(&format!("/tasks/{task_id}:subscribe"))?;
1451 let builder = self.http_client.get(&url).headers(self.headers_for(&url)?);
1452 Self::open_stream(builder).await
1453 }
1454 }
1455 }
1456
1457 fn rest_endpoint(&self, path: &str) -> Result<String, V1ClientError> {
1459 let base = self.rest_url().ok_or_else(|| V1ClientError::UnexpectedStatus {
1460 status: 0,
1461 body: "no JSONRPC or HTTP+JSON interface in agent card".to_string(),
1462 })?;
1463 Ok(format!("{}{path}", base.trim_end_matches('/')))
1464 }
1465
1466 async fn open_stream(
1468 request: reqwest::RequestBuilder,
1469 ) -> Result<UpdateStream, V1ClientError> {
1470 use futures::StreamExt;
1471
1472 let response = request.send().await?;
1473 let status = response.status().as_u16();
1474 let is_sse = response
1475 .headers()
1476 .get(reqwest::header::CONTENT_TYPE)
1477 .and_then(|value| value.to_str().ok())
1478 .is_some_and(|value| value.starts_with("text/event-stream"));
1479 if !is_sse {
1480 let body = response.text().await.unwrap_or_default();
1483 if let Ok(value) = serde_json::from_str::<Value>(&body)
1484 && let Some(error) = value.get("error")
1485 {
1486 if error.get("code").and_then(Value::as_i64) == Some(VERSION_NOT_SUPPORTED) {
1487 return Err(Self::parse_version_error(error));
1488 }
1489 if error.get("code").and_then(Value::as_i64).is_some() {
1490 return Err(Self::parse_jsonrpc_error(&value));
1491 }
1492 }
1493 return Err(V1ClientError::UnexpectedStatus { status, body });
1494 }
1495
1496 let mut bytes = response.bytes_stream();
1497 let updates = async_stream::stream! {
1498 let mut decoder = super::SseDecoder::default();
1499 while let Some(chunk) = bytes.next().await {
1500 let chunk = match chunk {
1501 Ok(chunk) => chunk,
1502 Err(error) => {
1503 yield Err(V1ClientError::Http(error));
1504 return;
1505 }
1506 };
1507 let payloads = match decoder.push(&chunk) {
1508 Ok(payloads) => payloads,
1509 Err(error) => {
1510 yield Err(V1ClientError::UnexpectedStatus { status, body: error.to_string() });
1511 return;
1512 }
1513 };
1514 for data in payloads {
1515 match parse_stream_payload(&data) {
1516 Some(Ok(update)) => yield Ok(update),
1517 Some(Err(error)) => {
1518 yield Err(error);
1519 return;
1520 }
1521 None => tracing::debug!("SSE data that is no A2A update: {data}"),
1522 }
1523 }
1524 }
1525 };
1526 Ok(Box::pin(updates))
1527 }
1528
1529 pub async fn create_push_notification_config(
1532 &self,
1533 config: TaskPushNotificationConfig,
1534 ) -> Result<TaskPushNotificationConfig, V1ClientError> {
1535 self.jsonrpc_call("CreateTaskPushNotificationConfig", serde_json::to_value(&config)?)
1536 .await
1537 }
1538
1539 pub async fn get_push_notification_config(
1542 &self,
1543 task_id: &str,
1544 config_id: &str,
1545 ) -> Result<TaskPushNotificationConfig, V1ClientError> {
1546 self.jsonrpc_call(
1547 "GetTaskPushNotificationConfig",
1548 serde_json::json!({ "taskId": task_id, "id": config_id }),
1549 )
1550 .await
1551 }
1552
1553 pub async fn list_push_notification_configs(
1556 &self,
1557 task_id: &str,
1558 ) -> Result<Vec<TaskPushNotificationConfig>, V1ClientError> {
1559 let result: Value = self
1560 .jsonrpc_call(
1561 "ListTaskPushNotificationConfigs",
1562 serde_json::json!({ "taskId": task_id }),
1563 )
1564 .await?;
1565 Ok(parse_push_config_list(result)?)
1566 }
1567
1568 pub async fn delete_push_notification_config(
1571 &self,
1572 task_id: &str,
1573 config_id: &str,
1574 ) -> Result<(), V1ClientError> {
1575 let _: Value = self
1576 .jsonrpc_call(
1577 "DeleteTaskPushNotificationConfig",
1578 serde_json::json!({ "taskId": task_id, "id": config_id }),
1579 )
1580 .await?;
1581 Ok(())
1582 }
1583
1584 pub async fn get_extended_agent_card(&self) -> Result<AgentCard, V1ClientError> {
1586 self.jsonrpc_call("GetExtendedAgentCard", serde_json::json!({})).await
1587 }
1588
1589 pub async fn send_message_rest(
1601 &self,
1602 message: Message,
1603 ) -> Result<SendMessageResponse, V1ClientError> {
1604 self.send_message_rest_with(message, None).await
1605 }
1606
1607 pub async fn send_message_rest_with(
1614 &self,
1615 message: Message,
1616 configuration: Option<&SendMessageConfiguration>,
1617 ) -> Result<SendMessageResponse, V1ClientError> {
1618 let mut request = serde_json::json!({ "message": message });
1619 if let Some(configuration) = configuration {
1620 request["configuration"] = serde_json::to_value(configuration)?;
1621 }
1622 let body: Value = self.rest_post("/message:send", &request).await?;
1623 Ok(parse_send_message_result(body)?)
1624 }
1625
1626 pub async fn get_task_rest(&self, task_id: &str) -> Result<Task, V1ClientError> {
1628 self.rest_get(&format!("/tasks/{task_id}")).await
1629 }
1630
1631 pub async fn cancel_task_rest(&self, task_id: &str) -> Result<Task, V1ClientError> {
1633 self.rest_post(&format!("/tasks/{task_id}:cancel"), &serde_json::json!({})).await
1634 }
1635
1636 pub async fn list_tasks_rest(&self) -> Result<TaskListResponse, V1ClientError> {
1638 let body: Value = self.rest_get("/tasks").await?;
1639 Ok(parse_task_list(body)?)
1640 }
1641
1642 pub async fn create_push_notification_config_rest(
1645 &self,
1646 task_id: &str,
1647 config: TaskPushNotificationConfig,
1648 ) -> Result<TaskPushNotificationConfig, V1ClientError> {
1649 self.rest_post(
1650 &format!("/tasks/{task_id}/pushNotificationConfigs"),
1651 &serde_json::to_value(&config)?,
1652 )
1653 .await
1654 }
1655
1656 pub async fn get_push_notification_config_rest(
1659 &self,
1660 task_id: &str,
1661 config_id: &str,
1662 ) -> Result<TaskPushNotificationConfig, V1ClientError> {
1663 self.rest_get(&format!("/tasks/{task_id}/pushNotificationConfigs/{config_id}")).await
1664 }
1665
1666 pub async fn list_push_notification_configs_rest(
1669 &self,
1670 task_id: &str,
1671 ) -> Result<Vec<TaskPushNotificationConfig>, V1ClientError> {
1672 let body: Value =
1673 self.rest_get(&format!("/tasks/{task_id}/pushNotificationConfigs")).await?;
1674 Ok(parse_push_config_list(body)?)
1675 }
1676
1677 pub async fn delete_push_notification_config_rest(
1680 &self,
1681 task_id: &str,
1682 config_id: &str,
1683 ) -> Result<(), V1ClientError> {
1684 self.rest_delete(&format!("/tasks/{task_id}/pushNotificationConfigs/{config_id}")).await
1685 }
1686
1687 pub async fn get_extended_agent_card_rest(&self) -> Result<AgentCard, V1ClientError> {
1689 self.rest_get("/extendedAgentCard").await
1690 }
1691 }
1692
1693 #[cfg(test)]
1694 mod tests {
1695 #[test]
1696 fn card_sources_read_as_adk_go_reads_them() {
1697 let url = |source: &str| match super::card_source(source).unwrap() {
1698 super::CardSource::Url(url) => url,
1699 super::CardSource::File(path) => panic!("{source} is a file: {path:?}"),
1700 };
1701 assert_eq!(
1702 url("https://agents.example.com"),
1703 "https://agents.example.com/.well-known/agent-card.json"
1704 );
1705 assert_eq!(
1706 url("https://agents.example.com/billing/"),
1707 "https://agents.example.com/billing/.well-known/agent-card.json"
1708 );
1709 assert_eq!(
1710 url("https://agents.example.com/cards/billing.json"),
1711 "https://agents.example.com/cards/billing.json"
1712 );
1713 assert!(matches!(
1714 super::card_source("./cards/billing.json").unwrap(),
1715 super::CardSource::File(_)
1716 ));
1717 assert!(matches!(
1718 super::card_source("file:///etc/card.json").unwrap(),
1719 super::CardSource::File(_)
1720 ));
1721 assert!(super::card_source("ftp://agents.example.com/card.json").is_err());
1722 }
1723
1724 #[tokio::test]
1725 async fn a_card_file_is_read() {
1726 let dir = std::env::temp_dir().join(format!("a2a-card-{}", uuid::Uuid::new_v4()));
1727 std::fs::create_dir_all(&dir).unwrap();
1728 let path = dir.join("card.json");
1729 std::fs::write(
1730 &path,
1731 serde_json::json!({
1732 "name": "file-agent",
1733 "description": "from a file",
1734 "version": "1.0.0",
1735 "supportedInterfaces": [{"url": "https://a.example/a2a/v1", "protocolBinding": "JSONRPC", "protocolVersion": "1.0"}],
1736 "capabilities": {},
1737 "defaultInputModes": ["text/plain"],
1738 "defaultOutputModes": ["text/plain"],
1739 "skills": []
1740 })
1741 .to_string(),
1742 )
1743 .unwrap();
1744 let card =
1745 super::A2aV1Client::resolve_agent_card(path.to_str().unwrap()).await.unwrap();
1746 assert_eq!(card.name, "file-agent");
1747 std::fs::remove_dir_all(&dir).unwrap();
1748 }
1749
1750 use super::*;
1751 use a2a_protocol_types::{AgentCapabilities, AgentCard, AgentInterface, AgentSkill};
1752
1753 fn make_test_card() -> AgentCard {
1754 AgentCard {
1755 name: "test-agent".to_string(),
1756 url: Some("http://localhost:9999".to_string()),
1757 description: "A test agent".to_string(),
1758 version: "1.0.0".to_string(),
1759 supported_interfaces: vec![
1760 AgentInterface {
1761 url: "http://localhost:9999/a2a".to_string(),
1762 protocol_binding: "JSONRPC".to_string(),
1763 protocol_version: "1.0".to_string(),
1764 tenant: None,
1765 },
1766 AgentInterface {
1767 url: "http://localhost:9999/rest".to_string(),
1768 protocol_binding: "HTTP+JSON".to_string(),
1769 protocol_version: "1.0".to_string(),
1770 tenant: None,
1771 },
1772 ],
1773 default_input_modes: vec!["text/plain".to_string()],
1774 default_output_modes: vec!["text/plain".to_string()],
1775 skills: vec![AgentSkill {
1776 id: "echo".to_string(),
1777 name: "Echo".to_string(),
1778 description: "Echoes input".to_string(),
1779 tags: vec![],
1780 examples: None,
1781 input_modes: None,
1782 output_modes: None,
1783 security_requirements: None,
1784 }],
1785 capabilities: AgentCapabilities::default(),
1786 provider: None,
1787 icon_url: None,
1788 documentation_url: None,
1789 security_schemes: None,
1790 security_requirements: None,
1791 signatures: None,
1792 }
1793 }
1794
1795 fn make_jsonrpc_only_card() -> AgentCard {
1796 let mut card = make_test_card();
1797 card.supported_interfaces.retain(|i| i.protocol_binding == "JSONRPC");
1798 card
1799 }
1800
1801 #[test]
1802 fn new_client_stores_agent_card() {
1803 let card = make_test_card();
1804 let client = A2aV1Client::new(card.clone());
1805 assert_eq!(client.agent_card().name, "test-agent");
1806 assert_eq!(client.agent_card().version, "1.0.0");
1807 }
1808
1809 #[test]
1810 fn with_retry_stores_config() {
1811 let card = make_test_card();
1812 let config = RetryConfig { max_retries: 5, base_delay: Duration::from_millis(500) };
1813 let client = A2aV1Client::with_retry(card, config);
1814 assert_eq!(client.retry_config.max_retries, 5);
1815 assert_eq!(client.retry_config.base_delay, Duration::from_millis(500));
1816 }
1817
1818 #[test]
1819 fn default_retry_config() {
1820 let config = RetryConfig::default();
1821 assert_eq!(config.max_retries, 3);
1822 assert_eq!(config.base_delay, Duration::from_secs(1));
1823 }
1824
1825 #[test]
1826 fn jsonrpc_url_found() {
1827 let client = A2aV1Client::new(make_test_card());
1828 assert_eq!(client.jsonrpc_url(), Some("http://localhost:9999/a2a"));
1829 }
1830
1831 #[test]
1832 fn rest_url_found() {
1833 let client = A2aV1Client::new(make_test_card());
1834 assert_eq!(client.rest_url(), Some("http://localhost:9999/rest"));
1835 }
1836
1837 #[test]
1838 fn rest_url_none_when_not_available() {
1839 let client = A2aV1Client::new(make_jsonrpc_only_card());
1840 assert!(client.rest_url().is_none());
1841 }
1842
1843 #[test]
1844 fn default_headers_include_version() {
1845 let headers = A2aV1Client::default_headers();
1846 let version = headers.get(A2A_VERSION_HEADER).unwrap();
1847 assert_eq!(version, "1.0");
1848 }
1849
1850 #[test]
1851 fn parse_jsonrpc_error_extracts_fields() {
1852 let body = serde_json::json!({
1853 "jsonrpc": "2.0",
1854 "error": {
1855 "code": -32001,
1856 "message": "Task not found: task_123",
1857 "data": [{"@type": "type.googleapis.com/google.rpc.ErrorInfo"}]
1858 },
1859 "id": 1
1860 });
1861 let err = A2aV1Client::parse_jsonrpc_error(&body);
1862 match err {
1863 V1ClientError::JsonRpc { code, message, data } => {
1864 assert_eq!(code, -32001);
1865 assert_eq!(message, "Task not found: task_123");
1866 assert!(data.is_some());
1867 }
1868 other => panic!("expected JsonRpc error, got: {other}"),
1869 }
1870 }
1871
1872 #[test]
1873 fn parse_jsonrpc_error_handles_missing_error_field() {
1874 let body = serde_json::json!({"result": "ok"});
1875 let err = A2aV1Client::parse_jsonrpc_error(&body);
1876 match err {
1877 V1ClientError::JsonRpc { code, .. } => {
1878 assert_eq!(code, 0);
1879 }
1880 other => panic!("expected JsonRpc error, got: {other}"),
1881 }
1882 }
1883
1884 #[test]
1885 fn parse_version_error_extracts_supported_versions() {
1886 let err_obj = serde_json::json!({
1887 "code": -32009,
1888 "message": "Version not supported",
1889 "data": [{
1890 "@type": "type.googleapis.com/google.rpc.ErrorInfo",
1891 "reason": "VERSION_NOT_SUPPORTED",
1892 "domain": "a2a-protocol.org",
1893 "metadata": {
1894 "requested": "2.0",
1895 "supported": "0.3, 1.0"
1896 }
1897 }]
1898 });
1899 let err = A2aV1Client::parse_version_error(&err_obj);
1900 match err {
1901 V1ClientError::VersionNotSupported { requested, supported } => {
1902 assert_eq!(requested, "1.0");
1903 assert_eq!(supported, vec!["0.3", "1.0"]);
1904 }
1905 other => panic!("expected VersionNotSupported, got: {other}"),
1906 }
1907 }
1908
1909 #[test]
1910 fn send_message_results_read_the_v1_oneof() {
1911 let task = serde_json::json!({
1912 "id": "t-1",
1913 "contextId": "c-1",
1914 "status": { "state": "TASK_STATE_COMPLETED" }
1915 });
1916 match parse_send_message_result(serde_json::json!({ "task": task })).unwrap() {
1917 SendMessageResponse::Task(task) => assert_eq!(task.id.0, "t-1"),
1918 other => panic!("expected a task, got {other:?}"),
1919 }
1920
1921 let message = serde_json::json!({
1922 "messageId": "m-1",
1923 "role": "ROLE_AGENT",
1924 "parts": [{ "text": "hi" }]
1925 });
1926 match parse_send_message_result(serde_json::json!({ "message": message })).unwrap() {
1927 SendMessageResponse::Message(message) => assert_eq!(message.id.0, "m-1"),
1928 other => panic!("expected a message, got {other:?}"),
1929 }
1930 }
1931
1932 #[test]
1933 fn send_message_results_accept_the_bare_task_older_servers_send() {
1934 let bare = serde_json::json!({
1935 "id": "t-2",
1936 "contextId": "c-2",
1937 "status": { "state": "TASK_STATE_WORKING" }
1938 });
1939 match parse_send_message_result(bare).unwrap() {
1940 SendMessageResponse::Task(task) => {
1941 assert_eq!(task.id.0, "t-2");
1942 assert_eq!(task.status.state, TaskState::Working);
1943 }
1944 other => panic!("expected a task, got {other:?}"),
1945 }
1946 }
1947
1948 #[test]
1949 fn send_message_results_of_another_shape_are_refused() {
1950 for result in [
1951 serde_json::json!(null),
1952 serde_json::json!({ "status": "done" }),
1953 serde_json::json!({ "task": { "id": "t-3" } }),
1954 ] {
1955 assert!(parse_send_message_result(result.clone()).is_err(), "{result}");
1956 }
1957 }
1958
1959 #[test]
1960 fn parse_version_error_handles_empty_data() {
1961 let err_obj = serde_json::json!({
1962 "code": -32009,
1963 "message": "Version not supported"
1964 });
1965 let err = A2aV1Client::parse_version_error(&err_obj);
1966 match err {
1967 V1ClientError::VersionNotSupported { supported, .. } => {
1968 assert!(supported.is_empty());
1969 }
1970 other => panic!("expected VersionNotSupported, got: {other}"),
1971 }
1972 }
1973
1974 #[test]
1975 fn v1_client_error_display() {
1976 let err = V1ClientError::JsonRpc {
1977 code: -32001,
1978 message: "Task not found".to_string(),
1979 data: None,
1980 };
1981 assert_eq!(err.to_string(), "JSON-RPC error -32001: Task not found");
1982
1983 let err = V1ClientError::VersionNotSupported {
1984 requested: "2.0".to_string(),
1985 supported: vec!["0.3".to_string(), "1.0".to_string()],
1986 };
1987 assert!(err.to_string().contains("2.0"));
1988 assert!(err.to_string().contains("0.3"));
1989
1990 let err =
1991 V1ClientError::UnexpectedStatus { status: 500, body: "internal error".to_string() };
1992 assert!(err.to_string().contains("500"));
1993 }
1994
1995 #[test]
1996 fn cached_card_starts_empty() {
1997 let client = A2aV1Client::new(make_test_card());
1998 let cache = client.cached_card.lock().unwrap();
1999 assert!(cache.card.is_none());
2000 assert!(cache.etag.is_none());
2001 assert!(cache.last_modified.is_none());
2002 }
2003
2004 #[test]
2005 fn a_credential_is_attached_only_inside_its_audience() {
2006 let token = |audience: &str| {
2007 adk_core::ScopedToken::new(
2008 adk_core::AgentId::new("urn:adk:agent:caller").unwrap(),
2009 "secret",
2010 adk_core::resource_indicator(audience).unwrap(),
2011 vec![],
2012 )
2013 };
2014 let client = A2aV1Client::new(make_test_card())
2015 .with_credential(token("http://localhost:9999/a2a"));
2016 let headers = client.headers_for("http://localhost:9999/a2a").unwrap();
2017 assert_eq!(headers.get(reqwest::header::AUTHORIZATION).unwrap(), "Bearer secret");
2018 assert_eq!(headers.get(A2A_VERSION_HEADER).unwrap(), A2A_VERSION);
2019
2020 match client.headers_for("http://localhost:9999/rest/tasks") {
2021 Err(V1ClientError::Credential(error)) => {
2022 assert_eq!(error.code, "credential.audience_mismatch");
2023 }
2024 other => panic!("expected a refused credential, got {other:?}"),
2025 }
2026 let anonymous = A2aV1Client::new(make_test_card());
2027 let headers = anonymous.headers_for("http://localhost:9999/rest").unwrap();
2028 assert!(headers.get(reqwest::header::AUTHORIZATION).is_none());
2029 }
2030 }
2031}