adk-tool 3.0.0

Tool system for Rust Agent Development Kit (ADK-Rust) agents (FunctionTool, MCP, Google Search)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
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
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
// MCP (Model Context Protocol) Toolset Integration
//
// Based on Go implementation: adk-go/tool/mcptoolset/
// Uses official Rust SDK: https://github.com/modelcontextprotocol/rust-sdk
//
// The McpToolset connects to an MCP server, discovers available tools,
// and exposes them as ADK-compatible tools for use with LlmAgent.

use super::discovery::{
    ListError, McpDiscoveryLimits, escape_for_display, list_pages, list_tools, unroutable_name,
    within,
};
use super::parked::{McpCallOutcome, ParkedCallKind, ParkedMcpCall};
use super::reconnect::{
    DEFAULT_RETRY_TOOL_CALLS, is_auth_rejection, is_connection_closed, should_retry_mcp_operation,
};
use super::schema_limits::McpSchemaLimits;
use super::task::{McpTaskConfig, TaskError};
use super::{ConnectionFactory, RefreshConfig, should_refresh_connection};
use adk_core::{
    AdkError, ErrorCategory, ErrorComponent, ReadonlyContext, Result, Tool, ToolContext,
    ToolEffect, Toolset,
};
use async_trait::async_trait;
use base64::{Engine as _, engine::general_purpose::STANDARD};
use futures::StreamExt;
use rmcp::{
    RoleClient, ServiceError,
    model::{
        CallToolRequest, CallToolRequestParams, CallToolResponse, CancelTaskParams,
        CancelledNotification, CancelledNotificationParam, ClientRequest, CompletionContext,
        CompletionInfo, ContentBlock, ErrorCode, GetPromptRequestParams, GetPromptResult,
        GetTaskParams, GetTaskRequest, InputRequest, InputRequests, InputResponses,
        PaginatedRequestParams, Prompt, ReadResourceRequestParams, RequestId, Resource,
        ResourceContents, ResourceTemplate, ServerResult, SubscribeRequestParams, TaskPayload,
        ToolAnnotations, UnsubscribeRequestParams, UpdateTaskParams, UpdateTaskRequest,
    },
    service::{Peer, PeerRequestOptions, RunningService},
};
use serde_json::{Value, json};
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use tokio::sync::{Mutex, RwLock};
use tracing::{debug, warn};

/// Shared factory object used to recreate MCP connections for refresh/retry.
type DynConnectionFactory<S> = Arc<dyn ConnectionFactory<S>>;

/// One live MCP connection. Callers hold a clone for the length of a request,
/// so a refresh never pulls a connection out from under an in-flight call.
type Connection<S> = Arc<RunningService<RoleClient, S>>;

/// How long a `tools/list` result is reused before discovery asks the server again.
const DEFAULT_TOOL_LIST_CACHE_TTL: Duration = Duration::from_secs(60);

/// How long [`Toolset::close`] waits for the connection to finish closing. rmcp kills a
/// stdio server that has not exited 3 seconds after its input closed, within this bound.
const DEFAULT_CLOSE_TIMEOUT: Duration = Duration::from_secs(5);

/// How often `close` checks whether the connection's service loop has ended.
const CLOSE_POLL_INTERVAL: Duration = Duration::from_millis(10);

/// The error code of a request made through a toolset after [`Toolset::close`].
const CLOSED_CODE: &str = "tool.mcp.closed";

/// The error code of a parked legacy call that is not re-issued because it is not retry-safe
/// (spec 3.2 §10 T2).
const NOT_RUN_CODE: &str = "tool.mcp.not_run";

/// The error for a request made through toolset `toolset` after it was closed.
fn closed_error(toolset: &str) -> AdkError {
    AdkError::new(
        ErrorComponent::Tool,
        ErrorCategory::Cancelled,
        CLOSED_CODE,
        format!(
            "MCP toolset '{toolset}' is closed, so it sends nothing to its server; build a new \
             McpToolset to connect again"
        ),
    )
}

/// The connection shared by a toolset, its clones, and every tool it produced.
///
/// The lock guards only the swap: callers take a clone of the current
/// [`Connection`] and release the lock before sending anything, so concurrent
/// requests never wait on each other here.
struct SharedClient<S>
where
    S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
{
    /// The current connection and the number of times it has been replaced.
    current: RwLock<(Connection<S>, u64)>,
    /// Held while a replacement connects, so concurrent failures replace a
    /// dead connection once instead of once per caller.
    refresh: Mutex<()>,
    /// Set by `close`; no request is sent and no connection is made afterwards.
    closed: AtomicBool,
    /// Run scopes that sampling requests count against, shared with every
    /// connection's [`AdkClientHandler`](super::AdkClientHandler).
    #[cfg(feature = "mcp-sampling")]
    sampling_scopes: Arc<crate::sampling::SamplingScopes>,
    /// The tool calls in flight, which an elicitation is attributed to, shared with
    /// every connection's handler (spec 3.1 §10 T1).
    elicitation_scopes: Arc<super::elicitation::ElicitationScopes>,
}

impl<S> SharedClient<S>
where
    S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
{
    fn new(client: RunningService<RoleClient, S>) -> Self {
        #[cfg(feature = "mcp-sampling")]
        let sampling_scopes = adk_client_handler(&client)
            .map(super::elicitation::AdkClientHandler::sampling_scopes)
            .unwrap_or_default();
        let elicitation_scopes = adk_client_handler(&client)
            .map(super::elicitation::AdkClientHandler::elicitation_scopes)
            .unwrap_or_default();
        Self {
            current: RwLock::new((Arc::new(client), 0)),
            refresh: Mutex::new(()),
            closed: AtomicBool::new(false),
            #[cfg(feature = "mcp-sampling")]
            sampling_scopes,
            elicitation_scopes,
        }
    }

    async fn connection(&self) -> Connection<S> {
        Arc::clone(&self.current.read().await.0)
    }

    /// Returns the current connection, or the closed error once `toolset` was closed.
    async fn open_connection(&self, toolset: &str) -> Result<Connection<S>> {
        if self.closed.load(Ordering::SeqCst) {
            return Err(closed_error(toolset));
        }
        Ok(self.connection().await)
    }

    /// Returns the current connection with its generation, which changes on every refresh.
    async fn connection_with_generation(&self) -> (Connection<S>, u64) {
        let current = self.current.read().await;
        (Arc::clone(&current.0), current.1)
    }

    /// Returns the current connection with its generation, first replacing it when it
    /// has already closed and a factory is configured.
    ///
    /// Nothing was sent on a closed connection, so replacing it here never turns the
    /// caller's next request into a replay. Fails once `toolset` was closed.
    async fn live_connection(
        &self,
        toolset: &str,
        factory: Option<&DynConnectionFactory<S>>,
        subscriptions: &RwLock<BTreeSet<String>>,
    ) -> Result<(Connection<S>, u64)> {
        if self.closed.load(Ordering::SeqCst) {
            return Err(closed_error(toolset));
        }
        let (connection, generation) = self.connection_with_generation().await;
        if factory.is_none() || !is_connection_closed(&connection) {
            return Ok((connection, generation));
        }
        debug!("MCP connection closed; reconnecting before the next request");
        self.refresh(toolset, &connection, factory, subscriptions).await?;
        Ok(self.connection_with_generation().await)
    }

    /// Replaces `failed` with a connection from `factory`.
    ///
    /// Returns `Ok(false)` when no factory is configured. When another caller
    /// already replaced `failed`, this returns `Ok(true)` without reconnecting,
    /// and the caller retries on the connection that caller installed. The old
    /// connection closes once the last in-flight request on it finishes. Fails,
    /// without installing a connection, once `toolset` was closed.
    async fn refresh(
        &self,
        toolset: &str,
        failed: &Connection<S>,
        factory: Option<&DynConnectionFactory<S>>,
        subscriptions: &RwLock<BTreeSet<String>>,
    ) -> Result<bool> {
        let Some(factory) = factory else {
            return Ok(false);
        };
        let _refreshing = self.refresh.lock().await;
        if self.closed.load(Ordering::SeqCst) {
            return Err(closed_error(toolset));
        }
        if !Arc::ptr_eq(&self.current.read().await.0, failed) {
            return Ok(true);
        }

        let new_client = factory
            .create_connection()
            .await
            .map_err(|e| AdkError::tool(format!("Failed to refresh MCP connection: {e}")))?;
        restore_subscriptions(&new_client, subscriptions).await?;
        if let Some(handler) = adk_client_handler(&new_client) {
            #[cfg(feature = "mcp-sampling")]
            handler.share_sampling_scopes(Arc::clone(&self.sampling_scopes));
            handler.share_elicitation_scopes(Arc::clone(&self.elicitation_scopes));
        }

        let mut current = self.current.write().await;
        // `close` sets the flag before it takes this lock to read the connection, so a
        // connection made during a close is either refused here or cancelled by it.
        // Dropping a refused connection cancels it.
        if self.closed.load(Ordering::SeqCst) {
            return Err(closed_error(toolset));
        }
        current.0 = Arc::new(new_client);
        current.1 += 1;
        Ok(true)
    }
}

/// The cached `tools/list` result, and how many times it has been invalidated.
#[derive(Default)]
struct ToolListCache {
    entry: Option<CachedToolList>,
    /// Bumped by `invalidate_tool_list_cache`; a fetch stores its result only when
    /// this has not changed since the fetch began.
    invalidations: u64,
}

/// One `tools/list` result and the state it was fetched under.
struct CachedToolList {
    /// Connection generation the list came from; a reconnect invalidates it.
    generation: u64,
    /// `notifications/tools/list_changed` count observed before the fetch.
    list_changes: u64,
    fetched_at: Instant,
    tools: Vec<rmcp::model::Tool>,
}

/// The [`AdkClientHandler`](super::AdkClientHandler) serving `connection`, if it uses one.
fn adk_client_handler<S>(
    connection: &RunningService<RoleClient, S>,
) -> Option<&super::elicitation::AdkClientHandler>
where
    S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
{
    (connection.service() as &dyn std::any::Any)
        .downcast_ref::<super::elicitation::AdkClientHandler>()
}

/// Counts `notifications/tools/list_changed` on connections served by
/// [`AdkClientHandler`](super::AdkClientHandler). Other handlers report zero,
/// so their cached list expires only by TTL or explicit invalidation.
fn tool_list_changes<S>(connection: &RunningService<RoleClient, S>) -> u64
where
    S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
{
    adk_client_handler(connection)
        .map_or(0, super::elicitation::AdkClientHandler::tool_list_changes)
}

/// What a [`CancelOnDrop`] guard asks the server to stop.
enum CancelTarget {
    /// A `tools/call` still awaiting its response, stopped with `notifications/cancelled`.
    Request(RequestId),
    /// A task the server created for a `tools/call`, stopped with `tasks/cancel`.
    Task(String),
}

/// Asks the server to stop work the caller stopped waiting for, such as a call an
/// agent-level tool timeout dropped, instead of finishing it for nobody.
struct CancelOnDrop {
    peer: Option<Peer<RoleClient>>,
    target: CancelTarget,
}

impl CancelOnDrop {
    fn disarm(mut self) {
        self.peer = None;
    }
}

impl Drop for CancelOnDrop {
    fn drop(&mut self) {
        let Some(peer) = self.peer.take() else {
            return;
        };
        // Without a runtime there is no transport left to carry the cancellation.
        let Ok(runtime) = tokio::runtime::Handle::try_current() else {
            return;
        };
        match &self.target {
            CancelTarget::Request(request_id) => {
                let request_id = request_id.clone();
                runtime.spawn(async move {
                    let notification = CancelledNotification::new(CancelledNotificationParam::new(
                        Some(request_id.clone()),
                        Some("the client stopped waiting for this tools/call".to_string()),
                    ));
                    match tokio::time::timeout(
                        TASK_CANCEL_TIMEOUT,
                        peer.send_notification(notification.into()),
                    )
                    .await
                    {
                        Ok(Ok(())) => {
                            debug!(request.id = %request_id, "sent MCP tools/call cancellation")
                        }
                        Ok(Err(error)) => debug!(
                            request.id = %request_id,
                            error = %error,
                            "could not send MCP tools/call cancellation"
                        ),
                        Err(_) => debug!(
                            request.id = %request_id,
                            "MCP tools/call cancellation was not sent before the timeout"
                        ),
                    }
                });
            }
            CancelTarget::Task(task_id) => {
                let task_id = task_id.clone();
                // The task stays in the pending set until a status confirms it, as with
                // every other `tasks/cancel`, so `cancel_pending_tasks` still checks it.
                runtime.spawn(async move {
                    let cancel = peer.cancel_task(CancelTaskParams::new(&task_id));
                    match tokio::time::timeout(TASK_CANCEL_TIMEOUT, cancel).await {
                        Ok(Ok(())) => debug!(task_id, "cancelled MCP task of a dropped tools/call"),
                        Ok(Err(error)) if is_unknown_or_finished_task(&error) => {}
                        Ok(Err(error)) => warn!(
                            task_id,
                            error = %error,
                            "failed to cancel MCP task of a dropped tools/call"
                        ),
                        Err(_) => warn!(
                            task_id,
                            timeout_ms = TASK_CANCEL_TIMEOUT.as_millis(),
                            "MCP server did not acknowledge tasks/cancel for a dropped tools/call"
                        ),
                    }
                });
            }
        }
    }
}

/// Sends one `tools/call` and returns the response envelope unchanged.
///
/// Mirrors rmcp's `call_tool_once`, but keeps the request id so that dropping
/// the returned future cancels the request on the server.
async fn send_tool_call(
    peer: &Peer<RoleClient>,
    params: CallToolRequestParams,
) -> std::result::Result<CallToolResponse, ServiceError> {
    let handle = peer
        .send_cancellable_request(
            ClientRequest::CallToolRequest(CallToolRequest::new(params)),
            PeerRequestOptions::no_options(),
        )
        .await?;
    let cancel = CancelOnDrop {
        peer: Some(handle.peer.clone()),
        target: CancelTarget::Request(handle.id.clone()),
    };
    let response = handle.await_response().await;
    cancel.disarm();
    match response? {
        ServerResult::CallToolResult(result) => Ok(CallToolResponse::Complete(result)),
        ServerResult::InputRequiredResult(result) => Ok(CallToolResponse::InputRequired(result)),
        ServerResult::CreateTaskResult(result) => Ok(CallToolResponse::Task(result)),
        _ => Err(ServiceError::UnexpectedResponse),
    }
}

/// Longest server-issued task id retained in the pending-task set.
const MAX_TASK_ID_BYTES: usize = 16 * 1024;

/// Most input requests answered in one MRTR or in-task input round.
const MAX_INPUT_REQUESTS_PER_ROUND: usize = 64;

/// Most tasks `cancel_pending_tasks` checks or cancels at once.
const MAX_CONCURRENT_TASK_CLEANUPS: usize = 16;

/// Longest wait for a `tasks/cancel` acknowledgement, so an unresponsive
/// server cannot hold a call far past its own deadline.
const TASK_CANCEL_TIMEOUT: Duration = Duration::from_secs(2);

/// Returns `true` when a task request failed because the server no longer
/// tracks the task, or (for `tasks/cancel`) because it already finished.
/// The specification reports both as `-32602`; `-32002` is the older
/// not-found code.
fn is_unknown_or_finished_task(error: &rmcp::ServiceError) -> bool {
    matches!(
        error,
        rmcp::ServiceError::McpError(error)
            if error.code == ErrorCode::INVALID_PARAMS || error.code == ErrorCode::RESOURCE_NOT_FOUND
    )
}

async fn restore_subscriptions<S: rmcp::service::Service<RoleClient>>(
    client: &RunningService<RoleClient, S>,
    subscriptions: &RwLock<BTreeSet<String>>,
) -> Result<()> {
    for uri in subscriptions.read().await.iter() {
        // Existing resource callbacks use the negotiated legacy subscription API.
        #[allow(deprecated)]
        client.subscribe(SubscribeRequestParams::new(uri.clone())).await.map_err(|error| {
            AdkError::tool(format!("Failed to restore MCP resource subscription '{uri}': {error}"))
        })?;
    }
    Ok(())
}

