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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
use crate::a2a::{
AgentCard, JsonRpcRequest, JsonRpcResponse, Message, MessageSendParams,
TaskArtifactUpdateEvent, TaskStatusUpdateEvent, UpdateEvent,
};
use adk_core::Result;
use futures::stream::Stream;
use serde_json::Value;
use std::pin::Pin;
/// A2A client for communicating with remote A2A agents
pub struct A2aClient {
http_client: reqwest::Client,
agent_card: AgentCard,
credential: Option<adk_core::ScopedToken>,
}
/// Attaches `token` as a bearer credential to a request for `url`, after checking the
/// URL is inside the token's audience.
fn bearer(
request: reqwest::RequestBuilder,
token: Option<&adk_core::ScopedToken>,
url: &str,
) -> Result<reqwest::RequestBuilder> {
let Some(token) = token else {
return Ok(request);
};
let target = adk_core::Url::parse(url)
.map_err(|error| adk_core::AdkError::agent(format!("invalid A2A endpoint URL: {error}")))?;
Ok(request.bearer_auth(token.authorize_for(&target)?.expose()))
}
/// Whether `url` names this host: `localhost`, `127.0.0.1`, or `::1`.
fn is_loopback(url: &adk_core::Url) -> bool {
// `host_str` is normalized: lowercase, IPv4 dotted, IPv6 bracketed and compressed.
matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "[::1]"))
}
/// `url`'s origin, with every loopback name written as `localhost`.
fn comparable_origin(url: &adk_core::Url) -> String {
let host = if is_loopback(url) {
"localhost".to_string()
} else {
url.host_str().unwrap_or_default().to_string()
};
format!("{}://{host}:{}", url.scheme(), url.port_or_known_default().unwrap_or_default())
}
/// Checks that `endpoint`, the RPC URL named by the agent card fetched from `card_url`,
/// may receive messages.
///
/// The endpoint must share the card's origin, with `localhost`, `127.0.0.1`, and `::1`
/// counted as one host, or have an origin listed in `allowed_origins`. An allowed endpoint
/// on another origin must use `https` unless its host is loopback. Without this check a
/// card could send every message, and any credential sent with it, to a host of its
/// choosing.
///
/// # Example
///
/// ```rust
/// use adk_server::a2a::client::check_card_endpoint;
///
/// let card = "https://agents.example.com/.well-known/agent-card.json";
/// assert!(check_card_endpoint(card, "https://agents.example.com/a2a", &[]).is_ok());
/// assert!(check_card_endpoint(card, "https://collector.example.net/a2a", &[]).is_err());
///
/// let allowed = vec!["https://rpc.example.com".to_string()];
/// assert!(check_card_endpoint(card, "https://rpc.example.com/a2a", &allowed).is_ok());
/// ```
///
/// # Errors
///
/// Returns `a2a.card_endpoint_refused` when the endpoint may not receive messages, and an
/// invalid-input error when either URL does not parse.
pub fn check_card_endpoint(
card_url: &str,
endpoint: &str,
allowed_origins: &[String],
) -> Result<()> {
let parse = |url: &str, what: &str| {
adk_core::Url::parse(url).map_err(|error| {
adk_core::AdkError::new(
adk_core::ErrorComponent::Server,
adk_core::ErrorCategory::InvalidInput,
"a2a.card_endpoint_invalid",
format!("invalid A2A {what} URL: {error}"),
)
})
};
let card = parse(card_url, "agent card")?;
let target = parse(endpoint, "endpoint")?;
let target_origin = comparable_origin(&target);
if target_origin == comparable_origin(&card) {
return Ok(());
}
let refused = |reason: String| {
Err(adk_core::AdkError::new(
adk_core::ErrorComponent::Server,
adk_core::ErrorCategory::Forbidden,
"a2a.card_endpoint_refused",
reason,
))
};
let listed = allowed_origins.iter().any(|origin| {
adk_core::Url::parse(origin).is_ok_and(|origin| comparable_origin(&origin) == target_origin)
});
if !listed {
return refused(format!(
"the agent card from {} names an endpoint on {}; messages are sent only to the \
card's origin unless the endpoint's origin is allowed explicitly",
card.origin().ascii_serialization(),
target.origin().ascii_serialization(),
));
}
if target.scheme() != "https" && !is_loopback(&target) {
return refused(format!(
"the agent card endpoint on {} must use https",
target.origin().ascii_serialization()
));
}
Ok(())
}
impl A2aClient {
/// Create a new A2A client from an agent card.
///
/// The card is trusted as given: its endpoint is not checked. Resolve cards from a
/// URL with [`resolve_agent_card`](Self::resolve_agent_card) or
/// [`from_url`](Self::from_url), which check it.
pub fn new(agent_card: AgentCard) -> Self {
Self { http_client: reqwest::Client::new(), agent_card, credential: None }
}
/// Sends `token` as a bearer credential on every message request.
///
/// A request goes out only when its URL is inside the token's audience
/// ([`ScopedToken::authorize_for`](adk_core::ScopedToken::authorize_for)); a request
/// to any other URL fails with `credential.audience_mismatch` and is not sent.
/// Agent card discovery stays unauthenticated.
pub fn with_credential(mut self, token: adk_core::ScopedToken) -> Self {
self.credential = Some(token);
self
}
/// Resolves an agent card from a base URL.
///
/// Fetches `/.well-known/agent-card.json`, the path A2A 0.3.0 and later define. Falls
/// back to `/.well-known/agent.json` when that path returns 404, so servers that
/// predate A2A 0.3.0 still resolve. It also falls back when that path holds a card
/// that is not a 0.3 card, such as the v1 card a server that speaks both versions
/// serves there; adk-server's [`with_a2a`](crate::ServerBuilder::with_a2a) keeps its
/// 0.3 card at `agent.json`.
///
/// The card's endpoint must be on `base_url`'s origin; see [`check_card_endpoint`].
///
/// # Errors
///
/// Returns an error when the request fails, when a card path answers with a
/// non-success status other than the 404 that triggers the fallback, when neither
/// path holds a 0.3 agent card, or when the card names an endpoint on another origin
/// (`a2a.card_endpoint_refused`).
pub async fn resolve_agent_card(base_url: &str) -> Result<AgentCard> {
Self::resolve_agent_card_allowing(base_url, &[]).await
}
/// Resolves an agent card from a base URL, accepting an endpoint on any origin in
/// `allowed_origins` as well as on `base_url`'s own; see [`check_card_endpoint`].
///
/// # Example
///
/// ```rust,ignore
/// let card = A2aClient::resolve_agent_card_allowing(
/// "https://agents.example.com",
/// &["https://rpc.example.com".to_string()],
/// )
/// .await?;
/// ```
///
/// # Errors
///
/// See [`resolve_agent_card`](Self::resolve_agent_card).
pub async fn resolve_agent_card_allowing(
base_url: &str,
allowed_origins: &[String],
) -> Result<AgentCard> {
let base_url = base_url.trim_end_matches('/');
let client = reqwest::Client::new();
let fetch = |path: &'static str| client.get(format!("{base_url}{path}")).send();
let fetch_error = |e: reqwest::Error| {
adk_core::AdkError::agent(format!("Failed to fetch agent card: {e}"))
};
// `None` when the path does not exist; otherwise the body, if it is a 0.3 card.
let read = |response: reqwest::Response| async move {
if response.status() == reqwest::StatusCode::NOT_FOUND {
return Ok(None);
}
if !response.status().is_success() {
return Err(adk_core::AdkError::agent(format!(
"Failed to fetch agent card: HTTP {}",
response.status()
)));
}
let body = response.bytes().await.map_err(fetch_error)?;
Ok(Some(serde_json::from_slice::<AgentCard>(&body)))
};
let current =
read(fetch("/.well-known/agent-card.json").await.map_err(fetch_error)?).await?;
let card = match current {
Some(Ok(card)) => card,
not_a_0_3_card => {
match read(fetch("/.well-known/agent.json").await.map_err(fetch_error)?).await? {
Some(Ok(card)) => card,
Some(Err(e)) => {
return Err(adk_core::AdkError::agent(format!(
"Failed to parse agent card: {e}"
)));
}
None => {
return Err(adk_core::AdkError::agent(match not_a_0_3_card {
Some(Err(e)) => format!("Failed to parse agent card: {e}"),
_ => "Failed to fetch agent card: HTTP 404 Not Found".to_string(),
}));
}
}
}
};
check_card_endpoint(base_url, &card.url, allowed_origins)?;
Ok(card)
}
/// Create a client by resolving an agent card from a URL; see
/// [`resolve_agent_card`](Self::resolve_agent_card).
pub async fn from_url(base_url: &str) -> Result<Self> {
let card = Self::resolve_agent_card(base_url).await?;
Ok(Self::new(card))
}
/// Get the agent card
pub fn agent_card(&self) -> &AgentCard {
&self.agent_card
}
/// Send a message to the remote agent (blocking/non-streaming)
pub async fn send_message(&self, message: Message) -> Result<JsonRpcResponse> {
let request = JsonRpcRequest {
jsonrpc: "2.0".to_string(),
method: "message/send".to_string(),
params: Some(
serde_json::to_value(MessageSendParams { message, config: None })
.map_err(|e| adk_core::AdkError::agent(e.to_string()))?,
),
id: Some(Value::String(uuid::Uuid::new_v4().to_string())),
};
let post = self.http_client.post(&self.agent_card.url);
let response = bearer(post, self.credential.as_ref(), &self.agent_card.url)?
.json(&request)
.send()
.await
.map_err(|e| adk_core::AdkError::agent(format!("Request failed: {e}")))?;
if !response.status().is_success() {
return Err(adk_core::AdkError::agent(format!(
"Request failed: HTTP {}",
response.status()
)));
}
let rpc_response: JsonRpcResponse = response
.json()
.await
.map_err(|e| adk_core::AdkError::agent(format!("Failed to parse response: {e}")))?;
Ok(rpc_response)
}
/// Send a message and receive streaming events via SSE
pub async fn send_streaming_message(
&self,
message: Message,
) -> Result<Pin<Box<dyn Stream<Item = Result<UpdateEvent>> + Send>>> {
let stream_url = format!("{}/stream", self.agent_card.url.trim_end_matches('/'));
let request = JsonRpcRequest {
jsonrpc: "2.0".to_string(),
method: "message/stream".to_string(),
params: Some(
serde_json::to_value(MessageSendParams { message, config: None })
.map_err(|e| adk_core::AdkError::agent(e.to_string()))?,
),
id: Some(Value::String(uuid::Uuid::new_v4().to_string())),
};
let post = self.http_client.post(&stream_url);
let response = bearer(post, self.credential.as_ref(), &stream_url)?
.json(&request)
.send()
.await
.map_err(|e| adk_core::AdkError::agent(format!("Request failed: {e}")))?;
if !response.status().is_success() {
return Err(adk_core::AdkError::agent(format!(
"Request failed: HTTP {}",
response.status()
)));
}
// An event can end on any read, so bytes are decoded only once a whole SSE line has
// arrived; a stream that stops before a final status is reported, not completed.
let stream = async_stream::stream! {
use futures::StreamExt;
let mut bytes_stream = response.bytes_stream();
let mut decoder = SseDecoder::default();
let mut finished = false;
while let Some(chunk_result) = bytes_stream.next().await {
let chunk = match chunk_result {
Ok(c) => c,
Err(e) => {
yield Err(adk_core::AdkError::agent(format!("Stream error: {e}")));
return;
}
};
let payloads = match decoder.push(&chunk) {
Ok(payloads) => payloads,
Err(e) => {
yield Err(e);
return;
}
};
for data in payloads {
// The server's closing `done` event carries no data.
if data.trim().is_empty() {
continue;
}
match serde_json::from_str::<JsonRpcResponse>(&data) {
Ok(rpc_response) => {
if let Some(result) = rpc_response.result {
if let Ok(status_event) = serde_json::from_value::<TaskStatusUpdateEvent>(result.clone()) {
finished |= ends_task(&status_event);
yield Ok(UpdateEvent::TaskStatusUpdate(status_event));
} else if let Ok(artifact_event) = serde_json::from_value::<TaskArtifactUpdateEvent>(result) {
yield Ok(UpdateEvent::TaskArtifactUpdate(artifact_event));
}
} else if let Some(error) = rpc_response.error {
yield Err(adk_core::AdkError::agent(format!(
"RPC error: {} ({})",
error.message, error.code
)));
return;
}
}
Err(e) => {
// Skip parse errors for non-JSON data
tracing::debug!("Failed to parse SSE data: {e}");
}
}
}
}
if !finished {
yield Err(truncated_stream_error());
}
};
Ok(Box::pin(stream))
}
}
/// Whether `update` is the last status of its task's stream: a final update, or a state
/// the task stops in.
fn ends_task(update: &TaskStatusUpdateEvent) -> bool {
use crate::a2a::TaskState;
update.final_update
|| match update.status.state {
TaskState::Completed
| TaskState::Failed
| TaskState::Canceled
| TaskState::InputRequired
| TaskState::AuthRequired => true,
TaskState::Submitted | TaskState::Working => false,
}
}
/// The error for a stream that ended before its task reached a final status.
pub(crate) fn truncated_stream_error() -> adk_core::AdkError {
adk_core::AdkError::agent(
"the A2A stream ended before the task reached a final status; the response is incomplete",
)
}
/// Splits an SSE byte stream into the data of each event.
///
/// Bytes are buffered until a whole line has arrived, so a multi-byte character split
/// across reads is decoded intact. Lines end in `\n`, `\r\n` or a lone `\r`, as the SSE
/// specification allows; an event's `data:` lines are joined with `\n`; other fields and
/// comments are ignored.
#[derive(Default)]
pub(crate) struct SseDecoder {
buffer: Vec<u8>,
data: Vec<String>,
}
impl SseDecoder {
/// Feeds `chunk` and returns the data of every event it completes.
///
/// # Errors
///
/// Returns an error when a complete line is not valid UTF-8.
pub(crate) fn push(&mut self, chunk: &[u8]) -> Result<Vec<String>> {
self.buffer.extend_from_slice(chunk);
let mut events = Vec::new();
while let Some(end) = self.buffer.iter().position(|&byte| byte == b'\n' || byte == b'\r') {
// A line ends in LF, CRLF or a lone CR. A CR that ends the buffer may start a CRLF
// whose LF has not arrived yet.
let consumed = match (self.buffer[end], self.buffer.get(end + 1)) {
(b'\r', Some(b'\n')) => end + 2,
(b'\r', None) => break,
_ => end + 1,
};
let line: Vec<u8> = self.buffer.drain(..consumed).collect();
let line = std::str::from_utf8(&line[..end]).map_err(|error| {
adk_core::AdkError::agent(format!("the A2A stream is not valid UTF-8: {error}"))
})?;
if line.is_empty() {
if !self.data.is_empty() {
events.push(self.data.join("\n"));
self.data.clear();
}
} else if let Some(value) = line.strip_prefix("data:") {
self.data.push(value.strip_prefix(' ').unwrap_or(value).to_string());
}
}
Ok(events)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sse_lines_may_end_in_a_lone_cr_even_across_reads() {
let mut decoder = SseDecoder::default();
// Lone CRs end lines; the blank line ends the event.
assert_eq!(
decoder.push(b"data: a\rdata: b\r\r:comment").unwrap(),
vec!["a\nb".to_string()]
);
// A CR that ends one read may be the start of a CRLF, so it waits for the next byte.
assert!(decoder.push(b"\rdata: c\r").unwrap().is_empty());
assert!(decoder.push(b"\n").unwrap().is_empty());
assert_eq!(decoder.push(b"\r\n").unwrap(), vec!["c".to_string()]);
}
#[test]
fn a_card_endpoint_on_the_card_origin_is_accepted() {
let card = "https://agents.example.com/.well-known/agent-card.json";
assert!(check_card_endpoint(card, "https://agents.example.com/a2a", &[]).is_ok());
assert!(check_card_endpoint(card, "https://AGENTS.example.com:443/rpc", &[]).is_ok());
// Loopback names are one host.
let local = "http://127.0.0.1:8080/.well-known/agent-card.json";
assert!(check_card_endpoint(local, "http://localhost:8080/a2a", &[]).is_ok());
assert!(check_card_endpoint(local, "http://[::1]:8080/a2a", &[]).is_ok());
}
#[test]
fn a_card_endpoint_on_another_origin_is_refused() {
let card = "https://agents.example.com/.well-known/agent-card.json";
for endpoint in [
"https://collector.example.net/a2a",
"http://agents.example.com/a2a",
"https://agents.example.com:8443/a2a",
"http://169.254.169.254/latest",
"http://localhost:8080/a2a",
] {
let error = check_card_endpoint(card, endpoint, &[]).unwrap_err();
assert_eq!(error.code, "a2a.card_endpoint_refused", "{endpoint}");
}
let local = "http://127.0.0.1:8080/.well-known/agent-card.json";
assert!(check_card_endpoint(local, "http://127.0.0.1:9090/a2a", &[]).is_err());
}
#[test]
fn an_allowed_origin_must_use_https_unless_loopback() {
let card = "https://agents.example.com/.well-known/agent-card.json";
let allowed = vec![
"https://rpc.example.com".to_string(),
"http://plain.example.com".to_string(),
"http://localhost:9090".to_string(),
];
assert!(check_card_endpoint(card, "https://rpc.example.com/a2a", &allowed).is_ok());
assert!(check_card_endpoint(card, "http://127.0.0.1:9090/a2a", &allowed).is_ok());
let error =
check_card_endpoint(card, "http://plain.example.com/a2a", &allowed).unwrap_err();
assert!(error.message.contains("must use https"), "{error}");
}
#[test]
fn a_refusal_names_origins_not_credentials() {
let error = check_card_endpoint(
"https://user:secret@agents.example.com/card",
"https://token:hunter2@collector.example.net/a2a?key=abc",
&[],
)
.unwrap_err();
for leaked in ["secret", "hunter2", "key=abc", "/a2a"] {
assert!(!error.message.contains(leaked), "{}", error.message);
}
}
#[test]
fn decoder_joins_data_lines_and_ignores_other_fields() {
let mut decoder = SseDecoder::default();
let events = decoder
.push(b"event: message\ndata: {\"a\":\ndata: 1}\n\n: comment\nevent: ping\n\n")
.unwrap();
assert_eq!(events, vec!["{\"a\":\n1}".to_string()]);
}
#[test]
fn decoder_keeps_a_character_split_across_reads() {
let frame = "data: Grüße ☕\r\n\r\n".as_bytes();
let split = "data: Gr".len() + 1;
let mut decoder = SseDecoder::default();
assert!(decoder.push(&frame[..split]).unwrap().is_empty());
assert_eq!(decoder.push(&frame[split..]).unwrap(), vec!["Grüße ☕".to_string()]);
}
#[test]
fn decoder_rejects_invalid_utf8() {
let mut decoder = SseDecoder::default();
assert!(decoder.push(b"data: \xff\n\n").is_err());
}
#[test]
fn only_final_or_stopping_statuses_end_a_task() {
use crate::a2a::{TaskState, TaskStatus};
let update = |state: TaskState, final_update: bool| TaskStatusUpdateEvent {
task_id: "task".to_string(),
context_id: None,
status: TaskStatus { state, message: None },
final_update,
};
assert!(!ends_task(&update(TaskState::Working, false)));
assert!(ends_task(&update(TaskState::Working, true)));
assert!(ends_task(&update(TaskState::InputRequired, false)));
assert!(ends_task(&update(TaskState::Completed, false)));
}
}
// ── A2A v1.0.0 Client ───────────────────────────────────────────────────────
#[cfg(feature = "a2a-v1")]
pub mod v1_client {
//! A2A v1.0.0 client for communicating with remote A2A agents.
//!
//! Sends the `A2A-Version: 1.0` header on all requests, supports all 11
//! v1.0.0 operations via JSON-RPC, optional REST binding, structured error
//! parsing, configurable retry, and agent card caching with conditional
//! request headers.
use a2a_protocol_types::events::StreamResponse;
use a2a_protocol_types::jsonrpc::JsonRpcRequest;
use a2a_protocol_types::params::SendMessageConfiguration;
use a2a_protocol_types::responses::{
ListPushConfigsResponse, SendMessageResponse, TaskListResponse,
};
use a2a_protocol_types::task::{Task, TaskState};
use a2a_protocol_types::{AgentCard, AgentInterface, Message, TaskPushNotificationConfig};
use reqwest::header::{HeaderMap, HeaderValue};
use serde_json::Value;
use std::time::Duration;
/// Header name for A2A protocol version negotiation.
const A2A_VERSION_HEADER: &str = "a2a-version";
/// The v1.0.0 protocol version string.
const A2A_VERSION: &str = "1.0";
/// Well-known path for v1 agent cards.
const AGENT_CARD_PATH: &str = "/.well-known/agent-card.json";
/// JSON-RPC code of `VersionNotSupportedError` (A2A §5.4).
const VERSION_NOT_SUPPORTED: i64 = -32009;
/// The card's A2A v1 interface for `binding` (`JSONRPC` or `HTTP+JSON`): the first
/// with a `1.x` protocol version, else the first that states none. An interface for an
/// earlier protocol version, such as the 0.3 endpoint a card may also list, is never
/// chosen.
pub fn v1_interface<'a>(card: &'a AgentCard, binding: &str) -> Option<&'a AgentInterface> {
let of_binding =
|| card.supported_interfaces.iter().filter(move |i| i.protocol_binding == binding);
of_binding()
.find(|i| i.protocol_version.split('.').next() == Some("1"))
.or_else(|| of_binding().find(|i| i.protocol_version.trim().is_empty()))
}
/// Reads a `SendMessage` result: the v1 `SendMessageResponse` oneof
/// (`{"task": …}` or `{"message": …}`, A2A §9.4.1 and §11.4), or a bare
/// `Task`, which adk-server before 3.0 returned.
///
/// # Errors
///
/// Returns the oneof's decoding error when `result` is neither shape.
fn parse_send_message_result(result: Value) -> Result<SendMessageResponse, serde_json::Error> {
serde_json::from_value::<SendMessageResponse>(result.clone()).or_else(|oneof_error| {
serde_json::from_value::<Task>(result)
.map(SendMessageResponse::Task)
.map_err(|_| oneof_error)
})
}
/// The updates of a streamed message or a task subscription, as they arrive.
pub type UpdateStream =
futures::stream::BoxStream<'static, Result<StreamResponse, V1ClientError>>;
/// Reads one SSE payload: a `StreamResponse`, bare (HTTP+JSON binding) or as a JSON-RPC
/// result, or a JSON-RPC error. `None` when it is neither, or empty.
pub(crate) fn parse_stream_payload(
data: &str,
) -> Option<Result<StreamResponse, V1ClientError>> {
if data.trim().is_empty() {
return None;
}
if let Ok(update) = serde_json::from_str::<StreamResponse>(data) {
return Some(Ok(update));
}
let value = serde_json::from_str::<Value>(data).ok()?;
if let Some(result) = value.get("result")
&& let Ok(update) = serde_json::from_value::<StreamResponse>(result.clone())
{
return Some(Ok(update));
}
let error = value.get("error")?;
Some(Err(V1ClientError::JsonRpc {
code: error.get("code").and_then(Value::as_i64).unwrap_or(0) as i32,
message: error
.get("message")
.and_then(Value::as_str)
.unwrap_or("unknown error")
.to_string(),
data: error.get("data").cloned(),
}))
}
/// Reads a `ListTasks` result: the v1 `ListTasksResponse` (A2A §3.1.4), or the bare
/// task array adk-server before 3.0 returned, read as one complete page.
///
/// # Errors
///
/// Returns the response's decoding error when `result` is neither shape.
fn parse_task_list(result: Value) -> Result<TaskListResponse, serde_json::Error> {
if result.is_array() {
let tasks: Vec<Task> = serde_json::from_value(result)?;
let count = u32::try_from(tasks.len()).unwrap_or(u32::MAX);
return Ok(TaskListResponse {
tasks,
next_page_token: String::new(),
page_size: count,
total_size: count,
});
}
serde_json::from_value(result)
}
/// Reads a `ListTaskPushNotificationConfigs` result: the v1 `{configs, nextPageToken}`
/// object, or the bare array adk-server before 3.0 returned.
///
/// # Errors
///
/// Returns the decoding error when `result` is neither shape.
fn parse_push_config_list(
result: Value,
) -> Result<Vec<TaskPushNotificationConfig>, serde_json::Error> {
if result.is_array() {
return serde_json::from_value(result);
}
serde_json::from_value::<ListPushConfigsResponse>(result).map(|page| page.configs)
}
/// Retry configuration for transient failures.
#[derive(Debug, Clone)]
pub struct RetryConfig {
/// Maximum number of retry attempts (0 = no retries).
pub max_retries: u32,
/// Base delay between retries (doubles each attempt).
pub base_delay: Duration,
}
impl Default for RetryConfig {
fn default() -> Self {
Self { max_retries: 3, base_delay: Duration::from_secs(1) }
}
}
/// Error returned by the v1 client.
#[derive(Debug, thiserror::Error)]
pub enum V1ClientError {
/// HTTP transport error.
#[error("HTTP error: {0}")]
Http(#[from] reqwest::Error),
/// JSON-RPC error returned by the server.
#[error("JSON-RPC error {code}: {message}")]
JsonRpc { code: i32, message: String, data: Option<Value> },
/// Version negotiation failed — server does not support requested version.
#[error("version not supported: requested {requested}, server supports: {supported:?}")]
VersionNotSupported { requested: String, supported: Vec<String> },
/// Serialization/deserialization error.
#[error("serialization error: {0}")]
Serde(#[from] serde_json::Error),
/// The client's credential may not be sent to the request URL, or the URL is
/// invalid. The request was not sent.
#[error("credential refused: {0}")]
Credential(#[from] adk_core::AdkError),
/// The server returned an unexpected HTTP status.
#[error("unexpected HTTP status {status}: {body}")]
UnexpectedStatus { status: u16, body: String },
/// The resolved agent card names an endpoint on an origin it may not; see
/// [`check_card_endpoint`](super::check_card_endpoint).
#[error("agent card refused: {0}")]
CardEndpoint(adk_core::AdkError),
}
/// Checks every interface this client calls (`JSONRPC`, `HTTP+JSON`) against the
/// origin the card was fetched from.
fn check_interfaces(
card_url: &str,
card: &AgentCard,
allowed_origins: &[String],
) -> Result<(), V1ClientError> {
card.supported_interfaces
.iter()
.filter(|interface| {
matches!(interface.protocol_binding.as_str(), "JSONRPC" | "HTTP+JSON")
})
.try_for_each(|interface| {
super::check_card_endpoint(card_url, &interface.url, allowed_origins)
})
.map_err(V1ClientError::CardEndpoint)
}
/// Cached agent card with ETag and Last-Modified for conditional requests.
#[derive(Debug, Clone, Default)]
struct CachedCard {
card: Option<AgentCard>,
etag: Option<String>,
last_modified: Option<String>,
}
/// A2A v1.0.0 client.
///
/// Sends `A2A-Version: 1.0` on every request, supports all 11 operations
/// via JSON-RPC (and optionally REST), parses structured error responses,
/// caches agent cards with conditional headers, and retries transient
/// failures.
/// How long a card fetch may take, as adk-go's card resolver allows.
const CARD_FETCH_TIMEOUT: Duration = Duration::from_secs(30);
/// Where an agent card comes from.
enum CardSource {
Url(String),
File(std::path::PathBuf),
}
/// Reads a card source as adk-go's card provider does: an `http(s)` URL whose path ends
/// in `.json` is the card's own URL; any other URL is the agent's base, under which the
/// card is at `/.well-known/agent-card.json`; a path (or `file://` URL) is a card file.
/// Any other scheme is refused.
fn card_source(source: &str) -> Result<CardSource, V1ClientError> {
let unsupported = || V1ClientError::UnexpectedStatus {
status: 0,
body: format!(
"unsupported agent card source {source:?}: use an http(s) URL or a file path"
),
};
match source.split_once("://") {
None => Ok(CardSource::File(std::path::PathBuf::from(source))),
Some(("file", path)) => Ok(CardSource::File(std::path::PathBuf::from(path))),
Some((scheme, _))
if scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https") =>
{
let url = adk_core::Url::parse(source).map_err(|_| unsupported())?;
if url.path().ends_with(".json") {
Ok(CardSource::Url(source.to_string()))
} else {
Ok(CardSource::Url(format!(
"{}{AGENT_CARD_PATH}",
source.trim_end_matches('/')
)))
}
}
Some(_) => Err(unsupported()),
}
}
pub struct A2aV1Client {
http_client: reqwest::Client,
agent_card: AgentCard,
retry_config: RetryConfig,
cached_card: std::sync::Mutex<CachedCard>,
credential: Option<adk_core::ScopedToken>,
}
impl A2aV1Client {
/// Creates a new v1 client from an already-resolved agent card.
pub fn new(agent_card: AgentCard) -> Self {
Self {
http_client: reqwest::Client::new(),
agent_card,
retry_config: RetryConfig::default(),
cached_card: std::sync::Mutex::new(CachedCard::default()),
credential: None,
}
}
/// Creates a new v1 client with custom retry configuration.
pub fn with_retry(agent_card: AgentCard, retry_config: RetryConfig) -> Self {
Self {
http_client: reqwest::Client::new(),
agent_card,
retry_config,
cached_card: std::sync::Mutex::new(CachedCard::default()),
credential: None,
}
}
/// Sends `token` as a bearer credential on every operation request.
///
/// A request goes out only when its URL is inside the token's audience
/// ([`ScopedToken::authorize_for`](adk_core::ScopedToken::authorize_for)); a
/// request to any other URL fails with [`V1ClientError::Credential`] and is not
/// sent. Agent card discovery stays unauthenticated.
pub fn with_credential(mut self, token: adk_core::ScopedToken) -> Self {
self.credential = Some(token);
self
}
/// The default headers plus, when a credential is set, its bearer value for a
/// request to `url`.
fn headers_for(&self, url: &str) -> Result<HeaderMap, V1ClientError> {
let mut headers = Self::default_headers();
if let Some(token) = &self.credential {
let target = adk_core::Url::parse(url).map_err(|error| {
adk_core::AdkError::agent(format!("invalid A2A endpoint URL: {error}"))
})?;
let secret = token.authorize_for(&target)?;
let mut value = HeaderValue::from_str(&format!("Bearer {}", secret.expose()))
.map_err(|_| {
adk_core::AdkError::agent("the brokered token is not a valid header value")
})?;
value.set_sensitive(true);
headers.insert(reqwest::header::AUTHORIZATION, value);
}
Ok(headers)
}
/// Returns a reference to the agent card.
pub fn agent_card(&self) -> &AgentCard {
&self.agent_card
}
/// Returns the JSON-RPC endpoint URL from the agent card's
/// `supportedInterfaces`; see [`v1_interface`].
fn jsonrpc_url(&self) -> Option<&str> {
v1_interface(&self.agent_card, "JSONRPC").map(|i| i.url.as_str())
}
/// Returns the REST endpoint URL from the agent card's
/// `supportedInterfaces`, if available; see [`v1_interface`].
fn rest_url(&self) -> Option<&str> {
v1_interface(&self.agent_card, "HTTP+JSON").map(|i| i.url.as_str())
}
/// Builds default headers including `A2A-Version: 1.0`.
fn default_headers() -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert(A2A_VERSION_HEADER, HeaderValue::from_static(A2A_VERSION));
headers
}
// ── Agent card resolution ────────────────────────────────────────
/// Resolves an agent card from a base URL, fetching from
/// `/.well-known/agent-card.json` with `A2A-Version: 1.0`.
///
/// The card's JSON-RPC and HTTP+JSON interfaces must be on `base_url`'s origin;
/// see [`check_card_endpoint`](super::check_card_endpoint).
///
/// # Errors
///
/// Returns [`V1ClientError::CardEndpoint`] when an interface names another
/// origin, and the transport or status error when the card cannot be fetched.
pub async fn resolve_agent_card(base_url: &str) -> Result<AgentCard, V1ClientError> {
Self::resolve_agent_card_allowing(base_url, &[]).await
}
/// Resolves an agent card from a base URL, accepting interfaces on any origin in
/// `allowed_origins` as well as on `base_url`'s own.
///
/// # Errors
///
/// See [`resolve_agent_card`](Self::resolve_agent_card).
pub async fn resolve_agent_card_allowing(
base_url: &str,
allowed_origins: &[String],
) -> Result<AgentCard, V1ClientError> {
let url = match card_source(base_url)? {
CardSource::File(path) => {
let json =
std::fs::read(&path).map_err(|error| V1ClientError::UnexpectedStatus {
status: 0,
body: format!(
"cannot read the agent card file {}: {error}",
path.display()
),
})?;
return Ok(serde_json::from_slice(&json)?);
}
CardSource::Url(url) => url,
};
let client = reqwest::Client::builder()
.timeout(CARD_FETCH_TIMEOUT)
.build()
.map_err(V1ClientError::from)?;
let response = client.get(&url).headers(Self::default_headers()).send().await?;
if !response.status().is_success() {
let status = response.status().as_u16();
let body = response.text().await.unwrap_or_default();
return Err(V1ClientError::UnexpectedStatus { status, body });
}
let card: AgentCard = response.json().await?;
check_interfaces(&url, &card, allowed_origins)?;
Ok(card)
}
/// Resolves an agent card using conditional headers if a cached
/// version exists. Returns `None` if the server responds 304.
///
/// The card's interfaces must be on `base_url`'s origin, as for
/// [`resolve_agent_card`](Self::resolve_agent_card).
pub async fn resolve_agent_card_cached(
&self,
base_url: &str,
) -> Result<Option<AgentCard>, V1ClientError> {
let url = format!("{}{AGENT_CARD_PATH}", base_url.trim_end_matches('/'));
let mut req = self.http_client.get(&url).headers(Self::default_headers());
// Add conditional headers from cache
{
let cache = self.cached_card.lock().unwrap();
if let Some(etag) = &cache.etag {
req = req.header("If-None-Match", etag.as_str());
}
if let Some(lm) = &cache.last_modified {
req = req.header("If-Modified-Since", lm.as_str());
}
}
let response = req.send().await?;
if response.status() == reqwest::StatusCode::NOT_MODIFIED {
return Ok(None);
}
if !response.status().is_success() {
let status = response.status().as_u16();
let body = response.text().await.unwrap_or_default();
return Err(V1ClientError::UnexpectedStatus { status, body });
}
// Cache ETag and Last-Modified from response
let etag =
response.headers().get("etag").and_then(|v| v.to_str().ok()).map(String::from);
let last_modified = response
.headers()
.get("last-modified")
.and_then(|v| v.to_str().ok())
.map(String::from);
let card: AgentCard = response.json().await?;
check_interfaces(&url, &card, &[])?;
{
let mut cache = self.cached_card.lock().unwrap();
cache.card = Some(card.clone());
cache.etag = etag;
cache.last_modified = last_modified;
}
Ok(Some(card))
}
// ── JSON-RPC transport ───────────────────────────────────────────
/// Sends a JSON-RPC request and returns the parsed result.
async fn jsonrpc_call<T: serde::de::DeserializeOwned>(
&self,
method: &str,
params: Value,
) -> Result<T, V1ClientError> {
let url = self.jsonrpc_url().ok_or_else(|| V1ClientError::UnexpectedStatus {
status: 0,
body: "no JSONRPC interface in agent card".to_string(),
})?;
let request = JsonRpcRequest::with_params(
serde_json::json!(uuid::Uuid::new_v4().to_string()),
method,
params,
);
let response = self.send_with_retry(url, &request).await?;
let body: Value = response.json().await?;
// A JSON-RPC error. A version negotiation failure (-32009) arrives as HTTP 200 from
// a conformant server, and as HTTP 400 from adk-server before 3.0, so the code
// decides, not the status.
if let Some(err) = body.get("error") {
if err.get("code").and_then(Value::as_i64) == Some(VERSION_NOT_SUPPORTED) {
return Err(Self::parse_version_error(err));
}
return Err(Self::parse_jsonrpc_error(&body));
}
// Extract result
let result = body.get("result").cloned().unwrap_or(Value::Null);
let parsed: T = serde_json::from_value(result)?;
Ok(parsed)
}
/// Sends an HTTP request with retry logic for transient failures.
async fn send_with_retry(
&self,
url: &str,
request: &JsonRpcRequest,
) -> Result<reqwest::Response, V1ClientError> {
let mut last_err = None;
for attempt in 0..=self.retry_config.max_retries {
if attempt > 0 {
let delay = self.retry_config.base_delay * 2u32.pow(attempt - 1);
tokio::time::sleep(delay).await;
}
match self
.http_client
.post(url)
.headers(self.headers_for(url)?)
.json(request)
.send()
.await
{
Ok(resp) => {
let status = resp.status().as_u16();
// Retry on 429 and 5xx
if (status == 429 || status >= 500)
&& attempt < self.retry_config.max_retries
{
last_err = Some(V1ClientError::UnexpectedStatus {
status,
body: format!("retryable status on attempt {attempt}"),
});
continue;
}
return Ok(resp);
}
Err(e) => {
if attempt < self.retry_config.max_retries && e.is_timeout() {
last_err = Some(V1ClientError::Http(e));
continue;
}
return Err(V1ClientError::Http(e));
}
}
}
Err(last_err.unwrap_or_else(|| V1ClientError::UnexpectedStatus {
status: 0,
body: "retry exhausted".to_string(),
}))
}
// ── REST transport ───────────────────────────────────────────────
/// Sends a REST request (POST with JSON body) and returns the parsed
/// result. Falls back to JSON-RPC if no REST interface is available.
async fn rest_post<T: serde::de::DeserializeOwned>(
&self,
path: &str,
body: &Value,
) -> Result<T, V1ClientError> {
let base = match self.rest_url() {
Some(url) => url.to_string(),
None => {
return Err(V1ClientError::UnexpectedStatus {
status: 0,
body: "no HTTP+JSON interface in agent card".to_string(),
});
}
};
let url = format!("{}{path}", base.trim_end_matches('/'));
let response = self
.http_client
.post(&url)
.headers(self.headers_for(&url)?)
.header("content-type", "application/a2a+json")
.json(body)
.send()
.await?;
if !response.status().is_success() {
let status = response.status().as_u16();
let body_text = response.text().await.unwrap_or_default();
return Err(V1ClientError::UnexpectedStatus { status, body: body_text });
}
let result: T = response.json().await?;
Ok(result)
}
/// Sends a REST GET request and returns the parsed result.
async fn rest_get<T: serde::de::DeserializeOwned>(
&self,
path: &str,
) -> Result<T, V1ClientError> {
let base = match self.rest_url() {
Some(url) => url.to_string(),
None => {
return Err(V1ClientError::UnexpectedStatus {
status: 0,
body: "no HTTP+JSON interface in agent card".to_string(),
});
}
};
let url = format!("{}{path}", base.trim_end_matches('/'));
let response =
self.http_client.get(&url).headers(self.headers_for(&url)?).send().await?;
if !response.status().is_success() {
let status = response.status().as_u16();
let body_text = response.text().await.unwrap_or_default();
return Err(V1ClientError::UnexpectedStatus { status, body: body_text });
}
let result: T = response.json().await?;
Ok(result)
}
/// Sends a REST DELETE request.
async fn rest_delete(&self, path: &str) -> Result<(), V1ClientError> {
let base = match self.rest_url() {
Some(url) => url.to_string(),
None => {
return Err(V1ClientError::UnexpectedStatus {
status: 0,
body: "no HTTP+JSON interface in agent card".to_string(),
});
}
};
let url = format!("{}{path}", base.trim_end_matches('/'));
let response =
self.http_client.delete(&url).headers(self.headers_for(&url)?).send().await?;
if !response.status().is_success() {
let status = response.status().as_u16();
let body_text = response.text().await.unwrap_or_default();
return Err(V1ClientError::UnexpectedStatus { status, body: body_text });
}
Ok(())
}
// ── Error parsing ────────────────────────────────────────────────
/// Parses a JSON-RPC error response into a `V1ClientError`.
fn parse_jsonrpc_error(body: &Value) -> V1ClientError {
let err = match body.get("error") {
Some(e) => e,
None => {
return V1ClientError::JsonRpc {
code: 0,
message: "unknown error".to_string(),
data: Some(body.clone()),
};
}
};
let code = err.get("code").and_then(|c| c.as_i64()).unwrap_or(0) as i32;
let message =
err.get("message").and_then(|m| m.as_str()).unwrap_or("unknown error").to_string();
let data = err.get("data").cloned();
V1ClientError::JsonRpc { code, message, data }
}
/// Parses a version negotiation error, extracting supported versions
/// from the structured `data` field.
fn parse_version_error(err: &Value) -> V1ClientError {
let data = err.get("data");
let mut supported = Vec::new();
// Try to extract supported versions from ErrorInfo metadata
if let Some(data_arr) = data.and_then(|d| d.as_array()) {
for info in data_arr {
if let Some(meta) = info.get("metadata")
&& let Some(versions) = meta.get("supported").and_then(|v| v.as_str())
{
supported = versions.split(", ").map(String::from).collect();
}
}
}
V1ClientError::VersionNotSupported { requested: A2A_VERSION.to_string(), supported }
}
// ── 11 v1.0.0 Operations (JSON-RPC) ─────────────────────────────
/// Sends a message to the remote agent (JSON-RPC `SendMessage`).
///
/// Returns the v1 `SendMessageResponse`: the task the message created or
/// continued, or a message the agent answered with directly. A server that
/// returns a bare `Task` (adk-server before 3.0) is read as
/// [`SendMessageResponse::Task`].
///
/// # Errors
///
/// Returns [`V1ClientError::JsonRpc`] for a JSON-RPC error,
/// [`V1ClientError::VersionNotSupported`] when the server does not serve
/// A2A 1.0, and [`V1ClientError::Serde`] when the result is neither shape.
pub async fn send_message(
&self,
message: Message,
) -> Result<SendMessageResponse, V1ClientError> {
self.send_message_with(message, None).await
}
/// Sends a message with a `SendMessageConfiguration` (JSON-RPC `SendMessage`):
/// `returnImmediately`, `historyLength`, accepted output modes, or a push config.
///
/// # Errors
///
/// See [`send_message`](Self::send_message).
pub async fn send_message_with(
&self,
message: Message,
configuration: Option<&SendMessageConfiguration>,
) -> Result<SendMessageResponse, V1ClientError> {
let mut params = serde_json::json!({ "message": message });
if let Some(configuration) = configuration {
params["configuration"] = serde_json::to_value(configuration)?;
}
let result: Value = self.jsonrpc_call("SendMessage", params).await?;
Ok(parse_send_message_result(result)?)
}
/// Sends a streaming message (JSON-RPC `SendStreamingMessage`).
///
/// Returns the raw response for SSE parsing by the caller.
pub async fn send_streaming_message(
&self,
message: Message,
) -> Result<reqwest::Response, V1ClientError> {
let url = self.jsonrpc_url().ok_or_else(|| V1ClientError::UnexpectedStatus {
status: 0,
body: "no JSONRPC interface in agent card".to_string(),
})?;
let request = JsonRpcRequest::with_params(
serde_json::json!(uuid::Uuid::new_v4().to_string()),
"SendStreamingMessage",
serde_json::json!({ "message": message }),
);
let response = self
.http_client
.post(url)
.headers(self.headers_for(url)?)
.json(&request)
.send()
.await?;
Ok(response)
}
/// Retrieves a task by ID (JSON-RPC `GetTask`).
pub async fn get_task(
&self,
task_id: &str,
history_length: Option<u32>,
) -> Result<Task, V1ClientError> {
let mut params = serde_json::json!({ "id": task_id });
if let Some(len) = history_length {
params["historyLength"] = serde_json::json!(len);
}
self.jsonrpc_call("GetTask", params).await
}
/// Cancels a task (JSON-RPC `CancelTask`).
pub async fn cancel_task(&self, task_id: &str) -> Result<Task, V1ClientError> {
self.jsonrpc_call("CancelTask", serde_json::json!({ "id": task_id })).await
}
/// Lists tasks with optional filtering (JSON-RPC `ListTasks`).
pub async fn list_tasks(
&self,
context_id: Option<&str>,
status: Option<TaskState>,
page_size: Option<u32>,
page_token: Option<&str>,
) -> Result<TaskListResponse, V1ClientError> {
let mut params = serde_json::json!({});
if let Some(cid) = context_id {
params["contextId"] = serde_json::json!(cid);
}
if let Some(s) = status {
params["status"] = serde_json::to_value(s)?;
}
if let Some(ps) = page_size {
params["pageSize"] = serde_json::json!(ps);
}
if let Some(pt) = page_token {
params["pageToken"] = serde_json::json!(pt);
}
let result: Value = self.jsonrpc_call("ListTasks", params).await?;
Ok(parse_task_list(result)?)
}
/// Subscribes to task updates (JSON-RPC `SubscribeToTask`).
///
/// Returns the raw response for SSE parsing by the caller.
pub async fn subscribe_to_task(
&self,
task_id: &str,
) -> Result<reqwest::Response, V1ClientError> {
let url = self.jsonrpc_url().ok_or_else(|| V1ClientError::UnexpectedStatus {
status: 0,
body: "no JSONRPC interface in agent card".to_string(),
})?;
let request = JsonRpcRequest::with_params(
serde_json::json!(uuid::Uuid::new_v4().to_string()),
"SubscribeToTask",
serde_json::json!({ "id": task_id }),
);
let response = self
.http_client
.post(url)
.headers(self.headers_for(url)?)
.json(&request)
.send()
.await?;
Ok(response)
}
/// Sends a streaming message and returns its updates as they arrive: the task,
/// then status and artifact updates, until the task ends or stops for its caller.
///
/// Uses the JSON-RPC binding (`SendStreamingMessage`), or the HTTP+JSON binding
/// (`POST /message:stream`) when the card offers no JSON-RPC interface.
///
/// # Errors
///
/// Returns an error when the request fails or the server answers with an error
/// instead of a stream. An error the stream carries ends it as its last item.
pub async fn stream_message(
&self,
message: Message,
) -> Result<UpdateStream, V1ClientError> {
self.stream_message_with(message, None).await
}
/// Streams a message with a `SendMessageConfiguration`, as
/// [`stream_message`](Self::stream_message) does.
///
/// # Errors
///
/// See [`stream_message`](Self::stream_message).
pub async fn stream_message_with(
&self,
message: Message,
configuration: Option<&SendMessageConfiguration>,
) -> Result<UpdateStream, V1ClientError> {
let mut body = serde_json::json!({ "message": message });
if let Some(configuration) = configuration {
body["configuration"] = serde_json::to_value(configuration)?;
}
match self.jsonrpc_url() {
Some(url) => {
let request = JsonRpcRequest::with_params(
serde_json::json!(uuid::Uuid::new_v4().to_string()),
"SendStreamingMessage",
body,
);
let builder =
self.http_client.post(url).headers(self.headers_for(url)?).json(&request);
Self::open_stream(builder).await
}
None => {
let url = self.rest_endpoint("/message:stream")?;
let builder = self
.http_client
.post(&url)
.headers(self.headers_for(&url)?)
.header("content-type", "application/a2a+json")
.json(&body);
Self::open_stream(builder).await
}
}
}
/// Subscribes to a task and returns its updates as they arrive (A2A §3.1.6).
///
/// Uses the JSON-RPC binding (`SubscribeToTask`), or the HTTP+JSON binding
/// (`GET /tasks/{id}:subscribe`) when the card offers no JSON-RPC interface.
///
/// # Errors
///
/// See [`stream_message`](Self::stream_message).
pub async fn subscribe(&self, task_id: &str) -> Result<UpdateStream, V1ClientError> {
match self.jsonrpc_url() {
Some(url) => {
let request = JsonRpcRequest::with_params(
serde_json::json!(uuid::Uuid::new_v4().to_string()),
"SubscribeToTask",
serde_json::json!({ "id": task_id }),
);
let builder =
self.http_client.post(url).headers(self.headers_for(url)?).json(&request);
Self::open_stream(builder).await
}
None => {
let url = self.rest_endpoint(&format!("/tasks/{task_id}:subscribe"))?;
let builder = self.http_client.get(&url).headers(self.headers_for(&url)?);
Self::open_stream(builder).await
}
}
}
/// The full URL of `path` on the card's HTTP+JSON interface.
fn rest_endpoint(&self, path: &str) -> Result<String, V1ClientError> {
let base = self.rest_url().ok_or_else(|| V1ClientError::UnexpectedStatus {
status: 0,
body: "no JSONRPC or HTTP+JSON interface in agent card".to_string(),
})?;
Ok(format!("{}{path}", base.trim_end_matches('/')))
}
/// Sends a streaming request and reads its SSE answer as updates.
async fn open_stream(
request: reqwest::RequestBuilder,
) -> Result<UpdateStream, V1ClientError> {
use futures::StreamExt;
let response = request.send().await?;
let status = response.status().as_u16();
let is_sse = response
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.is_some_and(|value| value.starts_with("text/event-stream"));
if !is_sse {
// A JSON answer to a streaming call is an error: the method's, or the
// version negotiation's.
let body = response.text().await.unwrap_or_default();
if let Ok(value) = serde_json::from_str::<Value>(&body)
&& let Some(error) = value.get("error")
{
if error.get("code").and_then(Value::as_i64) == Some(VERSION_NOT_SUPPORTED) {
return Err(Self::parse_version_error(error));
}
if error.get("code").and_then(Value::as_i64).is_some() {
return Err(Self::parse_jsonrpc_error(&value));
}
}
return Err(V1ClientError::UnexpectedStatus { status, body });
}
let mut bytes = response.bytes_stream();
let updates = async_stream::stream! {
let mut decoder = super::SseDecoder::default();
while let Some(chunk) = bytes.next().await {
let chunk = match chunk {
Ok(chunk) => chunk,
Err(error) => {
yield Err(V1ClientError::Http(error));
return;
}
};
let payloads = match decoder.push(&chunk) {
Ok(payloads) => payloads,
Err(error) => {
yield Err(V1ClientError::UnexpectedStatus { status, body: error.to_string() });
return;
}
};
for data in payloads {
match parse_stream_payload(&data) {
Some(Ok(update)) => yield Ok(update),
Some(Err(error)) => {
yield Err(error);
return;
}
None => tracing::debug!("SSE data that is no A2A update: {data}"),
}
}
}
};
Ok(Box::pin(updates))
}
/// Creates a push notification config (JSON-RPC
/// `CreateTaskPushNotificationConfig`).
pub async fn create_push_notification_config(
&self,
config: TaskPushNotificationConfig,
) -> Result<TaskPushNotificationConfig, V1ClientError> {
self.jsonrpc_call("CreateTaskPushNotificationConfig", serde_json::to_value(&config)?)
.await
}
/// Gets a push notification config (JSON-RPC
/// `GetTaskPushNotificationConfig`).
pub async fn get_push_notification_config(
&self,
task_id: &str,
config_id: &str,
) -> Result<TaskPushNotificationConfig, V1ClientError> {
self.jsonrpc_call(
"GetTaskPushNotificationConfig",
serde_json::json!({ "taskId": task_id, "id": config_id }),
)
.await
}
/// Lists push notification configs (JSON-RPC
/// `ListTaskPushNotificationConfigs`).
pub async fn list_push_notification_configs(
&self,
task_id: &str,
) -> Result<Vec<TaskPushNotificationConfig>, V1ClientError> {
let result: Value = self
.jsonrpc_call(
"ListTaskPushNotificationConfigs",
serde_json::json!({ "taskId": task_id }),
)
.await?;
Ok(parse_push_config_list(result)?)
}
/// Deletes a push notification config (JSON-RPC
/// `DeleteTaskPushNotificationConfig`).
pub async fn delete_push_notification_config(
&self,
task_id: &str,
config_id: &str,
) -> Result<(), V1ClientError> {
let _: Value = self
.jsonrpc_call(
"DeleteTaskPushNotificationConfig",
serde_json::json!({ "taskId": task_id, "id": config_id }),
)
.await?;
Ok(())
}
/// Gets the extended agent card (JSON-RPC `GetExtendedAgentCard`).
pub async fn get_extended_agent_card(&self) -> Result<AgentCard, V1ClientError> {
self.jsonrpc_call("GetExtendedAgentCard", serde_json::json!({})).await
}
// ── REST binding operations ──────────────────────────────────────
/// Sends a message via REST (`POST /message:send`).
///
/// Returns the v1 `SendMessageResponse`, read as
/// [`send_message`](Self::send_message) reads it.
///
/// # Errors
///
/// Returns [`V1ClientError::UnexpectedStatus`] for a non-2xx answer and
/// [`V1ClientError::Serde`] when the body is neither shape.
pub async fn send_message_rest(
&self,
message: Message,
) -> Result<SendMessageResponse, V1ClientError> {
self.send_message_rest_with(message, None).await
}
/// Sends a message with a `SendMessageConfiguration` via REST, as
/// [`send_message_rest`](Self::send_message_rest) does.
///
/// # Errors
///
/// See [`send_message_rest`](Self::send_message_rest).
pub async fn send_message_rest_with(
&self,
message: Message,
configuration: Option<&SendMessageConfiguration>,
) -> Result<SendMessageResponse, V1ClientError> {
let mut request = serde_json::json!({ "message": message });
if let Some(configuration) = configuration {
request["configuration"] = serde_json::to_value(configuration)?;
}
let body: Value = self.rest_post("/message:send", &request).await?;
Ok(parse_send_message_result(body)?)
}
/// Gets a task via REST (`GET /tasks/{taskId}`).
pub async fn get_task_rest(&self, task_id: &str) -> Result<Task, V1ClientError> {
self.rest_get(&format!("/tasks/{task_id}")).await
}
/// Cancels a task via REST (`POST /tasks/{taskId}:cancel`).
pub async fn cancel_task_rest(&self, task_id: &str) -> Result<Task, V1ClientError> {
self.rest_post(&format!("/tasks/{task_id}:cancel"), &serde_json::json!({})).await
}
/// Lists tasks via REST (`GET /tasks`).
pub async fn list_tasks_rest(&self) -> Result<TaskListResponse, V1ClientError> {
let body: Value = self.rest_get("/tasks").await?;
Ok(parse_task_list(body)?)
}
/// Creates a push notification config via REST
/// (`POST /tasks/{taskId}/pushNotificationConfigs`).
pub async fn create_push_notification_config_rest(
&self,
task_id: &str,
config: TaskPushNotificationConfig,
) -> Result<TaskPushNotificationConfig, V1ClientError> {
self.rest_post(
&format!("/tasks/{task_id}/pushNotificationConfigs"),
&serde_json::to_value(&config)?,
)
.await
}
/// Gets a push notification config via REST
/// (`GET /tasks/{taskId}/pushNotificationConfigs/{configId}`).
pub async fn get_push_notification_config_rest(
&self,
task_id: &str,
config_id: &str,
) -> Result<TaskPushNotificationConfig, V1ClientError> {
self.rest_get(&format!("/tasks/{task_id}/pushNotificationConfigs/{config_id}")).await
}
/// Lists push notification configs via REST
/// (`GET /tasks/{taskId}/pushNotificationConfigs`).
pub async fn list_push_notification_configs_rest(
&self,
task_id: &str,
) -> Result<Vec<TaskPushNotificationConfig>, V1ClientError> {
let body: Value =
self.rest_get(&format!("/tasks/{task_id}/pushNotificationConfigs")).await?;
Ok(parse_push_config_list(body)?)
}
/// Deletes a push notification config via REST
/// (`DELETE /tasks/{taskId}/pushNotificationConfigs/{configId}`).
pub async fn delete_push_notification_config_rest(
&self,
task_id: &str,
config_id: &str,
) -> Result<(), V1ClientError> {
self.rest_delete(&format!("/tasks/{task_id}/pushNotificationConfigs/{config_id}")).await
}
/// Gets the extended agent card via REST (`GET /extendedAgentCard`).
pub async fn get_extended_agent_card_rest(&self) -> Result<AgentCard, V1ClientError> {
self.rest_get("/extendedAgentCard").await
}
}
#[cfg(test)]
mod tests {
#[test]
fn card_sources_read_as_adk_go_reads_them() {
let url = |source: &str| match super::card_source(source).unwrap() {
super::CardSource::Url(url) => url,
super::CardSource::File(path) => panic!("{source} is a file: {path:?}"),
};
assert_eq!(
url("https://agents.example.com"),
"https://agents.example.com/.well-known/agent-card.json"
);
assert_eq!(
url("https://agents.example.com/billing/"),
"https://agents.example.com/billing/.well-known/agent-card.json"
);
assert_eq!(
url("https://agents.example.com/cards/billing.json"),
"https://agents.example.com/cards/billing.json"
);
assert!(matches!(
super::card_source("./cards/billing.json").unwrap(),
super::CardSource::File(_)
));
assert!(matches!(
super::card_source("file:///etc/card.json").unwrap(),
super::CardSource::File(_)
));
assert!(super::card_source("ftp://agents.example.com/card.json").is_err());
}
#[tokio::test]
async fn a_card_file_is_read() {
let dir = std::env::temp_dir().join(format!("a2a-card-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("card.json");
std::fs::write(
&path,
serde_json::json!({
"name": "file-agent",
"description": "from a file",
"version": "1.0.0",
"supportedInterfaces": [{"url": "https://a.example/a2a/v1", "protocolBinding": "JSONRPC", "protocolVersion": "1.0"}],
"capabilities": {},
"defaultInputModes": ["text/plain"],
"defaultOutputModes": ["text/plain"],
"skills": []
})
.to_string(),
)
.unwrap();
let card =
super::A2aV1Client::resolve_agent_card(path.to_str().unwrap()).await.unwrap();
assert_eq!(card.name, "file-agent");
std::fs::remove_dir_all(&dir).unwrap();
}
use super::*;
use a2a_protocol_types::{AgentCapabilities, AgentCard, AgentInterface, AgentSkill};
fn make_test_card() -> AgentCard {
AgentCard {
name: "test-agent".to_string(),
url: Some("http://localhost:9999".to_string()),
description: "A test agent".to_string(),
version: "1.0.0".to_string(),
supported_interfaces: vec![
AgentInterface {
url: "http://localhost:9999/a2a".to_string(),
protocol_binding: "JSONRPC".to_string(),
protocol_version: "1.0".to_string(),
tenant: None,
},
AgentInterface {
url: "http://localhost:9999/rest".to_string(),
protocol_binding: "HTTP+JSON".to_string(),
protocol_version: "1.0".to_string(),
tenant: None,
},
],
default_input_modes: vec!["text/plain".to_string()],
default_output_modes: vec!["text/plain".to_string()],
skills: vec![AgentSkill {
id: "echo".to_string(),
name: "Echo".to_string(),
description: "Echoes input".to_string(),
tags: vec![],
examples: None,
input_modes: None,
output_modes: None,
security_requirements: None,
}],
capabilities: AgentCapabilities::default(),
provider: None,
icon_url: None,
documentation_url: None,
security_schemes: None,
security_requirements: None,
signatures: None,
}
}
fn make_jsonrpc_only_card() -> AgentCard {
let mut card = make_test_card();
card.supported_interfaces.retain(|i| i.protocol_binding == "JSONRPC");
card
}
#[test]
fn new_client_stores_agent_card() {
let card = make_test_card();
let client = A2aV1Client::new(card.clone());
assert_eq!(client.agent_card().name, "test-agent");
assert_eq!(client.agent_card().version, "1.0.0");
}
#[test]
fn with_retry_stores_config() {
let card = make_test_card();
let config = RetryConfig { max_retries: 5, base_delay: Duration::from_millis(500) };
let client = A2aV1Client::with_retry(card, config);
assert_eq!(client.retry_config.max_retries, 5);
assert_eq!(client.retry_config.base_delay, Duration::from_millis(500));
}
#[test]
fn default_retry_config() {
let config = RetryConfig::default();
assert_eq!(config.max_retries, 3);
assert_eq!(config.base_delay, Duration::from_secs(1));
}
#[test]
fn jsonrpc_url_found() {
let client = A2aV1Client::new(make_test_card());
assert_eq!(client.jsonrpc_url(), Some("http://localhost:9999/a2a"));
}
#[test]
fn rest_url_found() {
let client = A2aV1Client::new(make_test_card());
assert_eq!(client.rest_url(), Some("http://localhost:9999/rest"));
}
#[test]
fn rest_url_none_when_not_available() {
let client = A2aV1Client::new(make_jsonrpc_only_card());
assert!(client.rest_url().is_none());
}
#[test]
fn default_headers_include_version() {
let headers = A2aV1Client::default_headers();
let version = headers.get(A2A_VERSION_HEADER).unwrap();
assert_eq!(version, "1.0");
}
#[test]
fn parse_jsonrpc_error_extracts_fields() {
let body = serde_json::json!({
"jsonrpc": "2.0",
"error": {
"code": -32001,
"message": "Task not found: task_123",
"data": [{"@type": "type.googleapis.com/google.rpc.ErrorInfo"}]
},
"id": 1
});
let err = A2aV1Client::parse_jsonrpc_error(&body);
match err {
V1ClientError::JsonRpc { code, message, data } => {
assert_eq!(code, -32001);
assert_eq!(message, "Task not found: task_123");
assert!(data.is_some());
}
other => panic!("expected JsonRpc error, got: {other}"),
}
}
#[test]
fn parse_jsonrpc_error_handles_missing_error_field() {
let body = serde_json::json!({"result": "ok"});
let err = A2aV1Client::parse_jsonrpc_error(&body);
match err {
V1ClientError::JsonRpc { code, .. } => {
assert_eq!(code, 0);
}
other => panic!("expected JsonRpc error, got: {other}"),
}
}
#[test]
fn parse_version_error_extracts_supported_versions() {
let err_obj = serde_json::json!({
"code": -32009,
"message": "Version not supported",
"data": [{
"@type": "type.googleapis.com/google.rpc.ErrorInfo",
"reason": "VERSION_NOT_SUPPORTED",
"domain": "a2a-protocol.org",
"metadata": {
"requested": "2.0",
"supported": "0.3, 1.0"
}
}]
});
let err = A2aV1Client::parse_version_error(&err_obj);
match err {
V1ClientError::VersionNotSupported { requested, supported } => {
assert_eq!(requested, "1.0");
assert_eq!(supported, vec!["0.3", "1.0"]);
}
other => panic!("expected VersionNotSupported, got: {other}"),
}
}
#[test]
fn send_message_results_read_the_v1_oneof() {
let task = serde_json::json!({
"id": "t-1",
"contextId": "c-1",
"status": { "state": "TASK_STATE_COMPLETED" }
});
match parse_send_message_result(serde_json::json!({ "task": task })).unwrap() {
SendMessageResponse::Task(task) => assert_eq!(task.id.0, "t-1"),
other => panic!("expected a task, got {other:?}"),
}
let message = serde_json::json!({
"messageId": "m-1",
"role": "ROLE_AGENT",
"parts": [{ "text": "hi" }]
});
match parse_send_message_result(serde_json::json!({ "message": message })).unwrap() {
SendMessageResponse::Message(message) => assert_eq!(message.id.0, "m-1"),
other => panic!("expected a message, got {other:?}"),
}
}
#[test]
fn send_message_results_accept_the_bare_task_older_servers_send() {
let bare = serde_json::json!({
"id": "t-2",
"contextId": "c-2",
"status": { "state": "TASK_STATE_WORKING" }
});
match parse_send_message_result(bare).unwrap() {
SendMessageResponse::Task(task) => {
assert_eq!(task.id.0, "t-2");
assert_eq!(task.status.state, TaskState::Working);
}
other => panic!("expected a task, got {other:?}"),
}
}
#[test]
fn send_message_results_of_another_shape_are_refused() {
for result in [
serde_json::json!(null),
serde_json::json!({ "status": "done" }),
serde_json::json!({ "task": { "id": "t-3" } }),
] {
assert!(parse_send_message_result(result.clone()).is_err(), "{result}");
}
}
#[test]
fn parse_version_error_handles_empty_data() {
let err_obj = serde_json::json!({
"code": -32009,
"message": "Version not supported"
});
let err = A2aV1Client::parse_version_error(&err_obj);
match err {
V1ClientError::VersionNotSupported { supported, .. } => {
assert!(supported.is_empty());
}
other => panic!("expected VersionNotSupported, got: {other}"),
}
}
#[test]
fn v1_client_error_display() {
let err = V1ClientError::JsonRpc {
code: -32001,
message: "Task not found".to_string(),
data: None,
};
assert_eq!(err.to_string(), "JSON-RPC error -32001: Task not found");
let err = V1ClientError::VersionNotSupported {
requested: "2.0".to_string(),
supported: vec!["0.3".to_string(), "1.0".to_string()],
};
assert!(err.to_string().contains("2.0"));
assert!(err.to_string().contains("0.3"));
let err =
V1ClientError::UnexpectedStatus { status: 500, body: "internal error".to_string() };
assert!(err.to_string().contains("500"));
}
#[test]
fn cached_card_starts_empty() {
let client = A2aV1Client::new(make_test_card());
let cache = client.cached_card.lock().unwrap();
assert!(cache.card.is_none());
assert!(cache.etag.is_none());
assert!(cache.last_modified.is_none());
}
#[test]
fn a_credential_is_attached_only_inside_its_audience() {
let token = |audience: &str| {
adk_core::ScopedToken::new(
adk_core::AgentId::new("urn:adk:agent:caller").unwrap(),
"secret",
adk_core::resource_indicator(audience).unwrap(),
vec![],
)
};
let client = A2aV1Client::new(make_test_card())
.with_credential(token("http://localhost:9999/a2a"));
let headers = client.headers_for("http://localhost:9999/a2a").unwrap();
assert_eq!(headers.get(reqwest::header::AUTHORIZATION).unwrap(), "Bearer secret");
assert_eq!(headers.get(A2A_VERSION_HEADER).unwrap(), A2A_VERSION);
match client.headers_for("http://localhost:9999/rest/tasks") {
Err(V1ClientError::Credential(error)) => {
assert_eq!(error.code, "credential.audience_mismatch");
}
other => panic!("expected a refused credential, got {other:?}"),
}
let anonymous = A2aV1Client::new(make_test_card());
let headers = anonymous.headers_for("http://localhost:9999/rest").unwrap();
assert!(headers.get(reqwest::header::AUTHORIZATION).is_none());
}
}
}