/// The effect a tool's `readOnlyHint` and `idempotentHint` declare; a tool that
/// declares neither is treated as non-idempotent.
fn mcp_tool_effect(annotations: Option<&ToolAnnotations>) -> ToolEffect {
    match annotations {
        Some(hints) if hints.read_only_hint == Some(true) => ToolEffect::ReadOnly,
        Some(hints) if hints.idempotent_hint == Some(true) => ToolEffect::Idempotent,
        _ => ToolEffect::NonIdempotent,
    }
}

/// Most UTF-8 bytes of an `isError` result's text passed to the model.
const MAX_SERVER_ERROR_BYTES: usize = 8 * 1024;

/// The function response for a call the server answered with `isError: true`.
///
/// An `isError` result is the tool's own output, written for the model so it can correct
/// the call, so its text is passed through as `{"error": text}` rather than failing the
/// call: a failed call reaches the model only as its error code. Transport and protocol
/// failures stay errors. The text is cut to [`MAX_SERVER_ERROR_BYTES`] at a character
/// boundary.
fn server_error_response(tool_name: &str, result: &rmcp::model::CallToolResult) -> Value {
    let text: Vec<&str> = result
        .content
        .iter()
        .filter_map(|content| content.as_text())
        .map(|t| t.text.as_str())
        .collect();
    let mut detail = if !text.is_empty() {
        text.join("\n")
    } else if let Some(structured) = &result.structured_content {
        // Structured-only errors carry their detail outside the text blocks.
        structured.to_string()
    } else {
        format!("MCP tool '{tool_name}' reported an error without a message")
    };
    if detail.len() > MAX_SERVER_ERROR_BYTES {
        detail.truncate(detail.floor_char_boundary(MAX_SERVER_ERROR_BYTES));
        detail.push_str(" [truncated]");
    }
    json!({ "error": detail })
}

/// Preserve every MCP content block in ADK's multimodal tool-result envelope.
/// `FunctionResponseData::from_tool_result` consumes this shape in the agent loop.
fn call_tool_result_to_adk_value(
    result: &rmcp::model::CallToolResult,
) -> std::result::Result<Value, String> {
    let mut text_parts = Vec::new();
    let mut inline_data = Vec::new();
    let mut file_data = Vec::new();

    for content in &result.content {
        match content {
            ContentBlock::Text(text) => text_parts.push(text.text.clone()),
            ContentBlock::Image(image) => {
                let data = STANDARD
                    .decode(&image.data)
                    .map_err(|error| format!("invalid MCP image base64: {error}"))?;
                inline_data.push(json!({ "mime_type": image.mime_type, "data": data }));
            }
            ContentBlock::Audio(audio) => {
                let data = STANDARD
                    .decode(&audio.data)
                    .map_err(|error| format!("invalid MCP audio base64: {error}"))?;
                inline_data.push(json!({ "mime_type": audio.mime_type, "data": data }));
            }
            ContentBlock::Resource(resource) => match &resource.resource {
                ResourceContents::TextResourceContents { uri, mime_type, text, .. } => {
                    text_parts.push(text.clone());
                    file_data.push(json!({
                        "mime_type": mime_type.as_deref().unwrap_or("text/plain"),
                        "file_uri": uri,
                    }));
                }
                ResourceContents::BlobResourceContents { uri, mime_type, blob, .. } => {
                    let data = STANDARD
                        .decode(blob)
                        .map_err(|error| format!("invalid MCP resource base64: {error}"))?;
                    inline_data.push(json!({
                        "mime_type": mime_type.as_deref().unwrap_or("application/octet-stream"),
                        "data": data,
                    }));
                    file_data.push(json!({
                        "mime_type": mime_type.as_deref().unwrap_or("application/octet-stream"),
                        "file_uri": uri,
                    }));
                }
                _ => return Err("unsupported MCP embedded resource content".to_string()),
            },
            ContentBlock::ResourceLink(link) => file_data.push(json!({
                "mime_type": link.mime_type.as_deref().unwrap_or("application/octet-stream"),
                "file_uri": link.uri,
            })),
            _ => {}
        }
    }

    let output = match (&result.structured_content, text_parts.is_empty()) {
        (Some(structured), true) => json!({ "output": structured }),
        (Some(structured), false) => json!({ "output": structured, "text": text_parts }),
        (None, false) => json!({ "output": text_parts.join("\n") }),
        (None, true) if !inline_data.is_empty() || !file_data.is_empty() => Value::Null,
        // A successful call may return nothing; reporting it as a failure would invite a
        // retry of a tool that already ran.
        (None, true) => json!({ "output": "" }),
    };

    if inline_data.is_empty() && file_data.is_empty() {
        Ok(output)
    } else {
        Ok(json!({
            "response": output,
            "inline_data": inline_data,
            "file_data": file_data,
        }))
    }
}

/// Type alias for tool filter predicate
pub type ToolFilter = Arc<dyn Fn(&str) -> bool + Send + Sync>;

fn mcp_tool_call_error(
    tool_name: &str,
    error: &ServiceError,
    has_connection_factory: bool,
    replay_allowed: bool,
) -> AdkError {
    if has_connection_factory
        && !replay_allowed
        && should_refresh_connection(error)
        && !is_auth_rejection(error)
    {
        AdkError::tool(format!(
            "MCP tool '{tool_name}' result is uncertain and was not replayed: {error}. \
             Enable tool-call retries only for replay-safe operations"
        ))
    } else {
        AdkError::tool(format!("Failed to call MCP tool '{tool_name}': {error}"))
    }
}

/// Returns `true` when the `ServiceError` wraps an MCP `MethodNotFound` (-32601)
/// JSON-RPC error, indicating the server does not implement the requested method.
fn is_method_not_found(err: &rmcp::ServiceError) -> bool {
    matches!(
        err,
        rmcp::ServiceError::McpError(e) if e.code == ErrorCode::METHOD_NOT_FOUND
    )
}

/// MCP Toolset - connects to an MCP server and exposes its tools as ADK tools.
///
/// This toolset implements the ADK `Toolset` trait and bridges the gap between
/// MCP servers and ADK agents. It:
/// 1. Connects to an MCP server via the provided transport
/// 2. Discovers available tools from the server
/// 3. Converts MCP tools to ADK-compatible `Tool` implementations
/// 4. Proxies tool execution calls to the MCP server
///
/// # Example
///
/// ```rust,ignore
/// use adk_tool::{
///     McpToolset,
///     mcp::rmcp::{ServiceExt, transport::TokioChildProcess},
/// };
/// use tokio::process::Command;
///
/// // Create MCP client connection to a local server
/// let client = ().serve(TokioChildProcess::new(
///     Command::new("/opt/company/bin/workspace-mcp")
///         .arg("--stdio")
///         .arg("--root")
///         .arg("/srv/workspace")
/// )?).await?;
///
/// // Create toolset from the client
/// let toolset = McpToolset::new(client);
///
/// // Add to agent
/// let agent = LlmAgentBuilder::new("assistant")
///     .toolset(Arc::new(toolset))
///     .build()?;
/// ```
pub struct McpToolset<S = ()>
where
    S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
{
    /// The running MCP client service
    client: Arc<SharedClient<S>>,
    /// The last `tools/list` result, shared by clones of this toolset.
    tool_list: Arc<Mutex<ToolListCache>>,
    /// How long `tool_list` is reused; zero disables the cache.
    tool_list_ttl: Duration,
    /// Optional filter to select which tools to expose
    tool_filter: Option<ToolFilter>,
    /// Name of this toolset
    name: String,
    /// Task configuration for long-running operations
    task_config: McpTaskConfig,
    /// Remote tasks whose terminal state has not been observed.
    active_tasks: Arc<Mutex<BTreeSet<String>>>,
    /// Optional connection factory used for reconnection on transport failures.
    connection_factory: Option<DynConnectionFactory<S>>,
    /// Reconnection/retry configuration.
    refresh_config: RefreshConfig,
    /// Whether ambiguous tool-call outcomes may be replayed after reconnection.
    retry_tool_calls: bool,
    /// Resource subscriptions restored after an automatic connection refresh.
    resource_subscriptions: Arc<RwLock<BTreeSet<String>>>,
    /// Policy bridge used to fulfil stateless MRTR and in-task input requests.
    mrtr_handler: Option<super::elicitation::AdkClientHandler>,
    /// Size limits checked against each discovered tool schema.
    schema_limits: McpSchemaLimits,
    /// Bounds on each catalog listing.
    discovery_limits: McpDiscoveryLimits,
    /// How long [`Toolset::close`] waits for the connection to finish closing.
    close_timeout: Duration,
}

impl<S> Clone for McpToolset<S>
where
    S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
{
    fn clone(&self) -> Self {
        Self {
            client: Arc::clone(&self.client),
            tool_list: Arc::clone(&self.tool_list),
            tool_list_ttl: self.tool_list_ttl,
            tool_filter: self.tool_filter.clone(),
            name: self.name.clone(),
            task_config: self.task_config.clone(),
            active_tasks: self.active_tasks.clone(),
            connection_factory: self.connection_factory.clone(),
            refresh_config: self.refresh_config.clone(),
            retry_tool_calls: self.retry_tool_calls,
            resource_subscriptions: Arc::clone(&self.resource_subscriptions),
            mrtr_handler: self.mrtr_handler.clone(),
            schema_limits: self.schema_limits,
            discovery_limits: self.discovery_limits,
            close_timeout: self.close_timeout,
        }
    }
}

impl<S> McpToolset<S>
where
    S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
{
    /// Create a new MCP toolset from a running MCP client service.
    ///
    /// The client should already be connected and initialized.
    /// Use `adk_tool::mcp::rmcp::ServiceExt::serve()` to create the client.
    ///
    /// MRTR and in-task input requests follow ADK's input policy when the client
    /// runs on [`AdkClientHandler`](super::AdkClientHandler), which rejects
    /// sampling and roots. Any other handler receives elicitation requests, and
    /// sampling or roots requests only when it declared those capabilities.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_tool::mcp::rmcp::{ServiceExt, transport::TokioChildProcess};
    /// use tokio::process::Command;
    ///
    /// let client = ().serve(TokioChildProcess::new(
    ///     Command::new("my-mcp-server")
    /// )?).await?;
    ///
    /// let toolset = McpToolset::new(client);
    /// ```
    pub fn new(client: RunningService<RoleClient, S>) -> Self {
        // A client served on ADK's own handler keeps ADK's MRTR input policy, however
        // it was built, so a configured sampling handler stays unreachable through MRTR.
        let mrtr_handler = (client.service() as &dyn std::any::Any)
            .downcast_ref::<super::elicitation::AdkClientHandler>()
            .cloned();
        Self {
            client: Arc::new(SharedClient::new(client)),
            tool_list: Arc::new(Mutex::new(ToolListCache::default())),
            tool_list_ttl: DEFAULT_TOOL_LIST_CACHE_TTL,
            tool_filter: None,
            name: "mcp_toolset".to_string(),
            task_config: McpTaskConfig::default(),
            active_tasks: Arc::new(Mutex::new(BTreeSet::new())),
            connection_factory: None,
            refresh_config: RefreshConfig::default(),
            retry_tool_calls: DEFAULT_RETRY_TOOL_CALLS,
            resource_subscriptions: Arc::new(RwLock::new(BTreeSet::new())),
            mrtr_handler,
            schema_limits: McpSchemaLimits::default(),
            discovery_limits: McpDiscoveryLimits::default(),
            close_timeout: DEFAULT_CLOSE_TIMEOUT,
        }
    }

    /// Create a McpToolset from a RunningService with a custom ClientHandler.
    ///
    /// This is functionally identical to `new()` but makes the intent explicit
    /// when using a custom `ClientHandler` type.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_tool::{McpToolset, mcp::rmcp::ServiceExt};
    ///
    /// let client = my_custom_handler.serve(transport).await?;
    /// let toolset = McpToolset::with_client_handler(client);
    /// ```
    pub fn with_client_handler(client: RunningService<RoleClient, S>) -> Self {
        Self::new(client)
    }

    /// Meters sampling requests that arrive outside any run's tool call against `scope`.
    ///
    /// Requests that arrive while a tool call from a run is in flight count against that
    /// run's budget and spend ledger instead. Without a scope, such requests are unmetered.
    /// See [sampling metering](crate::sampling#metering).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_core::{InMemorySpendLedger, ModelCallScope};
    ///
    /// let scope = ModelCallScope::new()
    ///     .with_spend_ledger(Arc::new(InMemorySpendLedger::default()), "acme")
    ///     .with_agent("mcp-sampling");
    /// let toolset = McpToolset::with_sampling_handler(transport, elicitation, sampling)
    ///     .await?
    ///     .with_sampling_scope(scope);
    /// ```
    #[cfg(feature = "mcp-sampling")]
    pub fn with_sampling_scope(self, scope: adk_core::ModelCallScope) -> Self {
        self.client.sampling_scopes.set_fallback(Some(scope));
        self
    }

    /// Attributes elicitations that arrive outside any tool call of this toolset to
    /// `scope` (spec 3.1 §10 T1).
    ///
    /// Elicitations that arrive while one of this toolset's tool calls is in flight belong
    /// to that call: the connection's handler answers them inside
    /// [`ElicitationScope::for_call`](super::ElicitationScope::for_call) of the call, which
    /// a handler reads with [`ElicitationScope::current`](super::ElicitationScope::current).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_tool::mcp::ElicitationScope;
    ///
    /// let toolset = McpToolset::with_elicitation_handler(transport, handler)
    ///     .await?
    ///     .with_elicitation_scope(ElicitationScope::new("app", "operator", "console"));
    /// ```
    pub fn with_elicitation_scope(self, scope: super::elicitation::ElicitationScope) -> Self {
        self.client.elicitation_scopes.set_fallback(Some(scope));
        self
    }

    /// Set a custom name for this toolset.
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }

    /// Enable MCP task support (SEP-2663) for long-running operations.
    ///
    /// Tools no longer declare task support: every call is one `tools/call`, and the
    /// server decides per call whether to answer with a task. When it does, this toolset
    /// polls `tasks/get` at the server's `pollIntervalMs` (else `config`'s interval) until the
    /// task completes, reading the result inlined in the status response, and answers
    /// in-task input requests through the connection's handler.
    ///
    /// Tasks need all three sides: this configuration, a client that declares the
    /// `io.modelcontextprotocol/tasks` extension
    /// ([`AdkClientHandler::with_tasks`](crate::mcp::AdkClientHandler::with_tasks); a plain
    /// `()` client never does), and a server that declares the tasks capability. A task
    /// returned while any of them is missing is cancelled, and the call fails with the reason.
    /// Every tool of the toolset reports
    /// [`is_long_running`](adk_core::Tool::is_long_running) when tasks are enabled and
    /// negotiated.
    ///
    /// # Example
    ///
    /// ```rust
    /// use std::time::Duration;
    ///
    /// use adk_tool::mcp::{AdkClientHandler, McpTaskConfig, McpToolset};
    /// use rmcp::service::RunningService;
    ///
    /// fn tasks_toolset(
    ///     client: RunningService<rmcp::RoleClient, AdkClientHandler>,
    /// ) -> McpToolset<AdkClientHandler> {
    ///     McpToolset::new(client).with_task_support(
    ///         McpTaskConfig::enabled()
    ///             .poll_interval(Duration::from_secs(2))
    ///             .timeout(Duration::from_secs(300)),
    ///     )
    /// }
    /// ```
    pub fn with_task_support(mut self, config: McpTaskConfig) -> Self {
        self.task_config = config;
        self
    }

    /// Set the size limits checked against each discovered tool schema.
    ///
    /// Discovery measures every input and output schema before copying or logging
    /// it. A tool whose schema exceeds a limit is skipped with a warning naming
    /// this toolset and the tool, and the remaining tools are still registered.
    /// See [`McpSchemaLimits`] for how size is measured and why the defaults are
    /// what they are.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_tool::mcp::{McpSchemaLimits, McpToolset};
    ///
    /// fn admit_larger_schemas(toolset: McpToolset) -> McpToolset {
    ///     toolset.with_schema_limits(
    ///         McpSchemaLimits::default().with_max_bytes(1024 * 1024).with_max_nodes(40_000),
    ///     )
    /// }
    /// ```
    pub fn with_schema_limits(mut self, limits: McpSchemaLimits) -> Self {
        self.schema_limits = limits;
        self
    }

    /// Set the bounds on each catalog listing: `tools/list`, `resources/list`,
    /// `resources/templates/list`, and `prompts/list`.
    ///
    /// A listing fails with `AdkError::Tool` when the server still returns a
    /// `nextCursor` after `max_pages` pages, returns a cursor it already returned,
    /// or takes longer than `timeout`, reconnects included. See
    /// [`McpDiscoveryLimits`] for the defaults.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_tool::mcp::{McpDiscoveryLimits, McpToolset};
    /// use std::time::Duration;
    ///
    /// fn fail_fast(toolset: McpToolset) -> McpToolset {
    ///     toolset.with_discovery_limits(
    ///         McpDiscoveryLimits::default().with_max_pages(16).with_timeout(Duration::from_secs(5)),
    ///     )
    /// }
    /// ```
    pub fn with_discovery_limits(mut self, limits: McpDiscoveryLimits) -> Self {
        self.discovery_limits = limits;
        self
    }

    /// Set how long a `tools/list` result is reused before discovery asks the
    /// server again. The default is 60 seconds; `Duration::ZERO` disables this
    /// cache, so every [`Toolset::tools`] call sends `tools/list`, except for a page
    /// the server marked fresh with `ttlMs`, which rmcp's response cache answers.
    ///
    /// An agent resolves its toolsets before every model turn, so without the
    /// cache each turn costs one `tools/list` round trip per MCP server. The
    /// cached list is dropped before the TTL elapses when:
    ///
    /// | Event | Applies to |
    /// |-------|------------|
    /// | The connection is refreshed | Every toolset with a connection factory |
    /// | The server sends `notifications/tools/list_changed` | Connections served by [`AdkClientHandler`](super::AdkClientHandler) |
    /// | [`invalidate_tool_list_cache`](Self::invalidate_tool_list_cache) is called | Every toolset, including a fetch already in flight |
    ///
    /// # Example
    ///
    /// ```
    /// use adk_tool::mcp::McpToolset;
    /// use std::time::Duration;
    ///
    /// fn rediscover_every_turn(toolset: McpToolset) -> McpToolset {
    ///     toolset.with_tool_list_cache_ttl(Duration::ZERO)
    /// }
    /// ```
    pub fn with_tool_list_cache_ttl(mut self, ttl: Duration) -> Self {
        self.tool_list_ttl = ttl;
        self
    }

    /// Set how long [`Toolset::close`] waits for the connection to finish closing.
    /// The default is 5 seconds.
    ///
    /// Remote tasks the toolset started get at most half of it to confirm their
    /// cancellation; the session gets the rest. A connection still closing when the
    /// timeout elapses keeps closing in the background: rmcp kills a stdio server
    /// that is still running 3 seconds after its input closed.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_tool::mcp::McpToolset;
    /// use std::time::Duration;
    ///
    /// fn close_fast(toolset: McpToolset) -> McpToolset {
    ///     toolset.with_close_timeout(Duration::from_secs(1))
    /// }
    /// ```
    pub fn with_close_timeout(mut self, timeout: Duration) -> Self {
        self.close_timeout = timeout;
        self
    }

    /// Drop the cached `tools/list` result, so the next [`Toolset::tools`] call
    /// asks the server again.
    ///
    /// This also clears the connection's rmcp response cache, which keeps pages
    /// the server marked fresh with `ttlMs`, and stops a `tools/list` already in
    /// flight from caching its result: that call still returns what it fetched,
    /// and the next call fetches again.
    ///
    /// Call this from a custom `ClientHandler`'s `on_tool_list_changed` when the
    /// connection does not run on [`AdkClientHandler`](super::AdkClientHandler),
    /// which invalidates the cache on its own.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_tool::mcp::McpToolset;
    ///
    /// async fn on_catalog_changed(toolset: &McpToolset) {
    ///     toolset.invalidate_tool_list_cache().await;
    /// }
    /// ```
    pub async fn invalidate_tool_list_cache(&self) {
        // Cleared first, so a fetch that starts after the bump below reads the server.
        self.client.connection().await.peer().clear_response_cache().await;
        let mut cache = self.tool_list.lock().await;
        cache.invalidations += 1;
        cache.entry = None;
    }

    /// Reuse the connection's client policy for stateless MRTR and task input.
    pub(crate) fn with_mrtr_handler(
        mut self,
        handler: super::elicitation::AdkClientHandler,
    ) -> Self {
        self.mrtr_handler = Some(handler);
        self
    }

    /// Provide a connection factory to enable automatic MCP reconnection.
    pub fn with_connection_factory<F>(mut self, factory: Arc<F>) -> Self
    where
        F: ConnectionFactory<S> + 'static,
    {
        self.connection_factory = Some(factory);
        self
    }

    /// Configure MCP reconnect/retry behavior.
    pub fn with_refresh_config(mut self, config: RefreshConfig) -> Self {
        self.refresh_config = config;
        self
    }

    /// Allow MCP tool calls to be replayed after reconnecting.
    ///
    /// A transport failure after request transmission is an ambiguous outcome:
    /// a mutating tool may have completed its external effect before the
    /// response was lost. Enable this only for read-only tools or operations
    /// protected by a stable provider idempotency guarantee. Discovery and
    /// resource operations keep their normal reconnect behavior without this.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let toolset = McpToolset::new(client)
    ///     .with_connection_factory(Arc::new(factory))
    ///     .with_tool_call_retries();
    /// ```
    pub fn with_tool_call_retries(mut self) -> Self {
        self.retry_tool_calls = true;
        self
    }

    /// Add a filter to select which tools to expose.
    ///
    /// The filter function receives a tool name and returns true if the tool
    /// should be included.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let toolset = McpToolset::new(client)
    ///     .with_filter(|name| {
    ///         matches!(name, "read_file" | "list_directory" | "search_files")
    ///     });
    /// ```
    pub fn with_filter<F>(mut self, filter: F) -> Self
    where
        F: Fn(&str) -> bool + Send + Sync + 'static,
    {
        self.tool_filter = Some(Arc::new(filter));
        self
    }

    /// Add a filter that only includes tools with the specified names.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let toolset = McpToolset::new(client)
    ///     .with_tools(&["read_file", "write_file"]);
    /// ```
    pub fn with_tools(self, tool_names: &[&str]) -> Self {
        let names: Vec<String> = tool_names.iter().map(|s| s.to_string()).collect();
        self.with_filter(move |name| names.iter().any(|n| n == name))
    }

    /// Get a cancellation token that can be used to shutdown the MCP server.
    ///
    /// Call `cancel()` on the returned token to cleanly shutdown the MCP server.
    /// This should be called before exiting to avoid EPIPE errors. Cancelling does
    /// not wait for the server to exit; [`Toolset::close`] does, and also stops the
    /// toolset from reconnecting.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let toolset = McpToolset::new(client);
    /// let cancel_token = toolset.cancellation_token().await;
    ///
    /// // ... use the toolset ...
    ///
    /// // Before exiting:
    /// cancel_token.cancel();
    /// ```
    pub async fn cancellation_token(&self) -> rmcp::service::RunningServiceCancellationToken {
        self.client.connection().await.cancellation_token()
    }

    /// Check whether the underlying MCP service connection has been closed or cancelled.
    ///
    /// Returns `true` once the transport has closed, as it does when a stdio server
    /// process exits, the connection's cancellation token has fired, or the toolset
    /// was closed with [`Toolset::close`]. This is useful for health monitoring — a
    /// closed connection indicates the server process has crashed or the transport
    /// has been lost. With a connection factory, the next request replaces a closed
    /// connection before sending, unless the toolset was closed.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// if toolset.is_closed().await {
    ///     tracing::warn!("MCP server connection lost");
    /// }
    /// ```
    pub async fn is_closed(&self) -> bool {
        self.client.closed.load(Ordering::SeqCst)
            || is_connection_closed(&*self.client.connection().await)
    }

    /// Closes the toolset, waiting at most `timeout` for its connection to finish closing.
    ///
    /// Marks the toolset closed first, so no new request starts and no connection
    /// factory reconnects, then cancels the remote tasks it started (within half of
    /// `timeout`) and the rmcp service. The service loop closes the transport before it
    /// ends: a stdio server's input is closed and the process waited for, or killed after
    /// 3 seconds; a Streamable HTTP session is ended with `DELETE`. A second call only
    /// waits for that to finish.
    pub(crate) async fn close_within(&self, timeout: Duration) {
        let deadline = tokio::time::Instant::now() + timeout;
        if !self.client.closed.swap(true, Ordering::SeqCst) {
            match tokio::time::timeout(timeout / 2, self.cancel_pending_tasks()).await {
                Ok(Ok(())) => {}
                Ok(Err(error)) => warn!(
                    toolset.name = %self.name,
                    error = %error,
                    "MCP tasks did not confirm cancellation before the toolset closed"
                ),
                Err(_) => warn!(
                    toolset.name = %self.name,
                    close.timeout_ms = timeout.as_millis(),
                    "MCP task cancellation did not finish within half of the close timeout"
                ),
            }
        }
        // Read under the write lock, which a reconnect holds while it installs a
        // connection, so a connection made during this close is the one cancelled here.
        let connection = Arc::clone(&self.client.current.write().await.0);
        connection.cancellation_token().cancel();
        // The peer's channel closes when the service loop ends, after its transport closed.
        let closed = tokio::time::timeout_at(deadline, async {
            while !connection.peer().is_transport_closed() {
                tokio::time::sleep(CLOSE_POLL_INTERVAL).await;
            }
        })
        .await;
        match closed {
            Ok(()) => debug!(toolset.name = %self.name, "closed MCP connection"),
            Err(_) => warn!(
                toolset.name = %self.name,
                close.timeout_ms = timeout.as_millis(),
                "MCP connection did not finish closing within the close timeout; its transport \
                 keeps closing in the background"
            ),
        }
    }

    /// Call one MCP tool and preserve structured, text, image, audio, and resource content
    /// in the same ADK multimodal value shape used by model-facing tool execution.
    ///
    /// # Errors
    ///
    /// Returns `AdkError::Tool` without contacting the server when the toolset's
    /// [filter](Self::with_filter) excludes `name`, and when the call fails.
    pub async fn call_tool_value(
        &self,
        name: &str,
        arguments: serde_json::Map<String, Value>,
    ) -> Result<Value> {
        self.direct_tool(name).await?.execute_value(Value::Object(arguments), None).await
    }

    /// Calls MCP tool `name`, ending the call with its parked form when the server needs
    /// input instead of answering it in process (spec 3.2 §10 T2).
    ///
    /// A server that answers `input_required` with input requests, or a task that reports
    /// `input_required`, parks the call: the result is [`McpCallOutcome::Parked`], nothing
    /// waits in this process, and a parked task keeps waiting on the server and is not
    /// cancelled by [`cancel_pending_tasks`](Self::cancel_pending_tasks). Persist the
    /// [`ParkedMcpCall`], ask the person, and pass the answers to
    /// [`reissue`](Self::reissue) — from this toolset or one built after a restart. A
    /// state-only `input_required` asks nothing and is retried in place, as in every call. A
    /// server before 2026-07-28 asks with `elicitation/create` while the call runs, which the
    /// connection's handler answers in process (see [`ParkedMcpCall::current`]). `call_id` is
    /// recorded in the parked call.
    ///
    /// # Errors
    ///
    /// Returns `AdkError::Tool` without contacting the server when the toolset's
    /// [filter](Self::with_filter) excludes `name`, when the call fails, and when it takes more
    /// than [`McpTaskConfig::max_input_rounds`] input rounds.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_tool::mcp::{McpCallOutcome, McpToolset};
    ///
    /// async fn send(toolset: &McpToolset) -> adk_core::Result<Option<String>> {
    ///     let arguments = serde_json::json!({ "draftId": "d-7" }).as_object().unwrap().clone();
    ///     Ok(match toolset.call_tool_resumable(Some("call-1"), "send_draft", arguments).await? {
    ///         McpCallOutcome::Completed(value) => Some(value.to_string()),
    ///         // Persist it beside the approval that asks the person.
    ///         McpCallOutcome::Parked(parked) => {
    ///             let _checkpoint = serde_json::to_string(&parked).unwrap();
    ///             None
    ///         }
    ///     })
    /// }
    /// ```
    pub async fn call_tool_resumable(
        &self,
        call_id: Option<&str>,
        name: &str,
        arguments: serde_json::Map<String, Value>,
    ) -> Result<McpCallOutcome> {
        let tool = self.direct_tool(name).await?;
        let params = tool.call_params(Value::Object(arguments))?;
        let spec = CallSpec {
            call_id: call_id.map(str::to_string),
            mode: InputMode::Park,
            input_rounds: 0,
        };
        tool.run(params, &spec).await
    }

    /// Re-issues a parked call with the answers to its input requests (spec 3.2 §7.7, §10 T2).
    ///
    /// `responses` maps keys of [`ParkedMcpCall::input_requests`] to the answers, as
    /// `inputResponses` carry them (an elicitation's answer is its `ElicitResult` as JSON).
    /// What happens depends on [`ParkedMcpCall::kind`]:
    ///
    /// | Kind | Re-issue |
    /// |---|---|
    /// | [`Mrtr`](ParkedCallKind::Mrtr) | A new `tools/call` with `inputResponses` and the stored `requestState`. The server ended the first request at `input_required`, so this is the call's first execution |
    /// | [`Task`](ParkedCallKind::Task) | `tasks/get` on the stored task; outstanding requests equal to the parked ones are answered through `tasks/update`, and polling continues until the task ends. Needs task support on this toolset |
    /// | [`Legacy`](ParkedCallKind::Legacy) | Refused as not run unless the tool the server publishes now declares `readOnlyHint` or `idempotentHint`; then the original call runs again, without `responses`, and its new questions park again |
    ///
    /// A server that answers with new input requests — for example because the
    /// `requestState` lapsed — parks the call again: the result is
    /// [`McpCallOutcome::Parked`] with the next round, under
    /// [`McpTaskConfig::max_input_rounds`] counted across re-issues.
    ///
    /// # Errors
    ///
    /// Returns `AdkError::Tool` when `parked` names another toolset, its input requests do
    /// not match their digest, `responses` answers a request it does not hold, the
    /// [filter](Self::with_filter) excludes the tool, a task is re-issued on a toolset or
    /// server without task support, or the call fails. A `Legacy` call that is not
    /// retry-safe fails with code `tool.mcp.not_run` without contacting the tool.
    ///
    /// # Example
    ///
    /// ```rust
    /// use adk_tool::mcp::{McpCallOutcome, McpToolset, ParkedMcpCall};
    /// use rmcp::model::{ElicitResult, ElicitationAction, InputResponses};
    ///
    /// async fn resume(toolset: &McpToolset, checkpoint: &str) -> adk_core::Result<McpCallOutcome> {
    ///     let parked: ParkedMcpCall = serde_json::from_str(checkpoint).unwrap();
    ///     let approved = ElicitResult::new(ElicitationAction::Accept);
    ///     let responses: InputResponses = parked
    ///         .input_requests
    ///         .keys()
    ///         .map(|key| (key.clone(), serde_json::to_value(&approved).unwrap()))
    ///         .collect();
    ///     toolset.reissue(&parked, responses).await
    /// }
    /// ```
    pub async fn reissue(
        &self,
        parked: &ParkedMcpCall,
        responses: InputResponses,
    ) -> Result<McpCallOutcome> {
        let refused = |reason: String| {
            AdkError::new(
                ErrorComponent::Tool,
                ErrorCategory::InvalidInput,
                "tool.mcp.reissue_refused",
                format!(
                    "parked call of MCP tool '{}' was not re-issued: {reason}",
                    escape_for_display(&parked.tool_name)
                ),
            )
        };
        if parked.server_id != self.name {
            return Err(refused(format!(
                "it was made through toolset '{}', not '{}'; re-issue it on that server's toolset",
                parked.server_id, self.name
            )));
        }
        if !parked.is_intact() {
            return Err(refused(
                "its input requests do not match their digest, so the answers cannot be bound \
                 to them"
                    .to_string(),
            ));
        }
        if let Some(key) = responses.keys().find(|key| !parked.input_requests.contains_key(*key)) {
            return Err(refused(format!(
                "the answer '{}' has no input request of that key",
                escape_for_display(key)
            )));
        }

        let mut tool = self.direct_tool(&parked.tool_name).await?;
        let mut params =
            tool.call_params(Value::Object(parked.arguments.clone().unwrap_or_default()))?;
        let spec = CallSpec {
            call_id: parked.call_id.clone(),
            mode: InputMode::Park,
            input_rounds: parked.input_rounds,
        };
        match &parked.kind {
            ParkedCallKind::Mrtr => {
                params.input_responses = (!responses.is_empty()).then_some(responses);
                params.request_state = parked.request_state.clone();
                tool.run(params, &spec).await
            }
            ParkedCallKind::Task { task_id } => {
                if !tool.task_config.enable_tasks || !tool.server_supports_tasks {
                    return Err(refused(format!(
                        "task '{}' needs task support on toolset '{}' and its server; build the \
                         toolset with `McpToolset::with_task_support(McpTaskConfig::enabled())` \
                         on a connection that declares the tasks extension",
                        escape_for_display(task_id),
                        self.name
                    )));
                }
                // Answers bind to the questions they were given for: a request the server
                // changed or added is asked again.
                let answered = parked
                    .input_requests
                    .iter()
                    .filter_map(|(key, request)| {
                        responses
                            .get(key)
                            .map(|answer| (key.clone(), (request.clone(), answer.clone())))
                    })
                    .collect();
                let peer = self.client.open_connection(&self.name).await?.peer().clone();
                let cancel_on_drop =
                    CancelOnDrop { peer: Some(peer), target: CancelTarget::Task(task_id.clone()) };
                self.active_tasks.lock().await.insert(task_id.clone());
                let mut call = ParkedMcpCall::of_call(&self.name, &params, spec.call_id.as_deref());
                call.input_rounds = parked.input_rounds;
                let outcome =
                    tool.poll_task(task_id.clone(), None, spec.mode, call, answered).await;
                cancel_on_drop.disarm();
                outcome.map_err(|error| AdkError::tool(format!("Task execution failed: {error}")))
            }
            ParkedCallKind::Legacy => {
                // The tool's effect as the server publishes it now decides the replay.
                let connection = self.client.open_connection(&self.name).await?;
                let listed = tokio::time::timeout(
                    self.discovery_limits.timeout,
                    list_tools(connection.peer(), self.discovery_limits.max_pages),
                )
                .await
                .map_err(|_| ListError::Timeout {
                    method: "tools/list",
                    timeout: self.discovery_limits.timeout,
                })
                .and_then(|listed| listed)
                .map_err(|error| {
                    AdkError::tool(format!(
                        "Failed to list MCP tools from '{}': {error}",
                        self.name
                    ))
                })?;
                tool.annotations = listed
                    .into_iter()
                    .find(|listed| listed.name == parked.tool_name)
                    .and_then(|listed| listed.annotations);
                if !mcp_tool_effect(tool.annotations.as_ref()).is_retry_safe() {
                    return Err(AdkError::new(
                        ErrorComponent::Tool,
                        ErrorCategory::Cancelled,
                        NOT_RUN_CODE,
                        format!(
                            "MCP tool '{}' was not run: its call to server '{}' was lost with the \
                             connection, and the tool declares neither readOnlyHint nor \
                             idempotentHint, so running it again could repeat its effect",
                            escape_for_display(&parked.tool_name),
                            self.name
                        ),
                    ));
                }
                tool.run(params, &spec).await
            }
        }
    }

    /// Enters the scopes an agent's call made with `ctx` runs in, as a tool of this toolset
    /// enters them: sampling requests the server sends meanwhile count against the run, and
    /// elicitations belong to the call (spec 3.2 §7.7). The scopes end with the guard.
    pub(crate) fn enter_call_scopes(&self, ctx: &dyn ToolContext) -> CallScopes {
        #[cfg(feature = "mcp-sampling")]
        let sampling = ctx
            .run_config()
            .map(|config| {
                adk_core::ModelCallScope::for_run(config, ctx.app_name(), ctx.agent_name())
            })
            .filter(|scope| !scope.is_unmetered())
            .map(|scope| self.client.sampling_scopes.enter(scope));
        CallScopes {
            #[cfg(feature = "mcp-sampling")]
            _sampling: sampling,
            _elicitation: self
                .client
                .elicitation_scopes
                .enter(super::elicitation::ElicitationScope::for_call(ctx)),
        }
    }

    /// A tool for `name` without its declaration, for calls made outside discovery.
    ///
    /// Fails without contacting the server when the filter excludes `name`.
    async fn direct_tool(&self, name: &str) -> Result<McpTool<S>> {
        if let Some(filter) = &self.tool_filter
            && !filter(name)
        {
            return Err(AdkError::tool(format!(
                "MCP tool '{}' is excluded by the tool filter of toolset '{}'",
                escape_for_display(name),
                self.name
            )));
        }
        let server_supports_tasks = self
            .client
            .open_connection(&self.name)
            .await?
            .peer_info()
            .is_some_and(|info| info.capabilities.supports_tasks());
        Ok(McpTool {
            name: name.into(),
            origin: format!("mcp:{}", self.name),
            description: String::new(),
            input_schema: None,
            output_schema: None,
            client: self.client.clone(),
            connection_factory: self.connection_factory.clone(),
            refresh_config: self.refresh_config.clone(),
            retry_tool_calls: self.retry_tool_calls,
            annotations: None,
            annotations_json: None,
            server_supports_tasks,
            task_config: self.task_config.clone(),
            active_tasks: self.active_tasks.clone(),
            mrtr_handler: self.mrtr_handler.clone(),
            resource_subscriptions: self.resource_subscriptions.clone(),
            // A re-issued call finishes one an app was already shown for, or not.
            #[cfg(feature = "mcp-apps")]
            ui: None,
        })
    }

    /// Cancels every remote task this toolset started and has not seen finish.
    ///
    /// The set covers tasks whose tool-call future was dropped and tasks an
    /// in-flight call is still polling, so this also cancels in-flight calls:
    /// each one returns a task error once the server reports the cancellation.
    ///
    /// Each task is checked with `tasks/get` first. A task that is already
    /// terminal, or that the server no longer knows (its TTL expired, or the
    /// connection was refreshed into a new session), is released without a
    /// cancel request. Any other task receives `tasks/cancel` and a second
    /// `tasks/get`. A task stays tracked until a terminal status or an
    /// unknown-task response confirms it, so calling this again re-checks it.
    ///
    /// Nothing else prunes the set: every task whose call ended before it saw a
    /// terminal status stays tracked until this runs, so a long-lived toolset
    /// that drops calls should call it periodically as well as at shutdown.
    ///
    /// Cancellation is cooperative on the server side, so bound this call
    /// with the shutdown deadline. [`McpServerManager`](super::McpServerManager)
    /// runs it within its grace period before closing a managed session.
    ///
    /// # Errors
    ///
    /// Returns `AdkError::Tool` naming a task whose outcome is not confirmed:
    /// `tasks/get` or `tasks/cancel` failed for a reason other than an unknown
    /// or finished task, or the task is still running after the cancel request.
    /// Tasks confirmed by the same call are released regardless.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use adk_tool::mcp::McpToolset;
    /// use std::time::Duration;
    ///
    /// async fn shutdown(toolset: &McpToolset) {
    ///     let cleanup = toolset.cancel_pending_tasks();
    ///     match tokio::time::timeout(Duration::from_secs(5), cleanup).await {
    ///         Ok(Ok(())) => {}
    ///         Ok(Err(error)) => tracing::warn!(%error, "remote MCP tasks may still run"),
    ///         Err(_) => tracing::warn!("MCP task cleanup exceeded the shutdown deadline"),
    ///     }
    ///     toolset.cancellation_token().await.cancel();
    /// }
    /// ```
    pub async fn cancel_pending_tasks(&self) -> Result<()> {
        let ids: Vec<_> = self.active_tasks.lock().await.iter().cloned().collect();
        if ids.is_empty() {
            return Ok(());
        }
        let client = self.client.connection().await.peer().clone();
        let settled = |id: String| {
            let client = client.clone();
            async move {
                match client.get_task(GetTaskParams::new(&id)).await {
                    Ok(status) if status.task.task.task_id != id => Err(AdkError::tool(format!(
                        "MCP server answered tasks/get for task '{id}' with task '{}'",
                        status.task.task.task_id
                    ))),
                    Ok(status) => Ok(status.task.status().is_terminal()),
                    Err(error) if is_unknown_or_finished_task(&error) => Ok(true),
                    Err(error) => Err(AdkError::tool(format!(
                        "MCP task '{id}' status is unavailable: {error}"
                    ))),
                }
            }
        };
        let results: Vec<Result<()>> = futures::stream::iter(ids)
            .map(|id| {
                let client = &client;
                let settled = &settled;
                async move {
                    if !settled(id.clone()).await? {
                        if let Err(error) = client.cancel_task(CancelTaskParams::new(&id)).await
                            && !is_unknown_or_finished_task(&error)
                        {
                            return Err(AdkError::tool(format!(
                                "MCP task '{id}' cancellation outcome is unknown: {error}"
                            )));
                        }
                        if !settled(id.clone()).await? {
                            return Err(AdkError::tool(format!(
                                "MCP task '{id}' has not confirmed termination after tasks/cancel; \
                             call cancel_pending_tasks again to re-check it"
                            )));
                        }
                    }
                    self.active_tasks.lock().await.remove(&id);
                    Ok(())
                }
            })
            .buffer_unordered(MAX_CONCURRENT_TASK_CLEANUPS)
            .collect()
            .await;
        for result in results {
            result?;
        }
        Ok(())
    }

    /// List static resources from the connected MCP server.
    ///
    /// Returns the list of resources advertised by the server via the
    /// `resources/list` protocol method. Returns an empty `Vec` when the
    /// server does not support resources (i.e. responds with
    /// `MethodNotFound`).
    ///
    /// # Errors
    ///
    /// Returns `AdkError::Tool` on transport or unexpected server errors, and when
    /// the listing exceeds the [discovery limits](Self::with_discovery_limits).
    pub async fn list_resources(&self) -> Result<Vec<Resource>> {
        let client = self.client.open_connection(&self.name).await?;
        let limits = self.discovery_limits;
        let method = "resources/list";
        let listing = list_pages(method, limits.max_pages, |cursor| {
            let client = Arc::clone(&client);
            async move {
                let page = client
                    .list_resources(Some(PaginatedRequestParams::default().with_cursor(cursor)))
                    .await?;
                Ok((page.resources, page.next_cursor))
            }
        });
        match within(method, limits.timeout, listing).await {
            Ok(resources) => Ok(resources),
            Err(ListError::Service(error)) if is_method_not_found(&error) => Ok(Vec::new()),
            Err(error) => Err(AdkError::tool(format!(
                "Failed to list MCP resources from '{}': {error}",
                self.name
            ))),
        }
    }

    /// List URI template resources from the connected MCP server.
    ///
    /// Returns the list of resource templates advertised by the server via
    /// the `resourceTemplates/list` protocol method. Returns an empty `Vec`
    /// when the server does not support resource templates (i.e. responds
    /// with `MethodNotFound`).
    ///
    /// # Errors
    ///
    /// Returns `AdkError::Tool` on transport or unexpected server errors, and when
    /// the listing exceeds the [discovery limits](Self::with_discovery_limits).
    pub async fn list_resource_templates(&self) -> Result<Vec<ResourceTemplate>> {
        let client = self.client.open_connection(&self.name).await?;
        let limits = self.discovery_limits;
        let method = "resources/templates/list";
        let listing = list_pages(method, limits.max_pages, |cursor| {
            let client = Arc::clone(&client);
            async move {
                let page = client
                    .list_resource_templates(Some(
                        PaginatedRequestParams::default().with_cursor(cursor),
                    ))
                    .await?;
                Ok((page.resource_templates, page.next_cursor))
            }
        });
        match within(method, limits.timeout, listing).await {
            Ok(templates) => Ok(templates),
            Err(ListError::Service(error)) if is_method_not_found(&error) => Ok(Vec::new()),
            Err(error) => Err(AdkError::tool(format!(
                "Failed to list MCP resource templates from '{}': {error}",
                self.name
            ))),
        }
    }

    /// Read a resource by URI from the connected MCP server.
    ///
    /// Delegates to the `resources/read` protocol method. Returns the
    /// resource contents on success.
    ///
    /// # Errors
    ///
    /// Returns `AdkError::Tool("resource not found: {uri}")` when the URI
    /// does not match any resource on the server. Returns a generic
    /// `AdkError::Tool` on transport or other server errors.
    pub async fn read_resource(&self, uri: &str) -> Result<Vec<ResourceContents>> {
        let client = self.client.open_connection(&self.name).await?;
        let params = ReadResourceRequestParams::new(uri.to_string());
        match client.read_resource(params).await {
            Ok(result) => Ok(result.contents),
            Err(e) => {
                if is_method_not_found(&e) {
                    Err(AdkError::tool(format!("resource not found: {uri}")))
                } else {
                    Err(AdkError::tool(format!("Failed to read MCP resource '{uri}': {e}")))
                }
            }
        }
    }

    /// The apps this server's tools show (spec 3.3 §6.1 `genui-apps`): each tool's
    /// `_meta.ui`, including the tools only an app may call, which
    /// [`tools`](Toolset::tools) leaves out.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// for binding in toolset.ui_bindings().await? {
    ///     println!("{} shows {} (model: {})", binding.tool, binding.resource_uri, binding.visibility.model);
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns `AdkError::Tool` when the server cannot be reached or its listing exceeds the
    /// [discovery limits](Self::with_discovery_limits).
    #[cfg(feature = "mcp-apps")]
    pub async fn ui_bindings(&self) -> Result<Vec<super::apps::McpUiBinding>> {
        let listed = self.listed_tools().await?;
        Ok(listed.iter().filter_map(super::apps::McpUiBinding::of_tool).collect())
    }

    /// Who may call each tool this server publishes, by its name on the server, in the
    /// server's order: its `_meta.ui.visibility`, or the model and the app when it declares
    /// none (spec 3.3 §6.1 `genui-apps`; see [`McpUiVisibility::of_tool`](super::apps::McpUiVisibility::of_tool)).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// for (tool, visibility) in toolset.tool_visibility().await? {
    ///     println!("{tool}: model {}, app {}", visibility.model, visibility.app);
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns `AdkError::Tool` when the server cannot be reached or its listing exceeds the
    /// [discovery limits](Self::with_discovery_limits).
    #[cfg(feature = "mcp-apps")]
    pub async fn tool_visibility(&self) -> Result<Vec<(String, super::apps::McpUiVisibility)>> {
        let listed = self.listed_tools().await?;
        Ok(listed
            .iter()
            .map(|tool| (tool.name.to_string(), super::apps::McpUiVisibility::of_tool(tool)))
            .collect())
    }

    /// Every tool the server lists now, uncached, within the discovery limits.
    #[cfg(feature = "mcp-apps")]
    async fn listed_tools(&self) -> Result<Vec<rmcp::model::Tool>> {
        let connection = self.client.open_connection(&self.name).await?;
        tokio::time::timeout(
            self.discovery_limits.timeout,
            list_tools(connection.peer(), self.discovery_limits.max_pages),
        )
        .await
        .map_err(|_| ListError::Timeout {
            method: "tools/list",
            timeout: self.discovery_limits.timeout,
        })
        .and_then(|listed| listed)
        .map_err(|error| {
            AdkError::tool(format!("Failed to list MCP tools from '{}': {error}", self.name))
        })
    }

    /// Reads the app at `uri`, a `ui://` resource, with what its `_meta.ui` declares
    /// (spec 3.3 §6.1 `genui-apps`). A host still checks it before it shows it.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let app = toolset.read_app("ui://weather/app").await?;
    /// assert_eq!(app.mime_type, adk_tool::mcp::MCP_APP_MIME_TYPE);
    /// ```
    ///
    /// # Errors
    ///
    /// Returns `AdkError::Tool` when `uri` is not a `ui://` URI, the resource cannot be read,
    /// or it is not an MCP App's HTML.
    #[cfg(feature = "mcp-apps")]
    pub async fn read_app(&self, uri: &str) -> Result<super::apps::McpAppResource> {
        if !uri.starts_with("ui://") {
            return Err(AdkError::tool(format!(
                "'{}' is not an MCP App resource: apps are ui:// resources",
                escape_for_display(uri)
            )));
        }
        let contents = self.read_resource(uri).await?;
        super::apps::McpAppResource::from_contents(uri, &contents)
    }

    /// Return the prompt templates published by the connected MCP server.
    ///
    /// Returns an empty `Vec` when the server does not support prompts.
    ///
    /// # Errors
    ///
    /// Returns `AdkError::Tool` on transport or unexpected server errors, and when
    /// the listing exceeds the [discovery limits](Self::with_discovery_limits).
    pub async fn list_prompts(&self) -> Result<Vec<Prompt>> {
        let client = self.client.open_connection(&self.name).await?;
        let limits = self.discovery_limits;
        let method = "prompts/list";
        let listing = list_pages(method, limits.max_pages, |cursor| {
            let client = Arc::clone(&client);
            async move {
                let page = client
                    .list_prompts(Some(PaginatedRequestParams::default().with_cursor(cursor)))
                    .await?;
                Ok((page.prompts, page.next_cursor))
            }
        });
        match within(method, limits.timeout, listing).await {
            Ok(prompts) => Ok(prompts),
            Err(ListError::Service(error)) if is_method_not_found(&error) => Ok(Vec::new()),
            Err(error) => Err(AdkError::tool(format!(
                "failed to list MCP prompts from '{}': {error}",
                self.name
            ))),
        }
    }

    /// Resolve one published MCP prompt with optional typed arguments.
    pub async fn get_prompt(
        &self,
        name: &str,
        arguments: Option<serde_json::Map<String, Value>>,
    ) -> Result<GetPromptResult> {
        let mut params = GetPromptRequestParams::new(name);
        if let Some(arguments) = arguments {
            params = params.with_arguments(arguments);
        }
        let client = self.client.open_connection(&self.name).await?;
        client
            .get_prompt(params)
            .await
            .map_err(|error| AdkError::tool(format!("failed to get MCP prompt '{name}': {error}")))
    }

    /// Request completion suggestions for one prompt argument.
    pub async fn complete_prompt_argument(
        &self,
        prompt_name: &str,
        argument_name: &str,
        current_value: &str,
        context: Option<CompletionContext>,
    ) -> Result<CompletionInfo> {
        let client = self.client.open_connection(&self.name).await?;
        client
            .complete_prompt_argument(prompt_name, argument_name, current_value, context)
            .await
            .map_err(|error| {
                AdkError::tool(format!(
                    "failed to complete MCP prompt argument '{argument_name}': {error}"
                ))
            })
    }

    /// Request completion suggestions for one resource-template argument.
    pub async fn complete_resource_argument(
        &self,
        uri_template: &str,
        argument_name: &str,
        current_value: &str,
        context: Option<CompletionContext>,
    ) -> Result<CompletionInfo> {
        let client = self.client.open_connection(&self.name).await?;
        client
            .complete_resource_argument(uri_template, argument_name, current_value, context)
            .await
            .map_err(|error| {
                AdkError::tool(format!(
                    "failed to complete MCP resource argument '{argument_name}': {error}"
                ))
            })
    }

    /// Subscribe to change notifications for a resource URI.
    pub async fn subscribe_resource(&self, uri: &str) -> Result<()> {
        let client = self.client.open_connection(&self.name).await?;
        // `subscriptions/listen` replaces this in 2026-07-28, but we negotiate
        // 2025-11-25, and `listen` also stops routing notifications through
        // `ClientHandler`, which this crate's resource callbacks rely on.
        #[allow(deprecated)]
        client.subscribe(SubscribeRequestParams::new(uri)).await.map_err(|error| {
            AdkError::tool(format!("failed to subscribe to MCP resource '{uri}': {error}"))
        })?;
        self.resource_subscriptions.write().await.insert(uri.to_string());
        Ok(())
    }

    /// Remove a resource subscription created by [`subscribe_resource`](Self::subscribe_resource).
    pub async fn unsubscribe_resource(&self, uri: &str) -> Result<()> {
        let client = self.client.open_connection(&self.name).await?;
        // Paired with `subscribe_resource`; see the note there.
        #[allow(deprecated)]
        client.unsubscribe(UnsubscribeRequestParams::new(uri)).await.map_err(|error| {
            AdkError::tool(format!("failed to unsubscribe MCP resource '{uri}': {error}"))
        })?;
        self.resource_subscriptions.write().await.remove(uri);
        Ok(())
    }
}

#[async_trait]
impl<S> Toolset for McpToolset<S>
where
    S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
{
    fn name(&self) -> &str {
        &self.name
    }

    async fn tools(&self, _ctx: Arc<dyn ReadonlyContext>) -> Result<Vec<Arc<dyn Tool>>> {
        let limits = self.discovery_limits;
        let list_error = |error: ListError| {
            AdkError::tool(format!("Failed to list MCP tools from '{}': {error}", self.name))
        };
        let discovery = async {
            let (mut connection, mut generation) = self
                .client
                .live_connection(
                    &self.name,
                    self.connection_factory.as_ref(),
                    &self.resource_subscriptions,
                )
                .await?;
            // Read before fetching, so a change notified or an invalidation made mid-fetch
            // keeps the result out of the cache.
            let mut list_changes = tool_list_changes(&connection);
            let (cached, invalidations) = {
                let cache = self.tool_list.lock().await;
                let cached = cache
                    .entry
                    .as_ref()
                    .filter(|cached| {
                        !self.tool_list_ttl.is_zero()
                            && cached.generation == generation
                            && cached.list_changes == list_changes
                            && cached.fetched_at.elapsed() < self.tool_list_ttl
                    })
                    .map(|cached| cached.tools.clone());
                (cached, cache.invalidations)
            };
            if let Some(tools) = cached {
                return Ok((connection, tools));
            }

            let mut attempt = 0u32;
            let has_connection_factory = self.connection_factory.is_some();
            let fetched = loop {
                let error = match list_tools(connection.peer(), limits.max_pages).await {
                    Ok(tools) => break tools,
                    Err(ListError::Service(error)) => error,
                    // A server that pages without end would do the same on a new connection.
                    Err(bound) => return Err(list_error(bound)),
                };
                if !should_retry_mcp_operation(
                    &error,
                    attempt,
                    &self.refresh_config,
                    has_connection_factory,
                    true,
                ) {
                    return Err(list_error(ListError::Service(error)));
                }

                let retry_attempt = attempt + 1;
                if self.refresh_config.log_reconnections {
                    warn!(
                        attempt = retry_attempt,
                        max_attempts = self.refresh_config.max_attempts,
                        error = %error,
                        "MCP tools/list failed; reconnecting and retrying"
                    );
                }

                if self.refresh_config.retry_delay_ms > 0 {
                    tokio::time::sleep(tokio::time::Duration::from_millis(
                        self.refresh_config.retry_delay_ms,
                    ))
                    .await;
                }

                if !self
                    .client
                    .refresh(
                        &self.name,
                        &connection,
                        self.connection_factory.as_ref(),
                        &self.resource_subscriptions,
                    )
                    .await?
                {
                    return Err(list_error(ListError::Service(error)));
                }
                (connection, generation) = self.client.connection_with_generation().await;
                list_changes = tool_list_changes(&connection);
                attempt += 1;
            };
            if !self.tool_list_ttl.is_zero() {
                let mut cache = self.tool_list.lock().await;
                if cache.invalidations == invalidations {
                    cache.entry = Some(CachedToolList {
                        generation,
                        list_changes,
                        fetched_at: Instant::now(),
                        tools: fetched.clone(),
                    });
                }
            }
            Ok::<_, AdkError>((connection, fetched))
        };
        let (connection, mcp_tools) = match tokio::time::timeout(limits.timeout, discovery).await {
            Ok(discovered) => discovered?,
            Err(_) => {
                return Err(list_error(ListError::Timeout {
                    method: "tools/list",
                    timeout: limits.timeout,
                }));
            }
        };

        // Convert MCP tools to ADK tools
        let mut tools: Vec<Arc<dyn Tool>> = Vec::new();
        let mut seen = HashSet::new();
        let server_supports_tasks =
            connection.peer_info().is_some_and(|info| info.capabilities.supports_tasks());

        for mcp_tool in mcp_tools {
            let tool_name = mcp_tool.name.to_string();

            // Apply filter if present
            if let Some(ref filter) = self.tool_filter
                && !filter(&tool_name)
            {
                continue;
            }

            // The server chooses the name as well as the schema, so logs show it escaped.
            let logged_name = escape_for_display(&tool_name);
            if let Some(reason) = unroutable_name(&tool_name) {
                warn!(
                    toolset.name = %self.name,
                    tool.name = %logged_name,
                    reason,
                    "skipping MCP tool whose name no model provider can call"
                );
                continue;
            }
            // A tool only an app may call, with an app of its own or not, is never the model's
            // (spec 3.3 §6.1 `genui-apps`).
            #[cfg(feature = "mcp-apps")]
            let ui = super::apps::McpUiBinding::of_tool(&mcp_tool);
            #[cfg(feature = "mcp-apps")]
            if !super::apps::McpUiVisibility::of_tool(&mcp_tool).model {
                debug!(
                    toolset.name = %self.name,
                    tool.name = %logged_name,
                    "leaving out an MCP tool only its app may call"
                );
                continue;
            }
            // The first definition of a name wins, whatever happens to it below.
            if !seen.insert(tool_name.clone()) {
                warn!(
                    toolset.name = %self.name,
                    tool.name = %logged_name,
                    "skipping MCP tool that repeats the name of an earlier tool on the same \
                     server; the first definition is kept"
                );
                continue;
            }
            // Measured from the server's document before anything copies or logs it.
            let limits = self.schema_limits;
            let measured = limits
                .measure(&mcp_tool.input_schema)
                .map_err(|size| ("input", size))
                .and_then(|input| {
                    mcp_tool
                        .output_schema
                        .as_deref()
                        .map(|schema| limits.measure(schema))
                        .transpose()
                        .map(|output| (input, output))
                        .map_err(|size| ("output", size))
                });
            let (input_size, output_size) = match measured {
                Ok(sizes) => sizes,
                Err((kind, size)) => {
                    warn!(
                        toolset.name = %self.name,
                        tool.name = %logged_name,
                        schema.kind = kind,
                        schema.bytes = size.bytes,
                        schema.nodes = size.nodes,
                        schema.max_bytes = limits.max_bytes,
                        schema.max_nodes = limits.max_nodes,
                        "skipping MCP tool whose schema exceeds the size limits; \
                         raise them with McpToolset::with_schema_limits if the server is trusted"
                    );
                    continue;
                }
            };
            debug!(
                toolset.name = %self.name,
                tool.name = %logged_name,
                schema.bytes = input_size.bytes,
                schema.nodes = input_size.nodes,
                output_schema.bytes = output_size.map(|size| size.bytes),
                output_schema.nodes = output_size.map(|size| size.nodes),
                "registering MCP tool"
            );
            let annotations_json =
                mcp_tool.annotations.as_ref().and_then(|hints| serde_json::to_value(hints).ok());
            let mut description = mcp_tool.description.map(|d| d.to_string()).unwrap_or_default();
            if let Some(kept) = limits.truncate_description(&description) {
                warn!(
                    toolset.name = %self.name,
                    tool.name = %logged_name,
                    description.bytes = description.len(),
                    description.max_bytes = limits.max_description_bytes,
                    "truncating MCP tool description that exceeds the size limit; raise it with \
                     McpSchemaLimits::with_max_description_bytes if the server is trusted"
                );
                description = kept.to_string();
            }
            let adk_tool = McpTool {
                name: tool_name,
                origin: format!("mcp:{}", self.name),
                description,
                input_schema: Some(Value::Object(Arc::unwrap_or_clone(mcp_tool.input_schema))),
                output_schema: mcp_tool
                    .output_schema
                    .map(|schema| Value::Object(Arc::unwrap_or_clone(schema))),
                client: self.client.clone(),
                connection_factory: self.connection_factory.clone(),
                refresh_config: self.refresh_config.clone(),
                retry_tool_calls: self.retry_tool_calls,
                annotations: mcp_tool.annotations,
                annotations_json,
                server_supports_tasks,
                task_config: self.task_config.clone(),
                active_tasks: self.active_tasks.clone(),
                mrtr_handler: self.mrtr_handler.clone(),
                resource_subscriptions: self.resource_subscriptions.clone(),
                #[cfg(feature = "mcp-apps")]
                ui,
            };

            tools.push(Arc::new(adk_tool) as Arc<dyn Tool>);
        }

        Ok(tools)
    }

    /// Ends the MCP session and the server process behind it, waiting at most the
    /// [close timeout](McpToolset::with_close_timeout).
    ///
    /// Pending remote tasks are cancelled first, then the rmcp service. A stdio server's
    /// input is closed and its process waited for, or killed if it is still running 3
    /// seconds later; a Streamable HTTP session is ended with `DELETE`.
    ///
    /// Closing is final and shared: clones of this toolset and every tool it produced
    /// stop with it. Afterwards [`tools`](Toolset::tools), tool calls, and the resource
    /// and prompt methods fail with an `AdkError` whose code is `tool.mcp.closed`, and a
    /// [connection factory](McpToolset::with_connection_factory) is not used to
    /// reconnect. Build a new toolset to reach the server again. Closing again only waits
    /// for the first close to finish.
    async fn close(&self) {
        self.close_within(self.close_timeout).await;
    }
}

impl McpToolset<super::elicitation::AdkClientHandler> {
    /// Create a McpToolset with elicitation support from a transport.
    ///
    /// This creates the MCP client using `AdkClientHandler`, which advertises
    /// elicitation capabilities and delegates requests to the provided handler.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_tool::{McpToolset, ElicitationHandler, AutoDeclineElicitationHandler};
    /// use adk_tool::mcp::rmcp::transport::TokioChildProcess;
    /// use tokio::process::Command;
    /// use std::sync::Arc;
    ///
    /// let transport = TokioChildProcess::new(Command::new("my-mcp-server"))?;
    /// let handler = Arc::new(AutoDeclineElicitationHandler);
    /// let toolset = McpToolset::with_elicitation_handler(transport, handler).await?;
    /// ```
    ///
    /// # ConnectionFactory with Elicitation
    ///
    /// To preserve elicitation across reconnections, clone the `Arc<dyn ElicitationHandler>`
    /// into your `ConnectionFactory` implementation:
    ///
    /// ```rust,ignore
    /// use adk_tool::{McpToolset, ElicitationHandler};
    /// use adk_tool::mcp::ConnectionFactory;
    /// use adk_tool::mcp::rmcp::{
    ///     ServiceExt,
    ///     service::{RoleClient, RunningService},
    ///     transport::TokioChildProcess,
    /// };
    /// use tokio::process::Command;
    /// use std::sync::Arc;
    ///
    /// struct MyReconnectFactory {
    ///     handler: Arc<dyn ElicitationHandler>,
    ///     server_command: String,
    /// }
    ///
    /// // The factory creates a fresh AdkClientHandler on each reconnection,
    /// // so the new connection advertises elicitation capabilities.
    /// // The ConnectionFactory trait itself is unchanged.
    /// ```
    pub async fn with_elicitation_handler<T, E, A>(
        transport: T,
        handler: std::sync::Arc<dyn super::elicitation::ElicitationHandler>,
    ) -> Result<Self>
    where
        T: rmcp::transport::IntoTransport<rmcp::RoleClient, E, A> + Send + 'static,
        E: std::error::Error + Send + Sync + 'static,
    {
        use rmcp::ServiceExt;
        let adk_handler = super::elicitation::AdkClientHandler::new(handler);
        let client = adk_handler
            .serve(transport)
            .await
            .map_err(|e| AdkError::tool(format!("failed to connect MCP server: {e}")))?;
        Ok(Self::new(client))
    }

    /// Create an MCP toolset with elicitation and resource notification handlers.
    ///
    /// Both handlers are installed before the protocol handshake, so resource
    /// update notifications can be received immediately after subscribing.
    pub async fn with_handlers<T, E, A>(
        transport: T,
        elicitation_handler: std::sync::Arc<dyn super::elicitation::ElicitationHandler>,
        resource_notification_handler: std::sync::Arc<
            dyn super::resource_notifications::ResourceNotificationHandler,
        >,
    ) -> Result<Self>
    where
        T: rmcp::transport::IntoTransport<rmcp::RoleClient, E, A> + Send + 'static,
        E: std::error::Error + Send + Sync + 'static,
    {
        use rmcp::ServiceExt;
        let adk_handler = super::elicitation::AdkClientHandler::new(elicitation_handler)
            .with_resource_notification_handler(resource_notification_handler);
        let client = adk_handler
            .serve(transport)
            .await
            .map_err(|error| AdkError::tool(format!("failed to connect MCP server: {error}")))?;
        Ok(Self::new(client))
    }

    /// Create a McpToolset with MCP sampling support from a transport.
    ///
    /// This creates the MCP client using `AdkClientHandler`, which advertises
    /// both elicitation and sampling capabilities. When the connected MCP server
    /// sends a `sampling/createMessage` request, it is delegated to the provided
    /// [`SamplingHandler`](crate::sampling::SamplingHandler).
    ///
    /// An elicitation handler is also required because `AdkClientHandler` always
    /// advertises elicitation. Use [`AutoDeclineElicitationHandler`](super::elicitation::AutoDeclineElicitationHandler) if you don't
    /// need custom elicitation behavior.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_tool::{McpToolset, AutoDeclineElicitationHandler};
    /// use adk_tool::sampling::LlmSamplingHandler;
    /// use adk_tool::mcp::rmcp::transport::TokioChildProcess;
    /// use tokio::process::Command;
    /// use std::sync::Arc;
    ///
    /// let transport = TokioChildProcess::new(Command::new("my-mcp-server"))?;
    /// let elicitation = Arc::new(AutoDeclineElicitationHandler);
    /// let sampling = Arc::new(LlmSamplingHandler::new(my_llm.clone()));
    /// let toolset = McpToolset::with_sampling_handler(transport, elicitation, sampling).await?;
    /// ```
    ///
    /// # ConnectionFactory with Sampling
    ///
    /// To preserve sampling across reconnections, clone both handler `Arc`s
    /// into your `ConnectionFactory` implementation and rebuild the
    /// `AdkClientHandler` on each reconnection.
    #[cfg(feature = "mcp-sampling")]
    pub async fn with_sampling_handler<T, E, A>(
        transport: T,
        elicitation_handler: std::sync::Arc<dyn super::elicitation::ElicitationHandler>,
        sampling_handler: std::sync::Arc<dyn crate::sampling::SamplingHandler>,
    ) -> Result<Self>
    where
        T: rmcp::transport::IntoTransport<rmcp::RoleClient, E, A> + Send + 'static,
        E: std::error::Error + Send + Sync + 'static,
    {
        use rmcp::ServiceExt;
        let adk_handler = super::elicitation::AdkClientHandler::new(elicitation_handler)
            .with_sampling_handler(sampling_handler);
        let client = adk_handler
            .serve(transport)
            .await
            .map_err(|e| AdkError::tool(format!("failed to connect MCP server: {e}")))?;
        Ok(Self::new(client))
    }

    /// Create a toolset with elicitation, sampling, and resource notifications.
    #[cfg(feature = "mcp-sampling")]
    pub async fn with_sampling_and_resource_handlers<T, E, A>(
        transport: T,
        elicitation_handler: std::sync::Arc<dyn super::elicitation::ElicitationHandler>,
        sampling_handler: std::sync::Arc<dyn crate::sampling::SamplingHandler>,
        resource_notification_handler: std::sync::Arc<
            dyn super::resource_notifications::ResourceNotificationHandler,
        >,
    ) -> Result<Self>
    where
        T: rmcp::transport::IntoTransport<rmcp::RoleClient, E, A> + Send + 'static,
        E: std::error::Error + Send + Sync + 'static,
    {
        use rmcp::ServiceExt;
        let adk_handler = super::elicitation::AdkClientHandler::new(elicitation_handler)
            .with_sampling_handler(sampling_handler)
            .with_resource_notification_handler(resource_notification_handler);
        let client = adk_handler
            .serve(transport)
            .await
            .map_err(|error| AdkError::tool(format!("failed to connect MCP server: {error}")))?;
        Ok(Self::new(client))
    }
}

/// How a call answers the server's input requests (spec 3.2 §10 T2).
#[derive(Clone, Copy, PartialEq, Eq)]
enum InputMode {
    /// Through the connection's handler, in process: the single-process fast path.
    Answer,
    /// By ending the call with its parked form.
    Park,
}

/// The scopes of an agent's call, entered by [`McpToolset::enter_call_scopes`]; they end
/// when this is dropped.
pub(crate) struct CallScopes {
    #[cfg(feature = "mcp-sampling")]
    _sampling: Option<crate::sampling::SamplingScopeGuard>,
    _elicitation: super::elicitation::ElicitationScopeGuard,
}

/// A call's identity and input policy, kept across its rounds.
struct CallSpec {
    /// The agent's function call ID, recorded in the parked form.
    call_id: Option<String>,
    mode: InputMode,
    /// Input rounds taken before this attempt; nonzero for a re-issue.
    input_rounds: usize,
}

/// Individual MCP tool wrapper that implements the ADK `Tool` trait.
///
/// This struct wraps an MCP tool and proxies execution calls to the MCP server.
struct McpTool<S>
where
    S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
{
    name: String,
    /// `mcp:{toolset name}`, the identity approvals of this tool's calls bind to.
    origin: String,
    description: String,
    input_schema: Option<Value>,
    output_schema: Option<Value>,
    client: Arc<SharedClient<S>>,
    connection_factory: Option<DynConnectionFactory<S>>,
    refresh_config: RefreshConfig,
    retry_tool_calls: bool,
    /// Safety hints published by the MCP server for this tool.
    annotations: Option<ToolAnnotations>,
    /// `annotations` as the JSON object the server sent, for [`Tool::annotations`].
    annotations_json: Option<Value>,
    /// Whether the negotiated server capabilities permit task-augmented tool calls.
    server_supports_tasks: bool,
    /// Task configuration
    task_config: McpTaskConfig,
    active_tasks: Arc<Mutex<BTreeSet<String>>>,
    resource_subscriptions: Arc<RwLock<BTreeSet<String>>>,
    /// Policy bridge used to fulfil MRTR input without keeping server state.
    mrtr_handler: Option<super::elicitation::AdkClientHandler>,
    /// The app the tool shows, from its `_meta.ui` (spec 3.3 §6.1 `genui-apps`).
    #[cfg(feature = "mcp-apps")]
    ui: Option<super::apps::McpUiBinding>,
}

impl<S> McpTool<S>
where
    S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
{
    /// The name of the toolset that produced this tool.
    fn toolset_name(&self) -> &str {
        self.origin.strip_prefix("mcp:").unwrap_or(&self.origin)
    }

    /// Runs one call whose input the connection's handler answers in process.
    async fn execute_value(&self, args: Value, call_id: Option<String>) -> Result<Value> {
        let params = self.call_params(args)?;
        let spec = CallSpec { call_id, mode: InputMode::Answer, input_rounds: 0 };
        match self.run(params, &spec).await? {
            McpCallOutcome::Completed(value) => Ok(value),
            McpCallOutcome::Parked(_) => Err(AdkError::tool(format!(
                "MCP tool '{}' parked a call whose input is answered in process",
                self.name
            ))),
        }
    }

    /// The `tools/call` parameters for `args`, which must be an object or null.
    fn call_params(&self, args: Value) -> Result<CallToolRequestParams> {
        let mut params = CallToolRequestParams::new(self.name.clone());
        if !(args.is_null() || args == json!({})) {
            match args {
                Value::Object(map) => params = params.with_arguments(map),
                _ => return Err(AdkError::tool("Tool arguments must be an object")),
            }
        }
        Ok(params)
    }

    /// Runs the call `params` describes to its outcome under `spec`.
    async fn run(&self, params: CallToolRequestParams, spec: &CallSpec) -> Result<McpCallOutcome> {
        // SEP-2663 moved the task decision to the server, so one request shape
        // covers both modes and the response says which one happened.
        let mut call =
            ParkedMcpCall::of_call(self.toolset_name(), &params, spec.call_id.as_deref());
        let (response, peer, input_rounds) = self.call_tool_with_retry(params, spec).await?;
        call.input_rounds = input_rounds;
        let result = match response {
            CallToolResponse::Complete(result) => result,
            CallToolResponse::Task(created) => {
                let task_id = created.task.task_id.clone();
                if task_id.is_empty() || task_id.len() > MAX_TASK_ID_BYTES {
                    return Err(AdkError::tool(format!(
                        "MCP tool '{}' returned a task id of {} bytes; expected 1 to \
                         {MAX_TASK_ID_BYTES}",
                        self.name,
                        task_id.len()
                    )));
                }
                // Armed before the first await, so dropping the call from here on cancels a
                // task that nothing would poll.
                let cancel_on_drop =
                    CancelOnDrop { peer: Some(peer), target: CancelTarget::Task(task_id.clone()) };
                self.active_tasks.lock().await.insert(task_id.clone());
                if !self.task_config.enable_tasks || !self.server_supports_tasks {
                    // Nothing polls this task, so stop it rather than leave it running remotely.
                    self.cancel_task(&task_id).await;
                    cancel_on_drop.disarm();
                    let remedy = if self.task_config.enable_tasks {
                        "the server did not negotiate the tasks capability"
                    } else {
                        "task support is disabled on this toolset; enable it with \
                         `McpToolset::with_task_support(McpTaskConfig::enabled())`"
                    };
                    return Err(AdkError::tool(format!(
                        "MCP tool '{}' returned task '{task_id}', which was cancelled because \
                         {remedy}",
                        self.name
                    )));
                }
                debug!(tool = self.name, task_id, "MCP server materialized a task");
                let outcome = self
                    .poll_task(
                        task_id,
                        created.task.poll_interval_ms,
                        spec.mode,
                        call,
                        BTreeMap::new(),
                    )
                    .await;
                cancel_on_drop.disarm();
                return outcome
                    .map_err(|error| AdkError::tool(format!("Task execution failed: {error}")));
            }
            // `call_tool_with_retry` returns input requests only to a call that parks.
            CallToolResponse::InputRequired(required) if spec.mode == InputMode::Park => {
                return Ok(McpCallOutcome::Parked(call.waiting(
                    ParkedCallKind::Mrtr,
                    required.request_state,
                    required.input_requests.unwrap_or_default(),
                    input_rounds,
                )));
            }
            CallToolResponse::InputRequired(_) => {
                return Err(AdkError::tool(format!(
                    "MCP tool '{}' returned an unresolved MRTR input request",
                    self.name
                )));
            }
            response => {
                return Err(AdkError::tool(format!(
                    "MCP tool '{}' returned an unsupported response: {response:?}",
                    self.name
                )));
            }
        };

        if result.is_error.unwrap_or(false) {
            debug!(tool = self.name, "MCP server answered the call with isError");
            return Ok(McpCallOutcome::Completed(server_error_response(&self.name, &result)));
        }

        call_tool_result_to_adk_value(&result).map(McpCallOutcome::Completed).map_err(|error| {
            AdkError::tool(format!("MCP tool '{}' result invalid: {error}", self.name))
        })
    }

    /// Sends `tools/call` and returns the response envelope unchanged.
    ///
    /// Sends one request per round rather than using rmcp's `call_tool`: the
    /// latter fulfils SEP-2322 `input_required` rounds on its own and rejects a
    /// task response outright, which would break every server that
    /// materializes a task.
    ///
    /// Returns the response with the peer of the connection that answered it and the input
    /// rounds the call has taken. A call that parks gets an `input_required` with input
    /// requests back instead of having them answered.
    async fn call_tool_with_retry(
        &self,
        mut params: CallToolRequestParams,
        spec: &CallSpec,
    ) -> Result<(CallToolResponse, Peer<RoleClient>, usize)> {
        let has_connection_factory = self.connection_factory.is_some();
        let metadata_allows_replay = mcp_tool_effect(self.annotations.as_ref()).is_retry_safe();
        let replay_allowed = self.retry_tool_calls || metadata_allows_replay;
        let mut attempt = 0u32;
        let call = ParkedMcpCall::of_call(self.toolset_name(), &params, spec.call_id.as_deref());

        let mut input_rounds = spec.input_rounds;
        let mut state_only_rounds = 0u32;
        loop {
            let (connection, _) = self
                .client
                .live_connection(
                    self.toolset_name(),
                    self.connection_factory.as_ref(),
                    &self.resource_subscriptions,
                )
                .await?;
            // A legacy `elicitation/create` arriving meanwhile belongs to this call.
            let in_flight = self.client.elicitation_scopes.enter_call(call.clone().waiting(
                ParkedCallKind::Legacy,
                None,
                InputRequests::new(),
                input_rounds,
            ));
            let call_result = send_tool_call(connection.peer(), params.clone()).await;
            drop(in_flight);

            match call_result {
                Ok(CallToolResponse::InputRequired(mut required)) => {
                    input_rounds += 1;
                    if input_rounds > self.task_config.max_input_rounds {
                        return Err(AdkError::tool(format!(
                            "MCP tool '{}' exceeded {} MRTR input rounds",
                            self.name, self.task_config.max_input_rounds
                        )));
                    }
                    // The same checks rmcp's `call_tool` applies to each round.
                    let requests =
                        required.input_requests.take().filter(|requests| !requests.is_empty());
                    if requests.is_none() && required.request_state.is_none() {
                        return Err(AdkError::tool(format!(
                            "MCP tool '{}' returned input_required with neither input requests \
                             nor request state",
                            self.name
                        )));
                    }
                    let responses = match requests {
                        Some(requests) if spec.mode == InputMode::Park => {
                            required.input_requests = Some(requests);
                            return Ok((
                                CallToolResponse::InputRequired(required),
                                connection.peer().clone(),
                                input_rounds,
                            ));
                        }
                        Some(requests) => {
                            state_only_rounds = 0;
                            let parked = call.clone().waiting(
                                ParkedCallKind::Mrtr,
                                required.request_state.clone(),
                                requests.clone(),
                                input_rounds,
                            );
                            parked.within(self.fulfill_input(requests)).await.map_err(|error| {
                                AdkError::tool(format!(
                                    "MCP tool '{}' input request failed: {error}",
                                    self.name
                                ))
                            })?
                        }
                        None => {
                            // A state-only round asks nothing, so back off before resending it.
                            let delay_ms = (50u64 << state_only_rounds.min(3)).min(250);
                            tokio::time::sleep(Duration::from_millis(delay_ms)).await;
                            state_only_rounds += 1;
                            InputResponses::new()
                        }
                    };
                    params.input_responses = (!responses.is_empty()).then_some(responses);
                    params.request_state = required.request_state;
                    attempt = 0;
                }
                Ok(result) => return Ok((result, connection.peer().clone(), input_rounds)),
                Err(error) => {
                    if !should_retry_mcp_operation(
                        &error,
                        attempt,
                        &self.refresh_config,
                        has_connection_factory,
                        replay_allowed,
                    ) {
                        return Err(mcp_tool_call_error(
                            &self.name,
                            &error,
                            has_connection_factory,
                            replay_allowed,
                        ));
                    }

                    let retry_attempt = attempt + 1;
                    if self.refresh_config.log_reconnections {
                        warn!(
                            tool = %self.name,
                            attempt = retry_attempt,
                            max_attempts = self.refresh_config.max_attempts,
                            error = %error,
                            "MCP call_tool failed; reconnecting and retrying"
                        );
                    }

                    if self.refresh_config.retry_delay_ms > 0 {
                        tokio::time::sleep(tokio::time::Duration::from_millis(
                            self.refresh_config.retry_delay_ms,
                        ))
                        .await;
                    }

                    if !self
                        .client
                        .refresh(
                            self.toolset_name(),
                            &connection,
                            self.connection_factory.as_ref(),
                            &self.resource_subscriptions,
                        )
                        .await?
                    {
                        return Err(mcp_tool_call_error(
                            &self.name,
                            &error,
                            has_connection_factory,
                            replay_allowed,
                        ));
                    }
                    attempt += 1;
                }
            }
        }
    }

    /// Answers one MRTR or in-task input batch through the connection's policy.
    async fn fulfill_input(
        &self,
        requests: InputRequests,
    ) -> std::result::Result<InputResponses, String> {
        if requests.is_empty() {
            return Err("the server sent an empty input request batch".to_string());
        }
        if requests.len() > MAX_INPUT_REQUESTS_PER_ROUND {
            return Err(format!(
                "the server sent {} input requests in one round; at most \
                 {MAX_INPUT_REQUESTS_PER_ROUND} are accepted",
                requests.len()
            ));
        }
        match &self.mrtr_handler {
            Some(handler) => handler.fulfill_input_requests(requests).await,
            None => {
                let client = self.client.connection().await;
                super::input::fulfill(&client, requests).await
            }
        }
    }

    async fn send_task_request(
        &self,
        request: ClientRequest,
    ) -> std::result::Result<ServerResult, TaskError> {
        let client = self.client.connection().await;
        client.send_request(request).await.map_err(|error| TaskError::PollFailed(error.to_string()))
    }

    /// Answers task `task_id`'s input requests through `tasks/update`.
    async fn update_task(
        &self,
        task_id: &str,
        responses: InputResponses,
    ) -> std::result::Result<(), TaskError> {
        let request = ClientRequest::UpdateTaskRequest(UpdateTaskRequest::new(
            UpdateTaskParams::new(task_id, responses),
        ));
        match self.send_task_request(request).await? {
            ServerResult::TaskAckResult(_) => Ok(()),
            response => Err(TaskError::PollFailed(format!(
                "tasks/update returned an unexpected response: {response:?}"
            ))),
        }
    }

    /// Requests cancellation once; the pending-task set keeps the task until a
    /// status confirms it.
    async fn cancel_task(&self, task_id: &str) {
        let cancel = async {
            let peer = self.client.connection().await.peer().clone();
            peer.cancel_task(CancelTaskParams::new(task_id)).await
        };
        match tokio::time::timeout(TASK_CANCEL_TIMEOUT, cancel).await {
            Ok(Ok(())) => {}
            // The task already finished or the server dropped it; nothing to cancel.
            Ok(Err(error)) if is_unknown_or_finished_task(&error) => {}
            Ok(Err(error)) => warn!(task_id, error = %error, "failed to cancel MCP task"),
            Err(_) => warn!(
                task_id,
                timeout_ms = TASK_CANCEL_TIMEOUT.as_millis(),
                "MCP server did not acknowledge tasks/cancel"
            ),
        }
    }

    /// Poll a protocol-level MCP task until completion or timeout.
    ///
    /// `call` is the call the task runs, with the input rounds taken so far; `answered` holds
    /// answers to re-send while the server still lists their requests. A call that parks
    /// returns its parked form when the task asks something not yet answered.
    async fn poll_task(
        &self,
        task_id: String,
        poll_interval_ms: Option<u64>,
        mode: InputMode,
        call: ParkedMcpCall,
        mut answered: BTreeMap<String, (InputRequest, Value)>,
    ) -> std::result::Result<McpCallOutcome, TaskError> {
        let mut poll_interval_ms =
            poll_interval_ms.unwrap_or(self.task_config.poll_interval_ms).max(1);
        let start = Instant::now();
        let mut attempts = 0u32;
        let mut input_rounds = call.input_rounds;

        loop {
            if let Some(timeout_ms) = self.task_config.timeout_ms {
                let elapsed = start.elapsed().as_millis() as u64;
                if elapsed >= timeout_ms {
                    self.cancel_task(&task_id).await;
                    return Err(TaskError::Timeout { task_id, elapsed_ms: elapsed });
                }
            }

            if let Some(max_attempts) = self.task_config.max_poll_attempts
                && attempts >= max_attempts
            {
                self.cancel_task(&task_id).await;
                return Err(TaskError::MaxAttemptsExceeded { task_id, attempts });
            }

            tokio::time::sleep(tokio::time::Duration::from_millis(poll_interval_ms)).await;
            attempts += 1;

            debug!(task_id, attempt = attempts, "polling MCP task status");
            let request =
                ClientRequest::GetTaskRequest(GetTaskRequest::new(GetTaskParams::new(&task_id)));
            let detailed = match self.send_task_request(request).await? {
                ServerResult::GetTaskResult(result) => result.task,
                response => {
                    return Err(TaskError::PollFailed(format!(
                        "tasks/get returned an unexpected response: {response:?}"
                    )));
                }
            };
            let (task, payload) = (detailed.task, detailed.payload);
            if task.task_id != task_id {
                return Err(TaskError::PollFailed("MCP task identity changed".into()));
            }
            if task.status.is_terminal() {
                self.active_tasks.lock().await.remove(&task_id);
            }
            poll_interval_ms = task.poll_interval_ms.unwrap_or(poll_interval_ms).max(1);

            match payload {
                // SEP-2663 inlines the result in the status response, so a
                // completed task needs no second round trip.
                TaskPayload::Completed { result } => {
                    debug!(task_id, "MCP task completed successfully");
                    let call_result: rmcp::model::CallToolResult =
                        serde_json::from_value(Value::Object(result)).map_err(|error| {
                            TaskError::PollFailed(format!(
                                "tasks/get returned a result that is not a CallToolResult: {error}"
                            ))
                        })?;
                    if call_result.is_error == Some(true) {
                        debug!(task_id, "MCP task completed with an isError result");
                        return Ok(McpCallOutcome::Completed(server_error_response(
                            &self.name,
                            &call_result,
                        )));
                    }
                    return call_tool_result_to_adk_value(&call_result)
                        .map(McpCallOutcome::Completed)
                        .map_err(TaskError::PollFailed);
                }
                TaskPayload::Failed { error } => {
                    return Err(TaskError::TaskFailed {
                        task_id,
                        error: task
                            .status_message
                            .unwrap_or_else(|| Value::Object(error).to_string()),
                    });
                }
                TaskPayload::Cancelled => {
                    return Err(TaskError::Cancelled(task_id));
                }
                TaskPayload::InputRequired { input_requests } => {
                    if input_requests.is_empty() {
                        return Err(TaskError::PollFailed(format!(
                            "task '{task_id}' reported input_required without any input requests"
                        )));
                    }
                    let mut pending = InputRequests::new();
                    let mut responses = InputResponses::new();
                    for (key, request) in &input_requests {
                        if let Some((previous, response)) = answered.get(key) {
                            if previous != request {
                                return Err(TaskError::PollFailed(format!(
                                    "task '{task_id}' changed input request '{key}' after it \
                                     was answered"
                                )));
                            }
                            responses.insert(key.clone(), response.clone());
                        } else {
                            pending.insert(key.clone(), request.clone());
                        }
                    }
                    // Re-sending cached answers is not a new round of questions.
                    if !pending.is_empty() {
                        input_rounds += 1;
                        if input_rounds > self.task_config.max_input_rounds {
                            return Err(TaskError::PollFailed(format!(
                                "task '{task_id}' exceeded {} input rounds",
                                self.task_config.max_input_rounds
                            )));
                        }
                        let kind = ParkedCallKind::Task { task_id: task_id.clone() };
                        let parked =
                            call.clone().waiting(kind, None, pending.clone(), input_rounds);
                        if mode == InputMode::Park {
                            if !responses.is_empty() {
                                self.update_task(&task_id, responses).await?;
                            }
                            // The task waits for its answers durably; it is no longer this
                            // toolset's to cancel.
                            self.active_tasks.lock().await.remove(&task_id);
                            return Ok(McpCallOutcome::Parked(parked));
                        }
                        let received = parked
                            .within(self.fulfill_input(pending))
                            .await
                            .map_err(TaskError::PollFailed)?;
                        for (key, response) in received {
                            answered.insert(
                                key.clone(),
                                (input_requests[&key].clone(), response.clone()),
                            );
                            responses.insert(key, response);
                        }
                    }
                    self.update_task(&task_id, responses).await?;
                }
                TaskPayload::Working => {
                    debug!(task_id, "MCP task is still working");
                    // The server consumed every answer, so a later key reuse is a new question.
                    answered.clear();
                }
                _ => {
                    return Err(TaskError::PollFailed(
                        "server returned an unsupported MCP task status".to_string(),
                    ));
                }
            }
        }
    }
}

#[async_trait]
impl<S> Tool for McpTool<S>
where
    S: rmcp::service::Service<RoleClient> + Send + Sync + 'static,
{
    fn name(&self) -> &str {
        &self.name
    }

    fn description(&self) -> &str {
        &self.description
    }

    /// SEP-2663 removed the per-tool task contract, so the server decides per
    /// call whether to materialize a task. The remaining signal is therefore
    /// per-connection: any call may return a task when both sides allow it.
    fn is_long_running(&self) -> bool {
        self.task_config.enable_tasks && self.server_supports_tasks
    }

    fn is_read_only(&self) -> bool {
        mcp_tool_effect(self.annotations.as_ref()) == ToolEffect::ReadOnly
    }

    fn is_concurrency_safe(&self) -> bool {
        mcp_tool_effect(self.annotations.as_ref()).is_retry_safe()
    }

    fn effect(&self) -> ToolEffect {
        mcp_tool_effect(self.annotations.as_ref())
    }

    fn annotations(&self) -> Option<&Value> {
        self.annotations_json.as_ref()
    }

    fn origin(&self) -> &str {
        &self.origin
    }

    fn parameters_schema(&self) -> Option<Value> {
        self.input_schema.clone()
    }

    fn response_schema(&self) -> Option<Value> {
        self.output_schema.clone()
    }

    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
        // Sampling requests the server sends while this call is in flight count against the run.
        #[cfg(feature = "mcp-sampling")]
        let _sampling_scope = ctx
            .run_config()
            .map(|config| {
                adk_core::ModelCallScope::for_run(config, ctx.app_name(), ctx.agent_name())
            })
            .filter(|scope| !scope.is_unmetered())
            .map(|scope| self.client.sampling_scopes.enter(scope));
        // Elicitations the server sends while this call is in flight belong to it
        // (spec 3.1 §10 T1).
        let _elicitation_scope = self
            .client
            .elicitation_scopes
            .enter(super::elicitation::ElicitationScope::for_call(ctx.as_ref()));
        let call_id = Some(ctx.function_call_id().to_string()).filter(|id| !id.is_empty());
        #[cfg(feature = "mcp-apps")]
        let record =
            self.ui.as_ref().zip(call_id.clone()).map(|(ui, call_id)| super::apps::McpAppRecord {
                server: self.toolset_name().to_string(),
                tool: self.name.clone(),
                resource_uri: ui.resource_uri.clone(),
                call_id,
            });
        let value = self.execute_value(args, call_id).await?;
        // The call that shows an app says so in its own event, so a host shows the app only
        // for a call this tool made (spec 3.3 §6.1 `genui-apps`).
        #[cfg(feature = "mcp-apps")]
        if let Some(record) = record
            && value.get("error").is_none()
        {
            let mut actions = ctx.actions();
            actions.state_delta.insert(super::apps::MCP_APP_STATE_KEY.to_string(), json!(record));
            ctx.set_actions(actions);
        }
        Ok(value)
    }
}

// McpTool<S> is Send + Sync when S: Send + Sync because all fields are
// composed of Send + Sync primitives (String, Arc<Mutex<_>>, Arc<dyn Send + Sync>, etc.).
// The compiler enforces this through the Tool trait bound (Tool: Send + Sync).
// No unsafe impl needed — the previous unsafe impl was removed as unnecessary.

#[cfg(test)]
mod tests {
    use super::*;

    /// Proves that `McpTool<S>` is `Send + Sync` for any service `S: Send + Sync`
    /// without requiring `unsafe impl`. The compiler rejects this test at build
    /// time if any field breaks the auto-trait derivation.
    ///
    /// This replaced a previous `unsafe impl Send/Sync for McpTool<S>` that was
    /// unnecessary — all fields (String, Arc<Mutex<_>>, Arc<dyn Send+Sync>, bool)
    /// are naturally Send + Sync.
    #[test]
    fn mcp_tool_is_send_and_sync() {
        fn require_send_sync<T: Send + Sync>() {}

        // The compiler proves Send + Sync for McpTool<S> and McpToolset<S> by
        // type-checking these function bodies. If any field were !Send or !Sync,
        // this would be a compile error — no unsafe needed.
        //
        // () satisfies Service<RoleClient> via the ClientHandler blanket impl
        // in rmcp, so this is a valid concrete instantiation.
        require_send_sync::<McpTool<()>>();
        require_send_sync::<McpToolset<()>>();
    }

    fn broken_pipe() -> ServiceError {
        ServiceError::TransportSend(rmcp::transport::DynamicTransportError::from_parts(
            "test",
            std::any::TypeId::of::<()>(),
            Box::new(std::io::Error::new(std::io::ErrorKind::BrokenPipe, "pipe closed")),
        ))
    }

    #[test]
    fn test_should_retry_mcp_operation_reconnectable_errors() {
        let config = RefreshConfig::default().with_max_attempts(3);
        assert!(should_retry_mcp_operation(&ServiceError::TransportClosed, 0, &config, true, true));
        assert!(should_retry_mcp_operation(&broken_pipe(), 1, &config, true, true));
    }

    #[test]
    fn mcp_tool_effect_defaults_to_non_idempotent() {
        assert_eq!(mcp_tool_effect(None), ToolEffect::NonIdempotent);
        assert_eq!(mcp_tool_effect(Some(&ToolAnnotations::default())), ToolEffect::NonIdempotent);
        let destructive = ToolAnnotations::new().destructive(true).idempotent(false);
        assert_eq!(mcp_tool_effect(Some(&destructive)), ToolEffect::NonIdempotent);
    }

    #[test]
    fn mcp_tool_effect_maps_read_only_and_idempotent_hints() {
        let read_only = ToolAnnotations::new().read_only(true).idempotent(true);
        assert_eq!(mcp_tool_effect(Some(&read_only)), ToolEffect::ReadOnly);

        let idempotent = ToolAnnotations::new().idempotent(true);
        assert_eq!(mcp_tool_effect(Some(&idempotent)), ToolEffect::Idempotent);
    }

    #[test]
    fn test_should_retry_mcp_operation_stops_at_max_attempts() {
        let config = RefreshConfig::default().with_max_attempts(2);
        assert!(!should_retry_mcp_operation(
            &ServiceError::TransportClosed,
            2,
            &config,
            true,
            true
        ));
    }

    #[test]
    fn test_should_retry_mcp_operation_requires_factory() {
        let config = RefreshConfig::default().with_max_attempts(3);
        assert!(!should_retry_mcp_operation(
            &ServiceError::TransportClosed,
            0,
            &config,
            false,
            true
        ));
    }

    #[test]
    fn test_should_retry_mcp_operation_non_reconnectable_error() {
        let config = RefreshConfig::default().with_max_attempts(3);
        let invalid = ServiceError::McpError(rmcp::ErrorData::invalid_params(
            "invalid arguments for tool; EOF",
            None,
        ));
        assert!(!should_retry_mcp_operation(&invalid, 0, &config, true, true));
    }

    /// The default must stay off.
    ///
    /// The opt-in *is* the security boundary of #504. The other tests pass `false` explicitly,
    /// so they verify the gate honours the flag but not that the flag starts closed — flipping
    /// every constructor to `true` left the whole suite green. This is the guard for that.
    #[test]
    fn tool_call_replay_is_disabled_by_default() {
        let config = RefreshConfig::default();
        assert!(
            !should_retry_mcp_operation(
                &ServiceError::TransportClosed,
                0,
                &config,
                true,
                DEFAULT_RETRY_TOOL_CALLS
            ),
            "a connection-level error must not replay tools/call under the default; see #504"
        );
    }

    #[test]
    fn test_should_retry_mcp_operation_requires_explicit_replay() {
        let config = RefreshConfig::default().with_max_attempts(3);
        assert!(!should_retry_mcp_operation(&broken_pipe(), 0, &config, true, false));
    }

    #[test]
    fn test_ambiguous_tool_call_error_explains_no_replay() {
        let error =
            mcp_tool_call_error("create_record", &ServiceError::TransportClosed, true, false);
        let message = error.to_string();
        assert!(message.contains("result is uncertain and was not replayed"));
        assert!(message.contains("replay-safe operations"));
    }

    #[test]
    fn mcp_result_preserves_structured_text_and_image_content() {
        let mut result = rmcp::model::CallToolResult::success(vec![
            rmcp::model::ContentBlock::text("observation"),
            rmcp::model::ContentBlock::image(STANDARD.encode([1_u8, 2, 3]), "image/png"),
        ]);
        result.structured_content = Some(json!({ "observation_id": "obs-1" }));

        let value = call_tool_result_to_adk_value(&result).unwrap();
        let response = adk_core::FunctionResponseData::from_tool_result("screenshot", value);

        assert_eq!(
            response.response,
            json!({ "output": { "observation_id": "obs-1" }, "text": ["observation"] })
        );
        assert_eq!(response.inline_data.len(), 1);
        assert_eq!(response.inline_data[0].mime_type, "image/png");
        assert_eq!(response.inline_data[0].data, vec![1, 2, 3]);
    }

    /// Publishes a fixed tool catalog over `tools/list`.
    #[derive(Clone)]
    struct CatalogServer(Vec<rmcp::model::Tool>);

    impl rmcp::ServerHandler for CatalogServer {
        fn get_info(&self) -> rmcp::model::InitializeResult {
            rmcp::model::InitializeResult::new(
                rmcp::model::ServerCapabilities::builder().enable_tools().build(),
            )
        }

        async fn list_tools(
            &self,
            _params: Option<rmcp::model::PaginatedRequestParams>,
            _context: rmcp::service::RequestContext<rmcp::RoleServer>,
        ) -> std::result::Result<rmcp::model::ListToolsResult, rmcp::ErrorData> {
            Ok(rmcp::model::ListToolsResult::with_all_items(self.0.clone()))
        }
    }

    /// Runs discovery against `catalog` over an in-process pipe.
    async fn discover(
        catalog: Vec<rmcp::model::Tool>,
        limits: McpSchemaLimits,
    ) -> Vec<Arc<dyn Tool>> {
        use rmcp::ServiceExt;

        let (server_io, client_io) = tokio::io::duplex(4096);
        tokio::spawn(async move {
            if let Ok(running) = CatalogServer(catalog).serve(server_io).await {
                let _ = running.waiting().await;
            }
        });
        let client = ().serve(client_io).await.unwrap();
        let toolset = McpToolset::new(client).with_name("catalog").with_schema_limits(limits);
        let ctx = Arc::new(crate::SimpleToolContext::new("schema-limits-test"));
        toolset.tools(ctx).await.unwrap()
    }

    fn schema_object(value: Value) -> serde_json::Map<String, Value> {
        match value {
            Value::Object(map) => map,
            other => panic!("expected a JSON object, got {other}"),
        }
    }

    fn small_schema() -> serde_json::Map<String, Value> {
        schema_object(json!({
            "type": "object",
            "properties": { "id": { "type": "string" } },
            "required": ["id"]
        }))
    }

    #[tokio::test]
    async fn discovery_skips_oversized_schemas_and_registers_the_other_tools() {
        let long_text = "x".repeat(300 * 1024);
        let wide: serde_json::Map<String, Value> =
            (0..6_000).map(|index| (format!("p{index}"), json!({ "type": "string" }))).collect();
        let output = schema_object(json!({ "type": "object" }));
        let catalog = vec![
            rmcp::model::Tool::new("before", "Valid.", small_schema()),
            rmcp::model::Tool::new(
                "long_string",
                "Input schema over the byte limit.",
                schema_object(json!({ "type": "object", "description": long_text })),
            ),
            rmcp::model::Tool::new(
                "wide",
                "Input schema over the node limit.",
                schema_object(json!({ "type": "object", "properties": wide })),
            ),
            rmcp::model::Tool::new(
                "long_output",
                "Output schema over the byte limit.",
                small_schema(),
            )
            .with_raw_output_schema(Arc::new(schema_object(json!({ "description": long_text })))),
            rmcp::model::Tool::new("after", "Valid.", small_schema())
                .with_raw_output_schema(Arc::new(output.clone())),
        ];

        let tools = discover(catalog, McpSchemaLimits::default()).await;

        let registered: Vec<_> = tools
            .iter()
            .map(|tool| (tool.name(), tool.parameters_schema(), tool.response_schema()))
            .collect();
        assert_eq!(
            registered,
            vec![
                ("before", Some(Value::Object(small_schema())), None),
                ("after", Some(Value::Object(small_schema())), Some(Value::Object(output))),
            ]
        );
    }

    #[tokio::test]
    async fn discovery_accepts_a_schema_exactly_at_the_configured_limits() {
        let schema = small_schema();
        let bytes = serde_json::to_string(&schema).unwrap().len();
        // The root, "type", "properties", the "id" object and its "type", "required", "id".
        let nodes = 7;
        let catalog = vec![rmcp::model::Tool::new("lookup", "Valid.", schema)];
        let at = McpSchemaLimits::default().with_max_bytes(bytes).with_max_nodes(nodes);

        let names = |tools: Vec<Arc<dyn Tool>>| {
            tools.iter().map(|tool| tool.name().to_string()).collect::<Vec<_>>()
        };
        assert_eq!(names(discover(catalog.clone(), at).await), vec!["lookup"]);
        assert!(discover(catalog.clone(), at.with_max_bytes(bytes - 1)).await.is_empty());
        assert!(discover(catalog, at.with_max_nodes(nodes - 1)).await.is_empty());
    }

    #[test]
    fn an_is_error_result_keeps_its_text_for_the_model() {
        let result = rmcp::model::CallToolResult::error(vec![
            ContentBlock::text("order IDs look like ORD-1234"),
            ContentBlock::text("retry with ORD-7781"),
        ]);
        assert_eq!(
            server_error_response("lookup", &result),
            json!({ "error": "order IDs look like ORD-1234\nretry with ORD-7781" })
        );

        let mut structured = rmcp::model::CallToolResult::error(vec![]);
        structured.structured_content = Some(json!({ "field": "order_id" }));
        assert_eq!(
            server_error_response("lookup", &structured),
            json!({ "error": "{\"field\":\"order_id\"}" })
        );

        let empty = rmcp::model::CallToolResult::error(vec![]);
        assert_eq!(
            server_error_response("lookup", &empty),
            json!({ "error": "MCP tool 'lookup' reported an error without a message" })
        );
    }

    #[test]
    fn an_is_error_text_over_the_limit_is_cut_at_a_character_boundary() {
        let result = rmcp::model::CallToolResult::error(vec![ContentBlock::text(
            "é".repeat(MAX_SERVER_ERROR_BYTES),
        )]);
        let response = server_error_response("lookup", &result);
        let text = response["error"].as_str().unwrap();
        let kept = text.strip_suffix(" [truncated]").expect("a truncation marker");
        assert!(kept.len() <= MAX_SERVER_ERROR_BYTES);
        assert!(kept.chars().all(|c| c == 'é'));
    }

    #[test]
    fn a_successful_result_without_content_is_an_empty_output() {
        let result = rmcp::model::CallToolResult::success(vec![]);
        assert_eq!(call_tool_result_to_adk_value(&result), Ok(json!({ "output": "" })));
    }

    #[tokio::test]
    async fn discovery_truncates_descriptions_over_the_limit_and_keeps_the_tool() {
        let catalog = vec![
            rmcp::model::Tool::new("huge", "é".repeat(600_000), small_schema()),
            rmcp::model::Tool::new("short", "Valid.", small_schema()),
        ];

        let tools = discover(catalog, McpSchemaLimits::default()).await;

        let registered: Vec<_> = tools
            .iter()
            .map(|tool| (tool.name().to_string(), tool.description().to_string()))
            .collect();
        assert_eq!(
            registered,
            vec![
                (
                    "huge".to_string(),
                    "é".repeat(McpSchemaLimits::DEFAULT_MAX_DESCRIPTION_BYTES / 2)
                ),
                ("short".to_string(), "Valid.".to_string()),
            ]
        );
    }

    #[test]
    fn mcp_result_rejects_invalid_image_base64() {
        let result = rmcp::model::CallToolResult::success(vec![rmcp::model::ContentBlock::image(
            "not-base64!",
            "image/png",
        )]);
        assert!(call_tool_result_to_adk_value(&result).is_err());
    }

    #[tokio::test]
    async fn discovery_skips_repeated_and_unroutable_names_and_keeps_the_rest() {
        let long = |suffix: &str| format!("{}{suffix}", "n".repeat(64));
        let catalog = vec![
            rmcp::model::Tool::new("dup", "First.", small_schema()),
            rmcp::model::Tool::new("dup", "Second.", small_schema()),
            rmcp::model::Tool::new("line\nbreak\u{1b}[31m", "Control characters.", small_schema()),
            rmcp::model::Tool::new("", "Empty.", small_schema()),
            rmcp::model::Tool::new(long("_a"), "Long a.", small_schema()),
            rmcp::model::Tool::new(long("_b"), "Long b.", small_schema()),
            rmcp::model::Tool::new("n".repeat(64), "Exactly 64 bytes.", small_schema()),
            rmcp::model::Tool::new("lookup", "Valid.", small_schema()),
        ];

        let tools = discover(catalog, McpSchemaLimits::default()).await;

        let registered: Vec<_> = tools
            .iter()
            .map(|tool| (tool.name().to_string(), tool.description().to_string()))
            .collect();
        assert_eq!(
            registered,
            vec![
                ("dup".to_string(), "First.".to_string()),
                ("n".repeat(64), "Exactly 64 bytes.".to_string()),
                ("lookup".to_string(), "Valid.".to_string()),
            ]
        );
    }

    #[tokio::test]
    async fn discovered_tools_carry_their_effect_and_annotations() {
        let annotated = |name: &str, hints: ToolAnnotations| {
            rmcp::model::Tool::new(name.to_string(), "Annotated.", small_schema()).annotate(hints)
        };
        let catalog = vec![
            annotated(
                "set_thermostat",
                ToolAnnotations::with_title("Set thermostat")
                    .idempotent(true)
                    .destructive(false)
                    .open_world(false),
            ),
            annotated("read_temperature", ToolAnnotations::new().read_only(true)),
            annotated("delete_logs", ToolAnnotations::new().destructive(true)),
            rmcp::model::Tool::new("plain", "No annotations.", small_schema()),
        ];

        let tools = discover(catalog, McpSchemaLimits::default()).await;

        let described: Vec<_> = tools
            .iter()
            .map(|tool| {
                (
                    tool.name(),
                    tool.effect(),
                    tool.is_read_only(),
                    tool.is_concurrency_safe(),
                    tool.annotations().cloned(),
                )
            })
            .collect();
        assert_eq!(
            described,
            vec![
                (
                    "set_thermostat",
                    ToolEffect::Idempotent,
                    false,
                    true,
                    Some(json!({
                        "title": "Set thermostat",
                        "idempotentHint": true,
                        "destructiveHint": false,
                        "openWorldHint": false
                    })),
                ),
                (
                    "read_temperature",
                    ToolEffect::ReadOnly,
                    true,
                    true,
                    Some(json!({ "readOnlyHint": true }))
                ),
                (
                    "delete_logs",
                    ToolEffect::NonIdempotent,
                    false,
                    false,
                    Some(json!({ "destructiveHint": true })),
                ),
                ("plain", ToolEffect::NonIdempotent, false, false, None),
            ]
        );
    }

    /// Counts `tools/call` requests so a refused call can be shown never to reach the server.
    #[derive(Clone, Default)]
    struct CallCounter(Arc<std::sync::atomic::AtomicUsize>);

    impl rmcp::ServerHandler for CallCounter {
        fn get_info(&self) -> rmcp::model::InitializeResult {
            rmcp::model::InitializeResult::new(
                rmcp::model::ServerCapabilities::builder().enable_tools().build(),
            )
        }

        async fn call_tool(
            &self,
            params: CallToolRequestParams,
            _context: rmcp::service::RequestContext<rmcp::RoleServer>,
        ) -> std::result::Result<CallToolResponse, rmcp::ErrorData> {
            self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Ok(rmcp::model::CallToolResult::success(vec![ContentBlock::text(
                params.name.to_string(),
            )])
            .into())
        }
    }

    /// Answers every call with `isError` and guidance for the model.
    #[derive(Clone)]
    struct Refusing;

    impl rmcp::ServerHandler for Refusing {
        fn get_info(&self) -> rmcp::model::InitializeResult {
            rmcp::model::InitializeResult::new(
                rmcp::model::ServerCapabilities::builder().enable_tools().build(),
            )
        }

        async fn list_tools(
            &self,
            _params: Option<rmcp::model::PaginatedRequestParams>,
            _context: rmcp::service::RequestContext<rmcp::RoleServer>,
        ) -> std::result::Result<rmcp::model::ListToolsResult, rmcp::ErrorData> {
            Ok(rmcp::model::ListToolsResult::with_all_items(vec![rmcp::model::Tool::new(
                "lookup",
                "Looks up an order.",
                small_schema(),
            )]))
        }

        async fn call_tool(
            &self,
            _params: CallToolRequestParams,
            _context: rmcp::service::RequestContext<rmcp::RoleServer>,
        ) -> std::result::Result<CallToolResponse, rmcp::ErrorData> {
            Ok(rmcp::model::CallToolResult::error(vec![ContentBlock::text(
                "order 7781 moved; call lookup with id MIG-7781",
            )])
            .into())
        }
    }

    #[tokio::test]
    async fn a_server_is_error_result_is_the_tools_response() {
        use rmcp::ServiceExt;

        let (server_io, client_io) = tokio::io::duplex(4096);
        tokio::spawn(async move {
            if let Ok(running) = Refusing.serve(server_io).await {
                let _ = running.waiting().await;
            }
        });
        let toolset = McpToolset::new(().serve(client_io).await.unwrap()).with_name("orders");
        let ctx = Arc::new(crate::SimpleToolContext::new("is-error-test"));
        let tools = toolset.tools(ctx.clone()).await.unwrap();

        let response = tools[0].execute(ctx, json!({ "id": "7781" })).await.unwrap();
        assert_eq!(response, json!({ "error": "order 7781 moved; call lookup with id MIG-7781" }));
    }

    #[tokio::test]
    async fn call_tool_value_refuses_a_tool_the_filter_excludes() {
        use rmcp::ServiceExt;

        let server = CallCounter::default();
        let calls = Arc::clone(&server.0);
        let (server_io, client_io) = tokio::io::duplex(4096);
        tokio::spawn(async move {
            if let Ok(running) = server.serve(server_io).await {
                let _ = running.waiting().await;
            }
        });
        let toolset = McpToolset::new(().serve(client_io).await.unwrap())
            .with_name("filtered")
            .with_tools(&["public"]);

        let refused = toolset.call_tool_value("secret", Default::default()).await.unwrap_err();
        assert!(refused.to_string().contains("excluded by the tool filter"), "{refused}");
        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0);

        let allowed = toolset.call_tool_value("public", Default::default()).await.unwrap();
        assert_eq!(allowed, json!({ "output": "public" }));
        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
    }
}