tower-mcp 0.18.0

Tower-native Model Context Protocol (MCP) implementation
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
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
//! MCP Client with bidirectional communication support.
//!
//! Provides [`McpClient`] for connecting to MCP servers over any
//! [`ClientTransport`]. The client runs a background message loop that
//! handles request/response correlation, server-initiated requests
//! (sampling, elicitation, roots), and notifications.
//!
//! See [`crate::guides::client`] for transport selection, lifecycle setup,
//! callbacks, common requests, caching, retry policy, and shutdown guidance.
//!
//! # Example
//!
//! ```rust,no_run
//! use tower_mcp::client::{McpClient, StdioClientTransport};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), tower_mcp::BoxError> {
//!     let transport = StdioClientTransport::spawn("my-mcp-server", &["--flag"]).await?;
//!     let client = McpClient::connect(transport).await?;
//!
//!     let server_info = client.initialize("my-client", "1.0.0").await?;
//!     println!("Connected to: {}", server_info.server_info.name);
//!
//!     let tools = client.list_tools().await?;
//!     for tool in &tools.tools {
//!         println!("Tool: {}", tool.name);
//!     }
//!
//!     let result = client.call_tool("my-tool", serde_json::json!({"arg": "value"})).await?;
//!     println!("Result: {:?}", result);
//!
//!     Ok(())
//! }
//! ```

mod channel;
mod handler;
#[cfg(feature = "http-client")]
mod http;
#[cfg(feature = "oauth-client")]
mod oauth;
#[cfg(feature = "oauth-client")]
mod oauth_authcode;
#[cfg(feature = "oauth-client")]
mod oauth_flow;
mod response_cache;
mod stdio;
mod transport;

pub use channel::ChannelTransport;
pub use handler::{ClientHandler, NotificationHandler, ServerNotification};
#[cfg(feature = "http-client")]
pub use http::{HttpClientConfig, HttpClientTransport};
#[cfg(feature = "oauth-client")]
pub use oauth::{
    OAuthBearerChallenge, OAuthClientCredentials, OAuthClientCredentialsBuilder, OAuthClientError,
    OAuthScopeChallenge, OAuthScopeEscalationConfig, OAuthScopeEscalationHandler,
    OAuthScopeEscalationRequest, OAuthTokenEndpointAuthMethod, TokenProvider,
};
#[cfg(feature = "oauth-client")]
pub use oauth_authcode::{
    MemoryOAuthClientRegistrationStore, OAuthApplicationType, OAuthAuthCodeConfig,
    OAuthAuthorizationCode, OAuthAuthorizationDiscovery, OAuthAuthorizationServerMetadata,
    OAuthClientRegistration, OAuthClientRegistrationMethod, OAuthClientRegistrationOptions,
    OAuthClientRegistrationStore, OAuthDynamicClientRegistration, OAuthProtectedResourceMetadata,
    discover_oauth_authorization, discover_oauth_authorization_server,
    probe_oauth_bearer_challenge, resolve_oauth_client_registration,
    resolve_oauth_client_registration_with_store,
};
#[cfg(feature = "oauth-client")]
pub use oauth_flow::{
    MemoryOAuthAuthorizationStateStore, MemoryOAuthTokenStore, OAuthAuthorizationAction,
    OAuthAuthorizationFlow, OAuthAuthorizationFlowBuilder, OAuthAuthorizationHandler,
    OAuthAuthorizationRequest, OAuthAuthorizationStart, OAuthAuthorizationStateStore,
    OAuthClientAssertionRequest, OAuthClientAssertionSigner, OAuthHttpBody, OAuthHttpClient,
    OAuthHttpMethod, OAuthHttpRequest, OAuthHttpResponse, OAuthPendingAuthorization,
    OAuthPendingAuthorizationState, OAuthRedirectPolicy, OAuthStoredToken, OAuthTokenBinding,
    OAuthTokenStore, ReqwestOAuthHttpClient,
};
pub use response_cache::{ClientCacheConfig, DEFAULT_MAX_CACHE_TTL};
pub use stdio::StdioClientTransport;
pub use transport::ClientTransport;

use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};

use tokio::sync::{Mutex, RwLock, mpsc, oneshot};
use tokio::task::JoinHandle;

use crate::ProtocolSupport;
use crate::error::{Error, ErrorCode, McpErrorCode, Result};
#[cfg(any(feature = "protocol-2026-07-28", feature = "stateless"))]
use crate::protocol::DiscoverParams;
use crate::protocol::{
    CacheScope, CallToolParams, CallToolResult, CancelTaskParams, CancelledParams,
    ClientCapabilities, CompleteParams, CompleteResult, CompletionArgument, CompletionReference,
    CreateTaskResult, DiscoverResult, ElicitationCapability, GetPromptParams, GetPromptResult,
    GetTaskInfoParams, Implementation, InitializeParams, InitializeResult, InputRequest,
    InputRequests, InputResponse, InputResponses, JsonRpcNotification, JsonRpcRequest,
    ListPromptsParams, ListPromptsResult, ListResourceTemplatesParams, ListResourceTemplatesResult,
    ListResourcesParams, ListResourcesResult, ListRootsResult, ListToolsParams, ListToolsResult,
    PromptDefinition, ReadResourceParams, ReadResourceResult, RequestId, RequestMeta,
    RequestOutcome, ResourceDefinition, ResourceTemplateDefinition, Root, RootsCapability,
    SamplingCapability, SubscriptionFilter, SubscriptionsAcknowledgedParams,
    SubscriptionsListenParams, SubscriptionsListenResult, TaskObject, TaskRequestParams,
    TaskStatusParams, ToolDefinition, UpdateTaskParams, notifications,
};
use response_cache::{CacheLookup, ClientResponseCache};
use tower_mcp_types::JsonRpcError;

/// One response to a final-protocol `tools/call` request.
///
/// Task creation is server-directed in SEP-2663, so a client that declares
/// the Tasks extension must be prepared for an ordinary tool call to return a
/// task handle. [`McpClient::call_tool`] drives that task transparently;
/// [`McpClient::call_tool_once_task_aware`] exposes this enum for callers that
/// want direct control of the lifecycle.
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(untagged)]
#[non_exhaustive]
pub enum TaskAwareCallToolOutcome {
    /// The server elected to create a task.
    Task(crate::tasks::CreateTaskResult),
    /// The request completed synchronously.
    Complete(CallToolResult),
    /// The request needs one or more client inputs before it can complete.
    InputRequired(crate::protocol::InputRequiredResult),
}

trait CacheableResponse:
    Clone + serde::Serialize + serde::de::DeserializeOwned + Send + Sync + 'static
{
    fn ttl_ms(&self) -> Option<u64>;
    fn cache_scope(&self) -> Option<CacheScope>;
}

macro_rules! impl_cacheable_response {
    ($($ty:ty),+ $(,)?) => {
        $(
            impl CacheableResponse for $ty {
                fn ttl_ms(&self) -> Option<u64> {
                    self.ttl_ms
                }

                fn cache_scope(&self) -> Option<CacheScope> {
                    self.cache_scope
                }
            }
        )+
    };
}

impl_cacheable_response!(
    DiscoverResult,
    ListToolsResult,
    ListResourcesResult,
    ListResourceTemplatesResult,
    ListPromptsResult,
    ReadResourceResult,
);

/// Internal command sent from McpClient methods to the background loop.
enum LoopCommand {
    /// Send a JSON-RPC request and await a response.
    Request {
        method: String,
        params: serde_json::Value,
        response_tx: oneshot::Sender<Result<serde_json::Value>>,
    },
    /// Open a long-lived `subscriptions/listen` request and return its ID.
    StartSubscription {
        params: serde_json::Value,
        id_tx: oneshot::Sender<RequestId>,
        acknowledgment_tx: oneshot::Sender<SubscriptionFilter>,
        response_tx: oneshot::Sender<Result<serde_json::Value>>,
    },
    /// Cancel one active subscription request.
    CancelRequest {
        request_id: RequestId,
        done_tx: Option<oneshot::Sender<Result<()>>>,
    },
    /// Send a JSON-RPC notification (no response expected).
    Notify {
        method: String,
        params: serde_json::Value,
    },
    /// Reset the transport's session state for re-initialization.
    ResetSession { done_tx: oneshot::Sender<()> },
    /// Fulfil embedded MRTR requests through the configured client handler.
    ResolveInputs {
        requests: InputRequests,
        response_tx: oneshot::Sender<Result<InputResponses>>,
    },
    /// Graceful shutdown.
    Shutdown,
}

/// An active `subscriptions/listen` request.
///
/// The handle exposes the JSON-RPC request ID used as the subscription ID,
/// the server's acknowledged filter, graceful server completion, and explicit
/// cancellation. Dropping an active handle requests cancellation on a
/// best-effort basis; callers that need confirmation should call
/// [`cancel()`](Self::cancel).
#[must_use = "dropping the handle cancels the active subscription"]
pub struct SubscriptionHandle {
    request_id: RequestId,
    command_tx: mpsc::Sender<LoopCommand>,
    acknowledgment_rx: Option<oneshot::Receiver<SubscriptionFilter>>,
    response_rx: Option<oneshot::Receiver<Result<serde_json::Value>>>,
    active: bool,
}

impl SubscriptionHandle {
    /// The JSON-RPC request ID that identifies this subscription.
    pub fn id(&self) -> &RequestId {
        &self.request_id
    }

    /// Wait for the server's mandatory first-message acknowledgment.
    ///
    /// The returned filter is the subset the server agreed to honor.
    pub async fn acknowledged(&mut self) -> Result<SubscriptionFilter> {
        let receiver = self.acknowledgment_rx.take().ok_or_else(|| {
            Error::Transport("subscription acknowledgment was already consumed".to_string())
        })?;
        receiver
            .await
            .map_err(|_| Error::Transport("subscription ended before acknowledgment".to_string()))
    }

    /// Wait for the server to end the subscription gracefully.
    ///
    /// An HTTP disconnect without a terminal response is reported as a
    /// transport error. Dropping this future drops the handle and cancels the
    /// subscription.
    pub async fn wait(mut self) -> Result<SubscriptionsListenResult> {
        let receiver = self.response_rx.take().ok_or_else(|| {
            Error::Transport("subscription result was already consumed".to_string())
        })?;
        let value = receiver
            .await
            .map_err(|_| Error::Transport("connection closed".to_string()))??;
        self.active = false;
        let result: SubscriptionsListenResult = serde_json::from_value(value).map_err(|error| {
            Error::Transport(format!(
                "failed to deserialize subscriptions/listen response: {error}"
            ))
        })?;
        if !result.result_type.is_complete() {
            return Err(Error::Transport(format!(
                "subscriptions/listen ended with unexpected result type {:?}",
                result.result_type
            )));
        }
        if !request_ids_match(&result.meta.subscription_id, &self.request_id) {
            return Err(Error::Transport(
                "subscriptions/listen result carried the wrong subscription ID".to_string(),
            ));
        }
        Ok(result)
    }

    /// Cancel the subscription and wait until its transport stream is closed.
    pub async fn cancel(mut self) -> Result<()> {
        let (done_tx, done_rx) = oneshot::channel();
        self.command_tx
            .send(LoopCommand::CancelRequest {
                request_id: self.request_id.clone(),
                done_tx: Some(done_tx),
            })
            .await
            .map_err(|_| Error::Transport("connection closed".to_string()))?;
        let result = done_rx
            .await
            .map_err(|_| Error::Transport("connection closed".to_string()))?;
        self.active = false;
        result
    }
}

impl Drop for SubscriptionHandle {
    fn drop(&mut self) {
        if self.active {
            let _ = self.command_tx.try_send(LoopCommand::CancelRequest {
                request_id: self.request_id.clone(),
                done_tx: None,
            });
        }
    }
}

/// MCP client with a background message loop.
///
/// Unlike previous versions, this type is not generic over the transport.
/// The transport is consumed during [`connect()`](Self::connect) and moved
/// into a background Tokio task that handles message multiplexing.
///
/// All public methods take `&self`, enabling concurrent use from multiple
/// tasks.
///
/// # Construction
///
/// ```rust,no_run
/// use tower_mcp::client::{McpClient, StdioClientTransport};
///
/// # async fn example() -> Result<(), tower_mcp::BoxError> {
/// // Simple: no handler for server-initiated requests
/// let transport = StdioClientTransport::spawn("server", &[]).await?;
/// let client = McpClient::connect(transport).await?;
///
/// // With configuration
/// use tower_mcp::protocol::Root;
/// let transport = StdioClientTransport::spawn("server", &[]).await?;
/// let client = McpClient::builder()
///     .with_roots(vec![Root::new("file:///project")])
///     .connect_simple(transport)
///     .await?;
/// # Ok(())
/// # }
/// ```
pub struct McpClient {
    /// Channel to send commands to the background loop.
    command_tx: mpsc::Sender<LoopCommand>,
    /// Background task handle.
    task: Option<JoinHandle<()>>,
    /// Whether `initialize()` has been called successfully.
    initialized: AtomicBool,
    /// Server info (set after successful initialization).
    server_info: RwLock<Option<InitializeResult>>,
    /// Client capabilities declared during initialization.
    capabilities: ClientCapabilities,
    /// Exact ordered set of protocol implementations enabled for this client.
    protocol_support: ProtocolSupport,
    /// Protocol selected by the discover-based final lifecycle.
    selected_protocol_version: RwLock<Option<String>>,
    /// Client identity repeated in final-protocol request metadata.
    client_info: RwLock<Option<Implementation>>,
    /// Server discovery result, when the final lifecycle is active.
    discovery: RwLock<Option<DiscoverResult>>,
    /// Current roots (shared with the loop for roots/list responses).
    roots: Arc<RwLock<Vec<Root>>>,
    /// Whether the transport is still connected.
    connected: Arc<AtomicBool>,
    /// Whether the transport supports session recovery.
    supports_session_recovery: bool,
    /// Stored init params for session recovery re-initialization.
    init_params: RwLock<Option<(String, String)>>,
    /// Lock to prevent concurrent session recovery attempts.
    recovery_lock: Mutex<()>,
    /// Maximum number of input-required rounds auto-driven per operation.
    max_mrtr_rounds: usize,
    /// SEP-2549 final-protocol response cache.
    response_cache: Arc<ClientResponseCache>,
}

/// Builder for configuring and connecting an [`McpClient`].
///
/// # Example
///
/// ```rust,no_run
/// use tower_mcp::client::{McpClient, StdioClientTransport};
/// use tower_mcp::protocol::Root;
///
/// # async fn example() -> Result<(), tower_mcp::BoxError> {
/// let transport = StdioClientTransport::spawn("server", &[]).await?;
/// let handler = (); // Use a real ClientHandler for bidirectional support
/// let client = McpClient::builder()
///     .with_roots(vec![Root::new("file:///project")])
///     .with_sampling()
///     .connect(transport, handler)
///     .await?;
/// # Ok(())
/// # }
/// ```
pub struct McpClientBuilder {
    capabilities: ClientCapabilities,
    roots: Vec<Root>,
    protocol_support: ProtocolSupport,
    max_mrtr_rounds: usize,
    cache_config: ClientCacheConfig,
}

impl McpClientBuilder {
    /// Create a new builder with default settings.
    pub fn new() -> Self {
        Self {
            capabilities: ClientCapabilities::default(),
            roots: Vec::new(),
            // Merely compiling an opt-in implementation must not move an existing
            // client off the established initialize/session path.
            protocol_support: ProtocolSupport::stable(),
            max_mrtr_rounds: 8,
            cache_config: ClientCacheConfig::default(),
        }
    }

    /// Configure roots for this client.
    ///
    /// The client will declare roots support during initialization and
    /// respond to `roots/list` requests with these roots.
    pub fn with_roots(mut self, roots: Vec<Root>) -> Self {
        self.roots = roots;
        self.capabilities.roots = Some(RootsCapability {
            list_changed: true,
            deprecated: None,
        });
        self
    }

    /// Configure custom capabilities for this client.
    pub fn with_capabilities(mut self, capabilities: ClientCapabilities) -> Self {
        self.capabilities = capabilities;
        self
    }

    /// Add one validated MCP protocol-extension declaration.
    ///
    /// Repeated declarations for the same identifier use last-write-wins
    /// semantics. Other configured capabilities are preserved.
    pub fn with_protocol_extension(mut self, extension: crate::ExtensionDeclaration) -> Self {
        let (identifier, settings) = extension.into_parts();
        self.capabilities
            .extensions
            .get_or_insert_default()
            .insert(identifier, settings);
        self
    }

    /// Set the exact ordered protocol versions enabled for this client.
    ///
    /// The default is [`ProtocolSupport::stable`], even when the opt-in final
    /// protocol implementation was compiled. Applications select
    /// 2026-07-28 explicitly and then call `McpClient::discover`.
    pub fn protocol_support(mut self, support: ProtocolSupport) -> Self {
        self.protocol_support = support;
        self
    }

    /// Bound the number of MRTR rounds automatically followed for one request.
    ///
    /// Zero is normalized to one. The default is eight rounds.
    pub fn max_mrtr_rounds(mut self, rounds: usize) -> Self {
        self.max_mrtr_rounds = rounds.max(1);
        self
    }

    /// Configure the SEP-2549 final-protocol response cache.
    pub fn response_cache(mut self, config: ClientCacheConfig) -> Self {
        self.cache_config = config;
        self
    }

    /// Disable the SEP-2549 response cache.
    pub fn disable_response_cache(mut self) -> Self {
        self.cache_config.enabled = false;
        self
    }

    /// Declare sampling support.
    ///
    /// Sets the sampling capability so the server knows this client can
    /// handle `sampling/createMessage` requests. The handler passed to
    /// [`connect()`](Self::connect) should override
    /// [`handle_create_message()`](ClientHandler::handle_create_message).
    pub fn with_sampling(mut self) -> Self {
        self.capabilities.sampling = Some(SamplingCapability::default());
        self
    }

    /// Declare elicitation support.
    ///
    /// Sets the elicitation capability so the server knows this client can
    /// handle `elicitation/create` requests. The handler passed to
    /// [`connect()`](Self::connect) should override
    /// [`handle_elicit()`](ClientHandler::handle_elicit).
    pub fn with_elicitation(mut self) -> Self {
        self.capabilities.elicitation = Some(ElicitationCapability::default());
        self
    }

    /// Connect to a server using the given transport and handler.
    ///
    /// Spawns a background task to handle message I/O. The transport is
    /// consumed and owned by the background task.
    pub async fn connect<T, H>(self, transport: T, handler: H) -> Result<McpClient>
    where
        T: ClientTransport,
        H: ClientHandler,
    {
        McpClient::connect_inner(
            transport,
            handler,
            self.capabilities,
            self.roots,
            self.protocol_support,
            self.max_mrtr_rounds,
            self.cache_config,
        )
        .await
    }

    /// Connect to a server without a handler.
    ///
    /// All server-initiated requests will be rejected with `method_not_found`.
    pub async fn connect_simple<T: ClientTransport>(self, transport: T) -> Result<McpClient> {
        self.connect(transport, ()).await
    }
}

impl Default for McpClientBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl McpClient {
    /// Connect with default settings and no handler.
    ///
    /// Shorthand for `McpClient::builder().connect_simple(transport)`.
    pub async fn connect<T: ClientTransport>(transport: T) -> Result<Self> {
        McpClientBuilder::new().connect_simple(transport).await
    }

    /// Connect with a handler for server-initiated requests.
    pub async fn connect_with_handler<T, H>(transport: T, handler: H) -> Result<Self>
    where
        T: ClientTransport,
        H: ClientHandler,
    {
        McpClientBuilder::new().connect(transport, handler).await
    }

    /// Create a builder for advanced configuration.
    pub fn builder() -> McpClientBuilder {
        McpClientBuilder::new()
    }

    /// Internal connect implementation.
    async fn connect_inner<T, H>(
        transport: T,
        handler: H,
        capabilities: ClientCapabilities,
        roots: Vec<Root>,
        protocol_support: ProtocolSupport,
        max_mrtr_rounds: usize,
        cache_config: ClientCacheConfig,
    ) -> Result<Self>
    where
        T: ClientTransport,
        H: ClientHandler,
    {
        let supports_session_recovery = transport.supports_session_recovery();
        let (command_tx, command_rx) = mpsc::channel::<LoopCommand>(64);
        let connected = Arc::new(AtomicBool::new(true));
        let roots = Arc::new(RwLock::new(roots));
        let response_cache = ClientResponseCache::new(cache_config);

        let loop_connected = connected.clone();
        let loop_roots = roots.clone();
        let loop_response_cache = response_cache.clone();

        let task = tokio::spawn(async move {
            message_loop(
                transport,
                handler,
                command_rx,
                loop_connected,
                loop_roots,
                loop_response_cache,
            )
            .await;
        });

        Ok(Self {
            command_tx,
            task: Some(task),
            initialized: AtomicBool::new(false),
            server_info: RwLock::new(None),
            capabilities,
            protocol_support,
            selected_protocol_version: RwLock::new(None),
            client_info: RwLock::new(None),
            discovery: RwLock::new(None),
            roots,
            connected,
            supports_session_recovery,
            init_params: RwLock::new(None),
            recovery_lock: Mutex::new(()),
            max_mrtr_rounds,
            response_cache,
        })
    }

    /// Check if the client has been initialized.
    pub fn is_initialized(&self) -> bool {
        self.initialized.load(Ordering::Acquire)
    }

    /// Check if the transport is still connected.
    pub fn is_connected(&self) -> bool {
        self.connected.load(Ordering::Acquire)
    }

    /// Get the server info (available after initialization).
    pub async fn server_info(&self) -> Option<InitializeResult> {
        self.server_info.read().await.clone()
    }

    /// Return the exact ordered protocol implementations enabled for this client.
    pub fn protocol_support(&self) -> &ProtocolSupport {
        &self.protocol_support
    }

    /// Clear every cached final-protocol response held by this client.
    pub async fn clear_response_cache(&self) {
        self.response_cache.clear().await;
    }

    /// Change the authorization-context partition used for private responses.
    ///
    /// Previously cached private entries become inaccessible, while public
    /// entries remain reusable. Call this before issuing requests after the
    /// authenticated principal changes.
    pub async fn set_cache_partition(&self, partition: impl Into<String>) {
        self.response_cache.set_partition(partition.into()).await;
    }

    /// Return the number of response-cache entries held by this client.
    pub async fn response_cache_len(&self) -> usize {
        self.response_cache.len().await
    }

    /// Get the server discovery result after the final lifecycle is active.
    pub async fn discovery(&self) -> Option<DiscoverResult> {
        self.discovery.read().await.clone()
    }

    /// Get the protocol version selected for the discover-based lifecycle.
    pub async fn selected_protocol_version(&self) -> Option<String> {
        self.selected_protocol_version.read().await.clone()
    }

    /// Get the server info synchronously (best-effort, non-blocking).
    ///
    /// Returns `None` if the lock is currently held by a writer or if
    /// initialization hasn't completed. Prefer [`server_info()`](Self::server_info)
    /// in async contexts.
    pub fn server_info_blocking(&self) -> Option<InitializeResult> {
        self.server_info.try_read().ok()?.clone()
    }

    /// Initialize the MCP connection.
    ///
    /// Sends the `initialize` request and `notifications/initialized` notification.
    /// Must be called before any other operations.
    pub async fn initialize(
        &self,
        client_name: &str,
        client_version: &str,
    ) -> Result<InitializeResult> {
        let params = InitializeParams {
            protocol_version: crate::protocol::LATEST_PROTOCOL_VERSION.to_string(),
            capabilities: self.capabilities.clone(),
            client_info: Implementation {
                name: client_name.to_string(),
                version: client_version.to_string(),
                ..Default::default()
            },
            meta: None,
        };

        let result: InitializeResult = self.send_request("initialize", &params).await?;
        *self.server_info.write().await = Some(result.clone());

        // Store init params for potential session recovery
        *self.init_params.write().await =
            Some((client_name.to_string(), client_version.to_string()));

        // Send initialized notification
        self.send_notification("notifications/initialized", &serde_json::json!({}))
            .await?;
        self.initialized.store(true, Ordering::Release);

        Ok(result)
    }

    /// Start the sessionless 2026-07-28 lifecycle with `server/discover`.
    ///
    /// This path is available only when the final implementation was compiled.
    /// The client sends required per-request metadata from the first request,
    /// retries one `Unsupported protocol version` response using the server's
    /// advertised intersection, and then repeats the selected version,
    /// capabilities, and client identity on every subsequent request.
    #[cfg(any(feature = "protocol-2026-07-28", feature = "stateless"))]
    pub async fn discover(
        &self,
        client_name: &str,
        client_version: &str,
    ) -> Result<DiscoverResult> {
        use crate::protocol::PROTOCOL_VERSION_2026_07_28;

        let client_info = Implementation {
            name: client_name.to_string(),
            version: client_version.to_string(),
            ..Default::default()
        };
        *self.client_info.write().await = Some(client_info.clone());

        let mut candidate = self
            .protocol_support
            .versions()
            .iter()
            .find(|version| version.as_str() == PROTOCOL_VERSION_2026_07_28)
            .cloned()
            .ok_or_else(|| {
                Error::Transport(
                    "2026-07-28 is not enabled for this client; configure ProtocolSupport"
                        .to_string(),
                )
            })?;
        let mut retried_unsupported = false;

        loop {
            let params = DiscoverParams {
                meta: Some(self.request_meta_for(&candidate, &client_info)),
            };
            let cache_key = serde_json::to_string(&(
                client_name,
                client_version,
                candidate.as_str(),
                &self.capabilities,
            ))
            .expect("discovery cache key is serializable");
            match self
                .send_cacheable_request_when::<_, DiscoverResult>(
                    "server/discover",
                    &cache_key,
                    &params,
                    true,
                )
                .await
            {
                Ok(result) => {
                    let selected = self
                        .protocol_support
                        .versions()
                        .iter()
                        .find(|version| {
                            result
                                .supported_versions
                                .iter()
                                .any(|supported| supported == *version)
                        })
                        .cloned()
                        .ok_or_else(|| {
                            Error::Transport(format!(
                                "server and client have no protocol version in common; server: {:?}, client: {:?}",
                                result.supported_versions,
                                self.protocol_support.versions()
                            ))
                        })?;
                    *self.selected_protocol_version.write().await = Some(selected);
                    *self.discovery.write().await = Some(result.clone());
                    self.initialized.store(true, Ordering::Release);
                    return Ok(result);
                }
                Err(Error::JsonRpc(error)) if error.code == -32022 && !retried_unsupported => {
                    let supported = error
                        .data
                        .as_ref()
                        .and_then(|data| data.get("supported"))
                        .and_then(serde_json::Value::as_array)
                        .ok_or_else(|| Error::JsonRpc(error.clone()))?;
                    candidate = self
                        .protocol_support
                        .versions()
                        .iter()
                        .find(|version| {
                            supported
                                .iter()
                                .any(|item| item.as_str() == Some(version.as_str()))
                        })
                        .cloned()
                        .ok_or_else(|| Error::JsonRpc(error.clone()))?;
                    retried_unsupported = true;
                }
                Err(error) => return Err(error),
            }
        }
    }

    /// List available tools.
    pub async fn list_tools(&self) -> Result<ListToolsResult> {
        self.list_tools_with_cursor(None).await
    }

    /// Call a tool.
    ///
    /// On the final lifecycle, a header mismatch, method-not-found, or
    /// invalid-params response can indicate that the cached tool schema is
    /// stale. The client invalidates `tools/list`, refreshes it, and retries
    /// the rejected round once. These errors are raised before tool execution,
    /// so the bounded retry does not replay a completed side effect.
    pub async fn call_tool(
        &self,
        name: &str,
        arguments: serde_json::Value,
    ) -> Result<CallToolResult> {
        let mut input_responses = None;
        let mut request_state = None;
        let mut schema_retry_available = self.uses_final_protocol().await;
        for round in 0..=self.max_mrtr_rounds {
            let params = CallToolParams {
                name: name.to_string(),
                arguments: arguments.clone(),
                input_responses: input_responses.take(),
                request_state: request_state.take(),
                meta: None,
                task: None,
            };
            let outcome = self
                .send_task_aware_tool_request_with_schema_retry(
                    &params,
                    &mut schema_retry_available,
                )
                .await?;
            match outcome {
                TaskAwareCallToolOutcome::Complete(result) => return Ok(result),
                TaskAwareCallToolOutcome::Task(created) => {
                    return self
                        .complete_final_task(&created.task.metadata.task_id)
                        .await;
                }
                TaskAwareCallToolOutcome::InputRequired(required) => {
                    if round == self.max_mrtr_rounds {
                        return Err(Error::Transport(format!(
                            "MRTR round limit ({}) exceeded for tools/call",
                            self.max_mrtr_rounds
                        )));
                    }
                    let requests = required.input_requests.ok_or_else(|| {
                        Error::Transport(
                            "input_required result has no requests the client can fulfil"
                                .to_string(),
                        )
                    })?;
                    input_responses = Some(self.resolve_input_requests(requests).await?);
                    request_state = required.request_state;
                }
            }
        }
        unreachable!("MRTR loop either completes or returns at the configured bound")
    }

    /// Send one tools/call attempt without automatically following MRTR input.
    pub async fn call_tool_once(
        &self,
        name: &str,
        arguments: serde_json::Value,
        input_responses: Option<InputResponses>,
        request_state: Option<String>,
    ) -> Result<RequestOutcome<CallToolResult>> {
        match self
            .call_tool_once_task_aware(name, arguments, input_responses, request_state)
            .await?
        {
            TaskAwareCallToolOutcome::Complete(result) => Ok(RequestOutcome::Complete(result)),
            TaskAwareCallToolOutcome::InputRequired(required) => {
                Ok(RequestOutcome::InputRequired(required))
            }
            TaskAwareCallToolOutcome::Task(created) => Err(Error::Transport(format!(
                "tools/call returned task '{}'; use call_tool_once_task_aware for direct task lifecycle control",
                created.task.metadata.task_id
            ))),
        }
    }

    /// Send one `tools/call` attempt and preserve a server-created task.
    ///
    /// Unlike [`call_tool`](Self::call_tool), this does not poll a task or
    /// automatically fulfil input requests. Final-protocol callers can use it
    /// to retain the exact task handle returned from the ordinary request.
    pub async fn call_tool_once_task_aware(
        &self,
        name: &str,
        arguments: serde_json::Value,
        input_responses: Option<InputResponses>,
        request_state: Option<String>,
    ) -> Result<TaskAwareCallToolOutcome> {
        self.ensure_initialized()?;
        let params = CallToolParams {
            name: name.to_string(),
            arguments,
            input_responses,
            request_state,
            meta: None,
            task: None,
        };
        let mut schema_retry_available = self.uses_final_protocol().await;
        self.send_task_aware_tool_request_with_schema_retry(&params, &mut schema_retry_available)
            .await
    }

    /// Request direct control of a tool task lifecycle.
    ///
    /// Instead of blocking until the tool finishes, the server creates a
    /// task and immediately returns a [`CreateTaskResult`] carrying the task
    /// id. Poll with [`task_get`](Self::task_get) or block with
    /// [`task_wait`](Self::task_wait); a completed task's `result` field
    /// carries the [`CallToolResult`] the synchronous call would have
    /// returned.
    ///
    /// On 2025-11-25, `ttl_ms` is sent in the legacy task-augmentation field.
    /// On 2026-07-28, task creation is server-directed: this sends an ordinary
    /// request and requires the server to elect a task. A final client cannot
    /// request a TTL, so a non-`None` `ttl_ms` is rejected on that lifecycle.
    pub async fn call_tool_as_task(
        &self,
        name: &str,
        arguments: serde_json::Value,
        ttl_ms: Option<u64>,
    ) -> Result<CreateTaskResult> {
        self.ensure_initialized()?;
        if self.uses_final_protocol().await {
            if ttl_ms.is_some() {
                return Err(Error::Transport(
                    "ttl_ms is server-selected by the final Tasks extension".to_string(),
                ));
            }
            let params = CallToolParams {
                name: name.to_string(),
                arguments,
                input_responses: None,
                request_state: None,
                meta: None,
                task: None,
            };
            let mut schema_retry_available = true;
            return match self
                .send_task_aware_tool_request_with_schema_retry(
                    &params,
                    &mut schema_retry_available,
                )
                .await?
            {
                TaskAwareCallToolOutcome::Task(created) => {
                    Ok(Self::legacy_create_task_from_final(created))
                }
                TaskAwareCallToolOutcome::Complete(_) => Err(Error::Transport(
                    "server completed tools/call synchronously; final task creation is server-directed"
                        .to_string(),
                )),
                TaskAwareCallToolOutcome::InputRequired(_) => Err(Error::Transport(
                    "server requested input instead of creating a task".to_string(),
                )),
            };
        }

        let params = CallToolParams {
            name: name.to_string(),
            arguments,
            input_responses: None,
            request_state: None,
            meta: None,
            task: Some(TaskRequestParams { ttl: ttl_ms }),
        };
        let mut schema_retry_available = self.uses_final_protocol().await;
        self.send_tool_request_with_schema_retry(&params, &mut schema_retry_available)
            .await
    }

    /// Fetch a task's current state via `tasks/get` (SEP-2663).
    ///
    /// For `completed` tasks the returned object carries the terminal
    /// [`CallToolResult`] in its `result` field; for `failed` tasks the
    /// JSON-RPC error is in `error`. Unknown or expired task ids surface as
    /// an invalid-params error from the server.
    pub async fn task_get(&self, task_id: &str) -> Result<TaskObject> {
        self.ensure_initialized()?;
        if self.uses_final_protocol().await {
            return Self::legacy_task_from_final(self.task_get_detailed(task_id).await?);
        }
        let params = GetTaskInfoParams {
            task_id: task_id.to_string(),
            meta: None,
        };
        self.send_request("tasks/get", &params).await
    }

    /// Fetch the exact final-protocol `tasks/get` result.
    ///
    /// This preserves status-specific payloads, including all outstanding
    /// `inputRequests`. It is available only after selecting the 2026-07-28
    /// lifecycle; legacy callers should use [`task_get`](Self::task_get).
    pub async fn task_get_detailed(&self, task_id: &str) -> Result<crate::tasks::GetTaskResult> {
        self.ensure_initialized()?;
        if !self.uses_final_protocol().await {
            return Err(Error::Transport(
                "task_get_detailed requires the 2026-07-28 client lifecycle".to_string(),
            ));
        }
        let params = crate::tasks::GetTaskParams {
            task_id: task_id.to_string(),
            meta: None,
        };
        self.send_request("tasks/get", &params).await
    }

    /// Cancel a task via `tasks/cancel` (SEP-2663).
    ///
    /// Cancellation is cooperative: the acknowledgment is an empty result
    /// and the observable status may remain non-terminal for a while after
    /// the ack; poll [`task_get`](Self::task_get) to observe the terminal
    /// state. `reason` is a legacy-only field and is omitted on the final
    /// protocol. The ack body is discarded, so legacy peers that return the
    /// task object are also tolerated.
    pub async fn task_cancel(&self, task_id: &str, reason: Option<String>) -> Result<()> {
        self.ensure_initialized()?;
        if self.uses_final_protocol().await {
            let params = crate::tasks::CancelTaskParams {
                task_id: task_id.to_string(),
                meta: None,
            };
            let _ack: crate::tasks::CancelTaskResult =
                self.send_request("tasks/cancel", &params).await?;
            return Ok(());
        }
        let params = CancelTaskParams {
            task_id: task_id.to_string(),
            reason,
            meta: None,
        };
        let _ack: serde_json::Value = self.send_request("tasks/cancel", &params).await?;
        Ok(())
    }

    /// Answer a task's outstanding input requests via `tasks/update`
    /// (SEP-2663).
    ///
    /// Responses are matched to outstanding requests by key. Final-protocol
    /// callers read the keys from the `inputRequests` of an `input_required`
    /// task returned by [`task_get_detailed`](Self::task_get_detailed).
    ///
    /// A partial map is valid and expected: requests left unanswered stay
    /// outstanding and the task remains `input_required` until every one is
    /// answered. Keys the server does not currently have outstanding, whether
    /// unknown, already answered, or superseded by a later request, are
    /// ignored rather than rejected, so replaying a stale update is safe.
    ///
    /// The acknowledgment carries no data and is discarded. Poll
    /// [`task_get`](Self::task_get) to observe the resulting state.
    pub async fn task_update(&self, task_id: &str, input_responses: InputResponses) -> Result<()> {
        self.ensure_initialized()?;
        if self.uses_final_protocol().await {
            let params = crate::tasks::UpdateTaskParams {
                task_id: task_id.to_string(),
                input_responses,
                meta: None,
            };
            let _ack: crate::tasks::UpdateTaskResult =
                self.send_request("tasks/update", &params).await?;
            return Ok(());
        }
        let input_responses = input_responses
            .into_iter()
            .map(|(key, response)| serde_json::to_value(response).map(|value| (key, value)))
            .collect::<std::result::Result<_, _>>()?;
        let params = UpdateTaskParams {
            task_id: task_id.to_string(),
            input_responses,
            meta: None,
        };
        let _ack: serde_json::Value = self.send_request("tasks/update", &params).await?;
        Ok(())
    }

    /// Poll `tasks/get` until the task reaches a terminal state.
    ///
    /// Honors the server's suggested polling interval (default 1000 ms,
    /// clamped to 50 ms..30 s). On the final protocol it also fulfils
    /// `input_required` requests through the registered client handlers. A
    /// task purged after its TTL surfaces as the server's task-not-found
    /// error. Wrap in
    /// [`tokio::time::timeout`] to bound the overall wait.
    pub async fn task_wait(&self, task_id: &str) -> Result<TaskObject> {
        if self.uses_final_protocol().await {
            let result = self.wait_for_final_task(task_id).await?;
            return Self::legacy_task_from_final(result);
        }
        loop {
            let task = self.task_get(task_id).await?;
            if task.status.is_terminal() {
                return Ok(task);
            }
            let interval_ms = task.poll_interval.unwrap_or(1000).clamp(50, 30_000);
            tokio::time::sleep(std::time::Duration::from_millis(interval_ms)).await;
        }
    }

    /// List available resources.
    pub async fn list_resources(&self) -> Result<ListResourcesResult> {
        self.list_resources_with_cursor(None).await
    }

    /// Read a resource.
    pub async fn read_resource(&self, uri: &str) -> Result<ReadResourceResult> {
        self.ensure_initialized()?;
        let cache_enabled = self.uses_final_protocol().await && self.response_cache.enabled();
        let generation = if cache_enabled {
            self.response_cache
                .capture_generation("resources/read", uri)
                .await
        } else {
            0
        };
        let mut generation_active = cache_enabled;
        let mut stale = None;
        if cache_enabled {
            match self.response_cache.lookup("resources/read", uri).await {
                CacheLookup::Fresh(value) => {
                    if let Some(result) = decode_cached(&value, "resources/read") {
                        self.response_cache
                            .release_generation("resources/read", uri)
                            .await;
                        return Ok(result);
                    }
                    self.response_cache.evict_resource(uri).await;
                }
                CacheLookup::Stale(value) => stale = Some(value),
                CacheLookup::Miss => {}
            }
        }

        let mut input_responses = None;
        let mut request_state = None;
        let mut followed_input_required = false;
        for round in 0..=self.max_mrtr_rounds {
            let outcome = match self
                .read_resource_once(uri, input_responses.take(), request_state.take())
                .await
            {
                Ok(outcome) => outcome,
                Err(error) => {
                    if generation_active {
                        self.response_cache
                            .release_generation("resources/read", uri)
                            .await;
                    }
                    if self.response_cache.serve_stale_on_error()
                        && let Some(value) = stale.as_ref()
                        && let Some(result) = decode_cached(value, "resources/read")
                    {
                        tracing::warn!(
                            uri,
                            error = %error,
                            "Serving stale resources/read response after refresh failure"
                        );
                        return Ok(result);
                    }
                    return Err(error);
                }
            };
            match outcome {
                RequestOutcome::Complete(result) => {
                    if generation_active && !followed_input_required {
                        self.write_cached_response("resources/read", uri, generation, &result)
                            .await;
                    }
                    return Ok(result);
                }
                RequestOutcome::InputRequired(required) => {
                    if !followed_input_required {
                        followed_input_required = true;
                        if generation_active {
                            self.response_cache
                                .release_generation("resources/read", uri)
                                .await;
                            generation_active = false;
                        }
                    }
                    if round == self.max_mrtr_rounds {
                        return Err(Error::Transport(format!(
                            "MRTR round limit ({}) exceeded for resources/read",
                            self.max_mrtr_rounds
                        )));
                    }
                    let requests = required.input_requests.ok_or_else(|| {
                        Error::Transport(
                            "input_required result has no requests the client can fulfil"
                                .to_string(),
                        )
                    })?;
                    input_responses = Some(self.resolve_input_requests(requests).await?);
                    request_state = required.request_state;
                }
            }
        }
        unreachable!("MRTR loop either completes or returns at the configured bound")
    }

    /// Send one resources/read attempt without automatically following MRTR.
    pub async fn read_resource_once(
        &self,
        uri: &str,
        input_responses: Option<InputResponses>,
        request_state: Option<String>,
    ) -> Result<RequestOutcome<ReadResourceResult>> {
        self.ensure_initialized()?;
        let params = ReadResourceParams {
            uri: uri.to_string(),
            input_responses,
            request_state,
            meta: None,
        };
        self.send_request("resources/read", &params).await
    }

    /// Open a final-protocol `subscriptions/listen` notification stream.
    ///
    /// The returned handle owns the long-lived request. Use
    /// [`SubscriptionHandle::acknowledged`] to inspect the subset accepted by
    /// the server, [`SubscriptionHandle::wait`] to observe graceful server
    /// closure, or [`SubscriptionHandle::cancel`] to close the stream.
    /// Notifications continue to flow through the configured
    /// [`ClientHandler`] and carry their subscription ID in
    /// [`ServerNotification::Subscription`].
    pub async fn listen_subscriptions(
        &self,
        notifications: SubscriptionFilter,
    ) -> Result<SubscriptionHandle> {
        self.ensure_initialized()?;
        if !self.uses_final_protocol().await {
            return Err(Error::Transport(
                "subscriptions/listen requires the 2026-07-28 protocol".to_string(),
            ));
        }

        let params = SubscriptionsListenParams {
            notifications: Some(notifications),
            meta: None,
        };
        let params = serde_json::to_value(params).map_err(|error| {
            Error::Transport(format!(
                "failed to serialize subscriptions/listen params: {error}"
            ))
        })?;
        let params = self.with_final_request_meta(params).await?;
        let (id_tx, id_rx) = oneshot::channel();
        let (acknowledgment_tx, acknowledgment_rx) = oneshot::channel();
        let (response_tx, response_rx) = oneshot::channel();
        self.command_tx
            .send(LoopCommand::StartSubscription {
                params,
                id_tx,
                acknowledgment_tx,
                response_tx,
            })
            .await
            .map_err(|_| Error::Transport("connection closed".to_string()))?;
        let request_id = id_rx
            .await
            .map_err(|_| Error::Transport("connection closed".to_string()))?;

        Ok(SubscriptionHandle {
            request_id,
            command_tx: self.command_tx.clone(),
            acknowledgment_rx: Some(acknowledgment_rx),
            response_rx: Some(response_rx),
            active: true,
        })
    }

    /// Subscribe to `notifications/resources/updated` for one resource
    /// (`resources/subscribe`).
    ///
    /// The updates themselves arrive through the notification handler, so a
    /// client that subscribes without registering
    /// [`NotificationHandler::on_resource_updated`] will not see them. Servers
    /// that support this advertise `resources.subscribe` in their
    /// capabilities; one that does not will reject the request.
    pub async fn subscribe_resource(&self, uri: &str) -> Result<()> {
        self.ensure_initialized()?;
        if self.uses_final_protocol().await {
            return Err(Error::Transport(
                "resources/subscribe was removed in 2026-07-28; use subscriptions/listen"
                    .to_string(),
            ));
        }
        let _: serde_json::Value = self
            .send_request("resources/subscribe", &serde_json::json!({ "uri": uri }))
            .await?;
        Ok(())
    }

    /// Stop receiving updates for a resource (`resources/unsubscribe`).
    pub async fn unsubscribe_resource(&self, uri: &str) -> Result<()> {
        self.ensure_initialized()?;
        if self.uses_final_protocol().await {
            return Err(Error::Transport(
                "resources/unsubscribe was removed in 2026-07-28; use subscriptions/listen"
                    .to_string(),
            ));
        }
        let _: serde_json::Value = self
            .send_request("resources/unsubscribe", &serde_json::json!({ "uri": uri }))
            .await?;
        Ok(())
    }

    /// List available prompts.
    pub async fn list_prompts(&self) -> Result<ListPromptsResult> {
        self.list_prompts_with_cursor(None).await
    }

    /// List tools with an optional pagination cursor.
    pub async fn list_tools_with_cursor(&self, cursor: Option<String>) -> Result<ListToolsResult> {
        self.ensure_initialized()?;
        let cache_key = pagination_cache_key(cursor.as_deref());
        self.send_cacheable_request(
            "tools/list",
            &cache_key,
            &ListToolsParams { cursor, meta: None },
        )
        .await
    }

    /// List resources with an optional pagination cursor.
    pub async fn list_resources_with_cursor(
        &self,
        cursor: Option<String>,
    ) -> Result<ListResourcesResult> {
        self.ensure_initialized()?;
        let cache_key = pagination_cache_key(cursor.as_deref());
        self.send_cacheable_request(
            "resources/list",
            &cache_key,
            &ListResourcesParams { cursor, meta: None },
        )
        .await
    }

    /// List resource templates.
    pub async fn list_resource_templates(&self) -> Result<ListResourceTemplatesResult> {
        self.list_resource_templates_with_cursor(None).await
    }

    /// List resource templates with an optional pagination cursor.
    pub async fn list_resource_templates_with_cursor(
        &self,
        cursor: Option<String>,
    ) -> Result<ListResourceTemplatesResult> {
        self.ensure_initialized()?;
        let cache_key = pagination_cache_key(cursor.as_deref());
        self.send_cacheable_request(
            "resources/templates/list",
            &cache_key,
            &ListResourceTemplatesParams { cursor, meta: None },
        )
        .await
    }

    /// List prompts with an optional pagination cursor.
    pub async fn list_prompts_with_cursor(
        &self,
        cursor: Option<String>,
    ) -> Result<ListPromptsResult> {
        self.ensure_initialized()?;
        let cache_key = pagination_cache_key(cursor.as_deref());
        self.send_cacheable_request(
            "prompts/list",
            &cache_key,
            &ListPromptsParams { cursor, meta: None },
        )
        .await
    }

    /// List all tools, following pagination cursors until exhausted.
    pub async fn list_all_tools(&self) -> Result<Vec<ToolDefinition>> {
        let mut all = Vec::new();
        let mut cursor = None;
        loop {
            let result = self.list_tools_with_cursor(cursor).await?;
            all.extend(result.tools);
            match result.next_cursor {
                Some(c) => cursor = Some(c),
                None => break,
            }
        }
        Ok(all)
    }

    /// List all resources, following pagination cursors until exhausted.
    pub async fn list_all_resources(&self) -> Result<Vec<ResourceDefinition>> {
        let mut all = Vec::new();
        let mut cursor = None;
        loop {
            let result = self.list_resources_with_cursor(cursor).await?;
            all.extend(result.resources);
            match result.next_cursor {
                Some(c) => cursor = Some(c),
                None => break,
            }
        }
        Ok(all)
    }

    /// List all resource templates, following pagination cursors until exhausted.
    pub async fn list_all_resource_templates(&self) -> Result<Vec<ResourceTemplateDefinition>> {
        let mut all = Vec::new();
        let mut cursor = None;
        loop {
            let result = self.list_resource_templates_with_cursor(cursor).await?;
            all.extend(result.resource_templates);
            match result.next_cursor {
                Some(c) => cursor = Some(c),
                None => break,
            }
        }
        Ok(all)
    }

    /// List all prompts, following pagination cursors until exhausted.
    pub async fn list_all_prompts(&self) -> Result<Vec<PromptDefinition>> {
        let mut all = Vec::new();
        let mut cursor = None;
        loop {
            let result = self.list_prompts_with_cursor(cursor).await?;
            all.extend(result.prompts);
            match result.next_cursor {
                Some(c) => cursor = Some(c),
                None => break,
            }
        }
        Ok(all)
    }

    /// Call a tool and return the concatenated text content.
    ///
    /// Returns the text from all [`Text`](crate::protocol::Content::Text) items joined together.
    /// If the tool result indicates an error (`is_error` is true), returns
    /// an error with the text content as the message.
    ///
    /// For more control over the result, use [`call_tool()`](Self::call_tool).
    pub async fn call_tool_text(&self, name: &str, arguments: serde_json::Value) -> Result<String> {
        let result = self.call_tool(name, arguments).await?;
        if result.is_error {
            return Err(Error::Internal(result.all_text()));
        }
        Ok(result.all_text())
    }

    /// Get a prompt.
    pub async fn get_prompt(
        &self,
        name: &str,
        arguments: Option<std::collections::HashMap<String, String>>,
    ) -> Result<GetPromptResult> {
        let arguments = arguments.unwrap_or_default();
        let mut input_responses = None;
        let mut request_state = None;
        for round in 0..=self.max_mrtr_rounds {
            match self
                .get_prompt_once(
                    name,
                    arguments.clone(),
                    input_responses.take(),
                    request_state.take(),
                )
                .await?
            {
                RequestOutcome::Complete(result) => return Ok(result),
                RequestOutcome::InputRequired(required) => {
                    if round == self.max_mrtr_rounds {
                        return Err(Error::Transport(format!(
                            "MRTR round limit ({}) exceeded for prompts/get",
                            self.max_mrtr_rounds
                        )));
                    }
                    let requests = required.input_requests.ok_or_else(|| {
                        Error::Transport(
                            "input_required result has no requests the client can fulfil"
                                .to_string(),
                        )
                    })?;
                    input_responses = Some(self.resolve_input_requests(requests).await?);
                    request_state = required.request_state;
                }
            }
        }
        unreachable!("MRTR loop either completes or returns at the configured bound")
    }

    /// Send one prompts/get attempt without automatically following MRTR.
    pub async fn get_prompt_once(
        &self,
        name: &str,
        arguments: std::collections::HashMap<String, String>,
        input_responses: Option<InputResponses>,
        request_state: Option<String>,
    ) -> Result<RequestOutcome<GetPromptResult>> {
        self.ensure_initialized()?;
        let params = GetPromptParams {
            name: name.to_string(),
            arguments,
            input_responses,
            request_state,
            meta: None,
        };
        self.send_request("prompts/get", &params).await
    }

    /// Ping the server.
    pub async fn ping(&self) -> Result<()> {
        if self.uses_final_protocol().await {
            return Err(Error::Transport(
                "ping was removed from the 2026-07-28 core protocol".to_string(),
            ));
        }
        let _: serde_json::Value = self.send_request("ping", &serde_json::json!({})).await?;
        Ok(())
    }

    /// Request completion suggestions from the server.
    pub async fn complete(
        &self,
        reference: CompletionReference,
        argument_name: &str,
        argument_value: &str,
    ) -> Result<CompleteResult> {
        self.ensure_initialized()?;
        let params = CompleteParams {
            reference,
            argument: CompletionArgument::new(argument_name, argument_value),
            context: None,
            meta: None,
        };
        self.send_request("completion/complete", &params).await
    }

    /// Request completion for a prompt argument.
    pub async fn complete_prompt_arg(
        &self,
        prompt_name: &str,
        argument_name: &str,
        argument_value: &str,
    ) -> Result<CompleteResult> {
        self.complete(
            CompletionReference::prompt(prompt_name),
            argument_name,
            argument_value,
        )
        .await
    }

    /// Request completion for a resource URI.
    pub async fn complete_resource_uri(
        &self,
        resource_uri: &str,
        argument_name: &str,
        argument_value: &str,
    ) -> Result<CompleteResult> {
        self.complete(
            CompletionReference::resource(resource_uri),
            argument_name,
            argument_value,
        )
        .await
    }

    /// Send a raw typed request to the server.
    pub async fn request<P: serde::Serialize, R: serde::de::DeserializeOwned>(
        &self,
        method: &str,
        params: &P,
    ) -> Result<R> {
        self.send_request(method, params).await
    }

    /// Send a raw typed notification to the server.
    pub async fn notify<P: serde::Serialize>(&self, method: &str, params: &P) -> Result<()> {
        self.send_notification(method, params).await
    }

    /// Get the current roots.
    pub async fn roots(&self) -> Vec<Root> {
        self.roots.read().await.clone()
    }

    /// Set roots and notify the server if initialized.
    pub async fn set_roots(&self, roots: Vec<Root>) -> Result<()> {
        *self.roots.write().await = roots;
        if self.is_initialized() && !self.uses_final_protocol().await {
            self.send_notification(notifications::ROOTS_LIST_CHANGED, &serde_json::json!({}))
                .await?;
        }
        Ok(())
    }

    /// Add a root and notify the server if initialized.
    pub async fn add_root(&self, root: Root) -> Result<()> {
        self.roots.write().await.push(root);
        if self.is_initialized() && !self.uses_final_protocol().await {
            self.send_notification(notifications::ROOTS_LIST_CHANGED, &serde_json::json!({}))
                .await?;
        }
        Ok(())
    }

    /// Remove a root by URI and notify the server if initialized.
    pub async fn remove_root(&self, uri: &str) -> Result<bool> {
        let mut roots = self.roots.write().await;
        let initial_len = roots.len();
        roots.retain(|r| r.uri != uri);
        let removed = roots.len() < initial_len;
        drop(roots);

        if removed && self.is_initialized() && !self.uses_final_protocol().await {
            self.send_notification(notifications::ROOTS_LIST_CHANGED, &serde_json::json!({}))
                .await?;
        }
        Ok(removed)
    }

    /// Get the roots list result (for responding to server's roots/list request).
    pub async fn list_roots(&self) -> ListRootsResult {
        ListRootsResult {
            roots: self.roots.read().await.clone(),
            meta: None,
        }
    }

    /// Gracefully shut down the client and close the transport.
    pub async fn shutdown(mut self) -> Result<()> {
        let _ = self.command_tx.send(LoopCommand::Shutdown).await;
        if let Some(task) = self.task.take() {
            let _ = task.await;
        }
        Ok(())
    }

    // --- Internal helpers ---

    async fn send_task_aware_tool_request_with_schema_retry(
        &self,
        params: &CallToolParams,
        retry_available: &mut bool,
    ) -> Result<TaskAwareCallToolOutcome> {
        self.send_tool_request_with_schema_retry(params, retry_available)
            .await
    }

    async fn wait_for_final_task(&self, task_id: &str) -> Result<crate::tasks::GetTaskResult> {
        loop {
            let task = self.task_get_detailed(task_id).await?;
            match task.task.status() {
                crate::protocol::TaskStatus::Completed
                | crate::protocol::TaskStatus::Failed
                | crate::protocol::TaskStatus::Cancelled => return Ok(task),
                crate::protocol::TaskStatus::InputRequired => {
                    let requests = task.task.input_requests().cloned().ok_or_else(|| {
                        Error::Transport(format!(
                            "task '{task_id}' is input_required without inputRequests"
                        ))
                    })?;
                    if requests.is_empty() {
                        return Err(Error::Transport(format!(
                            "task '{task_id}' is input_required without inputRequests"
                        )));
                    }
                    let responses = self.resolve_input_requests(requests).await?;
                    self.task_update(task_id, responses).await?;
                }
                crate::protocol::TaskStatus::Working => {
                    let interval_ms = task
                        .task
                        .metadata()
                        .poll_interval_ms
                        .unwrap_or(1000)
                        .clamp(50, 30_000);
                    tokio::time::sleep(std::time::Duration::from_millis(interval_ms)).await;
                }
                _ => {
                    return Err(Error::Transport(format!(
                        "task '{task_id}' returned an unsupported status"
                    )));
                }
            }
        }
    }

    async fn complete_final_task(&self, task_id: &str) -> Result<CallToolResult> {
        let task = self.wait_for_final_task(task_id).await?;
        match task.task.status() {
            crate::protocol::TaskStatus::Completed => {
                let result = task.task.result().cloned().ok_or_else(|| {
                    Error::Transport(format!(
                        "completed task '{task_id}' did not contain a result"
                    ))
                })?;
                serde_json::from_value(serde_json::Value::Object(result)).map_err(|error| {
                    Error::Transport(format!(
                        "failed to deserialize completed task '{task_id}' result: {error}"
                    ))
                })
            }
            crate::protocol::TaskStatus::Failed => {
                let error = task.task.error().cloned().unwrap_or_else(|| {
                    JsonRpcError::internal_error(format!(
                        "task '{task_id}' failed without an error payload"
                    ))
                });
                Err(Error::JsonRpc(error))
            }
            crate::protocol::TaskStatus::Cancelled => {
                Err(Error::Transport(format!("task '{task_id}' was cancelled")))
            }
            _ => Err(Error::Transport(format!(
                "task '{task_id}' did not reach a terminal state"
            ))),
        }
    }

    fn legacy_create_task_from_final(created: crate::tasks::CreateTaskResult) -> CreateTaskResult {
        let metadata = created.task.metadata;
        CreateTaskResult {
            task: TaskObject {
                task_id: metadata.task_id,
                status: created.task.status,
                status_message: metadata.status_message,
                created_at: metadata.created_at,
                last_updated_at: metadata.last_updated_at,
                ttl: metadata.ttl_ms,
                poll_interval: metadata.poll_interval_ms,
                result: None,
                error: None,
                meta: None,
            },
            meta: created.meta.map(serde_json::Value::Object),
        }
    }

    fn legacy_task_from_final(result: crate::tasks::GetTaskResult) -> Result<TaskObject> {
        let task = &result.task;
        let metadata = task.metadata();
        let completed = task
            .result()
            .cloned()
            .map(serde_json::Value::Object)
            .map(serde_json::from_value)
            .transpose()
            .map_err(|error| {
                Error::Transport(format!(
                    "failed to deserialize task '{}' result: {error}",
                    metadata.task_id
                ))
            })?;
        Ok(TaskObject {
            task_id: metadata.task_id.clone(),
            status: task.status(),
            status_message: metadata.status_message.clone(),
            created_at: metadata.created_at.clone(),
            last_updated_at: metadata.last_updated_at.clone(),
            ttl: metadata.ttl_ms,
            poll_interval: metadata.poll_interval_ms,
            result: completed,
            error: task.error().cloned(),
            meta: result.meta.map(serde_json::Value::Object),
        })
    }

    async fn send_tool_request_with_schema_retry<R>(
        &self,
        params: &CallToolParams,
        retry_available: &mut bool,
    ) -> Result<R>
    where
        R: serde::de::DeserializeOwned,
    {
        match self.send_request("tools/call", params).await {
            Err(error) if *retry_available && is_stale_tool_schema_error(&error) => {
                *retry_available = false;
                self.response_cache.evict_method("tools/list").await;
                tracing::info!(
                    tool = params.name,
                    error = %error,
                    "Refreshing tools/list before one stale-schema retry"
                );
                if let Err(refresh_error) = self.list_tools().await {
                    tracing::warn!(
                        tool = params.name,
                        error = %refresh_error,
                        "Could not refresh tools/list after stale-schema rejection"
                    );
                    return Err(error);
                }
                self.send_request("tools/call", params).await
            }
            result => result,
        }
    }

    async fn send_cacheable_request<P, R>(
        &self,
        method: &str,
        cache_key: &str,
        params: &P,
    ) -> Result<R>
    where
        P: serde::Serialize,
        R: CacheableResponse,
    {
        let cache_allowed = self.uses_final_protocol().await;
        self.send_cacheable_request_when(method, cache_key, params, cache_allowed)
            .await
    }

    async fn send_cacheable_request_when<P, R>(
        &self,
        method: &str,
        cache_key: &str,
        params: &P,
        cache_allowed: bool,
    ) -> Result<R>
    where
        P: serde::Serialize,
        R: CacheableResponse,
    {
        if !cache_allowed || !self.response_cache.enabled() {
            return self.send_request(method, params).await;
        }

        let generation = self
            .response_cache
            .capture_generation(method, cache_key)
            .await;
        let mut stale = None;
        match self.response_cache.lookup(method, cache_key).await {
            CacheLookup::Fresh(value) => {
                if let Some(result) = decode_cached(&value, method) {
                    self.response_cache
                        .release_generation(method, cache_key)
                        .await;
                    tracing::debug!(method, "Serving fresh response from cache");
                    return Ok(result);
                }
                self.response_cache.evict_method(method).await;
            }
            CacheLookup::Stale(value) => stale = Some(value),
            CacheLookup::Miss => {}
        }

        match self.send_request(method, params).await {
            Ok(result) => {
                self.write_cached_response(method, cache_key, generation, &result)
                    .await;
                Ok(result)
            }
            Err(error) => {
                self.response_cache
                    .release_generation(method, cache_key)
                    .await;
                if self.response_cache.serve_stale_on_error()
                    && let Some(value) = stale.as_ref()
                    && let Some(result) = decode_cached(value, method)
                {
                    tracing::warn!(
                        method,
                        error = %error,
                        "Serving stale response after cache refresh failure"
                    );
                    return Ok(result);
                }
                Err(error)
            }
        }
    }

    async fn write_cached_response<R: CacheableResponse>(
        &self,
        method: &str,
        cache_key: &str,
        generation: u64,
        result: &R,
    ) {
        match serde_json::to_value(result) {
            Ok(value) => {
                self.response_cache
                    .write(
                        method,
                        cache_key,
                        generation,
                        value,
                        result.ttl_ms(),
                        result.cache_scope(),
                    )
                    .await;
            }
            Err(error) => {
                self.response_cache
                    .release_generation(method, cache_key)
                    .await;
                tracing::warn!(
                    method,
                    error = %error,
                    "Skipping response-cache write after serialization failure"
                );
            }
        }
    }

    async fn send_request<P: serde::Serialize, R: serde::de::DeserializeOwned>(
        &self,
        method: &str,
        params: &P,
    ) -> Result<R> {
        let final_protocol = self.uses_final_protocol().await;
        match self.send_request_once(method, params).await {
            Err(Error::SessionExpired)
                if self.supports_session_recovery && !final_protocol && method != "initialize" =>
            {
                tracing::info!(method = %method, "Session expired, attempting recovery");
                self.recover_session().await?;
                self.send_request_once(method, params).await
            }
            other => other,
        }
    }

    async fn send_request_once<P: serde::Serialize, R: serde::de::DeserializeOwned>(
        &self,
        method: &str,
        params: &P,
    ) -> Result<R> {
        self.ensure_connected()?;
        let params_value = serde_json::to_value(params)
            .map_err(|e| Error::Transport(format!("Failed to serialize params: {}", e)))?;
        let params_value = self.with_final_request_meta(params_value).await?;

        let (response_tx, response_rx) = oneshot::channel();
        self.command_tx
            .send(LoopCommand::Request {
                method: method.to_string(),
                params: params_value,
                response_tx,
            })
            .await
            .map_err(|_| Error::Transport("Connection closed".to_string()))?;

        let result = response_rx
            .await
            .map_err(|_| Error::Transport("Connection closed".to_string()))??;

        serde_json::from_value(result)
            .map_err(|e| Error::Transport(format!("Failed to deserialize response: {}", e)))
    }

    /// Recover from a session expiry by resetting the transport and re-initializing.
    async fn recover_session(&self) -> Result<()> {
        // Serialize recovery attempts
        let _guard = self.recovery_lock.lock().await;

        // Check if another task already recovered while we waited
        // (the init_params being present means we were initialized before)
        let init_params = self.init_params.read().await.clone();
        let (client_name, client_version) = match init_params {
            Some(params) => params,
            None => {
                return Err(Error::Transport(
                    "Cannot recover: never initialized".to_string(),
                ));
            }
        };

        // Tell the message loop to reset the transport
        let (done_tx, done_rx) = oneshot::channel();
        self.command_tx
            .send(LoopCommand::ResetSession { done_tx })
            .await
            .map_err(|_| Error::Transport("Connection closed".to_string()))?;
        done_rx
            .await
            .map_err(|_| Error::Transport("Connection closed during recovery".to_string()))?;

        // Clear initialized state
        self.initialized.store(false, Ordering::Release);
        *self.server_info.write().await = None;

        // Re-initialize (using send_request_once to avoid recursion)
        tracing::info!("Re-initializing session after expiry");
        let params = InitializeParams {
            protocol_version: crate::protocol::LATEST_PROTOCOL_VERSION.to_string(),
            capabilities: self.capabilities.clone(),
            client_info: Implementation {
                name: client_name,
                version: client_version,
                ..Default::default()
            },
            meta: None,
        };

        let result: InitializeResult = self.send_request_once("initialize", &params).await?;
        *self.server_info.write().await = Some(result);

        self.send_notification("notifications/initialized", &serde_json::json!({}))
            .await?;
        self.initialized.store(true, Ordering::Release);

        Ok(())
    }

    async fn send_notification<P: serde::Serialize>(&self, method: &str, params: &P) -> Result<()> {
        self.ensure_connected()?;
        let params_value = serde_json::to_value(params)
            .map_err(|e| Error::Transport(format!("Failed to serialize params: {}", e)))?;
        let params_value = self.with_final_request_meta(params_value).await?;

        self.command_tx
            .send(LoopCommand::Notify {
                method: method.to_string(),
                params: params_value,
            })
            .await
            .map_err(|_| Error::Transport("Connection closed".to_string()))?;

        Ok(())
    }

    async fn resolve_input_requests(&self, requests: InputRequests) -> Result<InputResponses> {
        if !self.uses_final_protocol().await {
            return Err(Error::Transport(
                "input_required results require the 2026-07-28 client lifecycle".to_string(),
            ));
        }
        for request in requests.values() {
            let declared = match request {
                InputRequest::CreateMessage(_) => self.capabilities.sampling.is_some(),
                InputRequest::ListRoots(_) => self.capabilities.roots.is_some(),
                InputRequest::Elicit(_) => self.capabilities.elicitation.is_some(),
                _ => false,
            };
            if !declared {
                return Err(Error::Transport(format!(
                    "server requested undeclared MRTR input capability: {}",
                    request.method_name()
                )));
            }
        }

        let (response_tx, response_rx) = oneshot::channel();
        self.command_tx
            .send(LoopCommand::ResolveInputs {
                requests,
                response_tx,
            })
            .await
            .map_err(|_| Error::Transport("Connection closed".to_string()))?;
        response_rx
            .await
            .map_err(|_| Error::Transport("Connection closed".to_string()))?
    }

    async fn uses_final_protocol(&self) -> bool {
        self.selected_protocol_version.read().await.as_deref()
            == Some(crate::protocol::PROTOCOL_VERSION_2026_07_28)
    }

    fn request_meta_for(&self, version: &str, client_info: &Implementation) -> RequestMeta {
        RequestMeta {
            progress_token: None,
            protocol_version: Some(version.to_string()),
            client_info: Some(client_info.clone()),
            client_capabilities: Some(self.capabilities.clone()),
            log_level: None,
        }
    }

    async fn with_final_request_meta(
        &self,
        mut params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let Some(version) = self.selected_protocol_version.read().await.clone() else {
            return Ok(params);
        };
        if version != crate::protocol::PROTOCOL_VERSION_2026_07_28 {
            return Ok(params);
        }
        let client_info = self.client_info.read().await.clone().ok_or_else(|| {
            Error::Transport("final protocol selected without client identity".to_string())
        })?;
        let required = serde_json::to_value(self.request_meta_for(&version, &client_info))
            .map_err(|e| Error::Transport(format!("Failed to serialize request metadata: {e}")))?;
        let required = required
            .as_object()
            .expect("RequestMeta serializes as an object");

        if !params.is_object() {
            params = serde_json::json!({});
        }
        let params_object = params
            .as_object_mut()
            .expect("params was normalized to object");
        let meta = params_object
            .entry("_meta")
            .or_insert_with(|| serde_json::json!({}));
        if !meta.is_object() {
            *meta = serde_json::json!({});
        }
        let meta = meta
            .as_object_mut()
            .expect("metadata was normalized to object");
        for (key, value) in required {
            meta.insert(key.clone(), value.clone());
        }

        Ok(params)
    }

    fn ensure_connected(&self) -> Result<()> {
        if !self.connected.load(Ordering::Acquire) {
            return Err(Error::Transport("Connection closed".to_string()));
        }
        Ok(())
    }

    fn ensure_initialized(&self) -> Result<()> {
        if !self.initialized.load(Ordering::Acquire) {
            return Err(Error::Transport("Client not initialized".to_string()));
        }
        Ok(())
    }
}

fn pagination_cache_key(cursor: Option<&str>) -> String {
    serde_json::to_string(&cursor).expect("pagination cursor cache key is serializable")
}

fn is_stale_tool_schema_error(error: &Error) -> bool {
    matches!(
        error,
        Error::JsonRpc(error)
            if error.code == McpErrorCode::HeaderMismatch.code()
                || error.code == ErrorCode::MethodNotFound.code()
                || error.code == ErrorCode::InvalidParams.code()
    )
}

fn decode_cached<R: serde::de::DeserializeOwned>(
    value: &serde_json::Value,
    method: &str,
) -> Option<R> {
    match serde_json::from_value(value.clone()) {
        Ok(result) => Some(result),
        Err(error) => {
            tracing::warn!(
                method,
                error = %error,
                "Discarding response-cache entry that no longer deserializes"
            );
            None
        }
    }
}

impl Drop for McpClient {
    fn drop(&mut self) {
        if let Some(task) = self.task.take() {
            task.abort();
        }
    }
}

// =============================================================================
// Background Message Loop
// =============================================================================

/// A pending request waiting for a response from the server.
struct PendingRequest {
    method: String,
    response_tx: oneshot::Sender<Result<serde_json::Value>>,
    acknowledgment_tx: Option<oneshot::Sender<SubscriptionFilter>>,
}

/// Background message loop that multiplexes incoming/outgoing messages.
async fn message_loop<T: ClientTransport, H: ClientHandler>(
    mut transport: T,
    handler: H,
    mut command_rx: mpsc::Receiver<LoopCommand>,
    connected: Arc<AtomicBool>,
    roots: Arc<RwLock<Vec<Root>>>,
    response_cache: Arc<ClientResponseCache>,
) {
    let handler = Arc::new(handler);
    let mut pending_requests: HashMap<RequestId, PendingRequest> = HashMap::new();
    let next_id = AtomicI64::new(1);

    loop {
        tokio::select! {
            // Commands from McpClient methods
            command = command_rx.recv() => {
                match command {
                    Some(LoopCommand::Request { method, params, response_tx }) => {
                        let id = RequestId::Number(next_id.fetch_add(1, Ordering::Relaxed));

                        let request = JsonRpcRequest::new(id.clone(), &method)
                            .with_params(params);
                        let json = match serde_json::to_string(&request) {
                            Ok(j) => j,
                            Err(e) => {
                                let _ = response_tx.send(Err(Error::Transport(
                                    format!("Serialization failed: {}", e)
                                )));
                                continue;
                            }
                        };

                        tracing::debug!(method = %method, id = ?id, "Sending request");
                        pending_requests.insert(id, PendingRequest {
                            method,
                            response_tx,
                            acknowledgment_tx: None,
                        });

                        if let Err(e) = transport.send(&json).await {
                            tracing::error!(error = %e, "Transport send error");
                            fail_all_pending(&mut pending_requests, &format!("Transport error: {}", e));
                            break;
                        }
                    }
                    Some(LoopCommand::StartSubscription {
                        params,
                        id_tx,
                        acknowledgment_tx,
                        response_tx,
                    }) => {
                        let id = RequestId::Number(next_id.fetch_add(1, Ordering::Relaxed));
                        let request = JsonRpcRequest::new(id.clone(), "subscriptions/listen")
                            .with_params(params);
                        let json = match serde_json::to_string(&request) {
                            Ok(json) => json,
                            Err(error) => {
                                let _ = response_tx.send(Err(Error::Transport(
                                    format!("Serialization failed: {error}")
                                )));
                                continue;
                            }
                        };

                        tracing::debug!(id = ?id, "Opening subscription");
                        pending_requests.insert(id.clone(), PendingRequest {
                            method: "subscriptions/listen".to_string(),
                            response_tx,
                            acknowledgment_tx: Some(acknowledgment_tx),
                        });
                        let _ = id_tx.send(id);

                        if let Err(error) = transport.send(&json).await {
                            tracing::error!(%error, "Subscription transport send error");
                            fail_all_pending(
                                &mut pending_requests,
                                &format!("Transport error: {error}"),
                            );
                            break;
                        }
                    }
                    Some(LoopCommand::CancelRequest {
                        request_id,
                        done_tx,
                    }) => {
                        let result = if pending_requests
                            .get(&request_id)
                            .is_some_and(|pending| pending.method == "subscriptions/listen")
                        {
                            let result = transport.cancel_request(&request_id).await;
                            if result.is_ok()
                                && let Some(pending) = pending_requests.remove(&request_id)
                            {
                                let _ = pending.response_tx.send(Err(Error::Transport(
                                    "subscription cancelled".to_string(),
                                )));
                            }
                            result
                        } else {
                            Ok(())
                        };
                        if let Some(done_tx) = done_tx {
                            let _ = done_tx.send(result);
                        }
                    }
                    Some(LoopCommand::Notify { method, params }) => {
                        let notification = JsonRpcNotification::new(&method)
                            .with_params(params);
                        if let Ok(json) = serde_json::to_string(&notification) {
                            tracing::debug!(method = %method, "Sending notification");
                            let _ = transport.send(&json).await;
                        }
                    }
                    Some(LoopCommand::ResolveInputs { requests, response_tx }) => {
                        let result = resolve_inputs_with_handler(&handler, &roots, requests).await;
                        let _ = response_tx.send(result);
                    }
                    Some(LoopCommand::ResetSession { done_tx }) => {
                        tracing::info!("Resetting transport session for re-initialization");
                        transport.reset_session().await;
                        // Fail any pending requests with session expired
                        for (_, pending) in pending_requests.drain() {
                            let _ = pending.response_tx.send(Err(Error::SessionExpired));
                        }
                        let _ = done_tx.send(());
                    }
                    Some(LoopCommand::Shutdown) | None => {
                        tracing::debug!("Message loop shutting down");
                        break;
                    }
                }
            }

            // Incoming messages from the server
            result = transport.recv() => {
                match result {
                    Ok(Some(line)) => {
                        handle_incoming(
                            &line,
                            &mut pending_requests,
                            &handler,
                            &roots,
                            &mut transport,
                            &response_cache,
                        ).await;
                    }
                    Ok(None) => {
                        tracing::info!("Transport closed (EOF)");
                        break;
                    }
                    Err(e) => {
                        tracing::error!(error = %e, "Transport receive error");
                        break;
                    }
                }
            }
        }
    }

    // Cleanup
    connected.store(false, Ordering::Release);
    fail_all_pending(&mut pending_requests, "Connection closed");
    let _ = transport.close().await;
}

async fn resolve_inputs_with_handler<H: ClientHandler>(
    handler: &Arc<H>,
    roots: &Arc<RwLock<Vec<Root>>>,
    requests: InputRequests,
) -> Result<InputResponses> {
    let mut responses = InputResponses::new();
    for (key, request) in requests {
        let response = match request {
            InputRequest::CreateMessage(params) => InputResponse::CreateMessage(
                handler
                    .handle_create_message(params)
                    .await
                    .map_err(Error::JsonRpc)?,
            ),
            InputRequest::ListRoots(_) => {
                let configured = roots.read().await.clone();
                let result = if configured.is_empty() {
                    handler.handle_list_roots().await.map_err(Error::JsonRpc)?
                } else {
                    ListRootsResult {
                        roots: configured,
                        meta: None,
                    }
                };
                InputResponse::ListRoots(result)
            }
            InputRequest::Elicit(params) => InputResponse::Elicit(
                handler
                    .handle_elicit(params)
                    .await
                    .map_err(Error::JsonRpc)?,
            ),
            _ => {
                return Err(Error::Transport(
                    "unsupported MRTR input request method".to_string(),
                ));
            }
        };
        responses.insert(key, response);
    }
    Ok(responses)
}

/// Handle a single incoming message from the server.
async fn handle_incoming<T: ClientTransport, H: ClientHandler>(
    line: &str,
    pending_requests: &mut HashMap<RequestId, PendingRequest>,
    handler: &Arc<H>,
    roots: &Arc<RwLock<Vec<Root>>>,
    transport: &mut T,
    response_cache: &Arc<ClientResponseCache>,
) {
    let parsed: serde_json::Value = match serde_json::from_str(line) {
        Ok(v) => v,
        Err(e) => {
            tracing::warn!(error = %e, "Failed to parse incoming message");
            return;
        }
    };

    // Case 1: Response to one of our pending requests (has result or error, no method)
    if parsed.get("method").is_none()
        && (parsed.get("result").is_some() || parsed.get("error").is_some())
    {
        // Check for session-level errors (id: null with -32005) that affect
        // all pending requests, not just a specific one.
        if let Some(error) = parsed.get("error") {
            let code = error.get("code").and_then(|c| c.as_i64()).unwrap_or(0) as i32;
            let id_missing_or_null = parsed.get("id").is_none_or(|id| id.is_null());
            if code == -32005 && id_missing_or_null {
                tracing::warn!(
                    "Session expired (-32005 with null id), failing all pending requests"
                );
                for (_, pending) in pending_requests.drain() {
                    let _ = pending.response_tx.send(Err(Error::SessionExpired));
                }
                return;
            }
        }

        handle_response(&parsed, pending_requests);
        return;
    }

    // Case 2: Server-initiated request (has id + method)
    if parsed.get("id").is_some() && parsed.get("method").is_some() {
        let id = parse_request_id(&parsed);
        let method = parsed["method"].as_str().unwrap_or("");
        let params = parsed.get("params").cloned();

        let result = dispatch_server_request(handler, roots, method, params).await;

        // Send response back to the server
        let response = match result {
            Ok(value) => {
                if let Some(id) = id {
                    serde_json::json!({
                        "jsonrpc": "2.0",
                        "id": id,
                        "result": value
                    })
                } else {
                    return;
                }
            }
            Err(error) => {
                serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": id,
                    "error": {
                        "code": error.code,
                        "message": error.message
                    }
                })
            }
        };

        if let Ok(json) = serde_json::to_string(&response) {
            let _ = transport.send(&json).await;
        }
        return;
    }

    // Case 3: Server notification (has method, no id)
    if parsed.get("method").is_some() && parsed.get("id").is_none() {
        let method = parsed["method"].as_str().unwrap_or("");
        let params = parsed.get("params").cloned();
        invalidate_response_cache(response_cache, method, params.as_ref()).await;
        let notification = parse_server_notification(method, params);
        let should_dispatch = match &notification {
            ServerNotification::SubscriptionAcknowledged {
                subscription_id,
                notifications,
            } => {
                let Some(key) = matching_subscription_id(pending_requests, subscription_id) else {
                    tracing::warn!(
                        id = ?subscription_id,
                        "Ignoring acknowledgment for unknown subscription"
                    );
                    return;
                };
                if let Some(sender) = pending_requests
                    .get_mut(&key)
                    .and_then(|pending| pending.acknowledgment_tx.take())
                {
                    let _ = sender.send(notifications.clone());
                    true
                } else {
                    tracing::warn!(
                        id = ?subscription_id,
                        "Ignoring duplicate subscription acknowledgment"
                    );
                    false
                }
            }
            ServerNotification::Subscription {
                subscription_id, ..
            } => {
                let Some(key) = matching_subscription_id(pending_requests, subscription_id) else {
                    tracing::warn!(
                        id = ?subscription_id,
                        "Ignoring notification for unknown subscription"
                    );
                    return;
                };
                let before_acknowledgment = pending_requests
                    .get(&key)
                    .is_some_and(|pending| pending.acknowledgment_tx.is_some());
                if before_acknowledgment {
                    tracing::warn!(
                        id = ?subscription_id,
                        "Ending subscription that received a notification before acknowledgment"
                    );
                    if let Some(pending) = pending_requests.remove(&key) {
                        let _ = pending.response_tx.send(Err(Error::Transport(
                            "subscription notification arrived before acknowledgment".to_string(),
                        )));
                    }
                    false
                } else {
                    true
                }
            }
            ServerNotification::SubscriptionCancelled {
                subscription_id,
                reason,
            } => {
                let Some(key) = matching_subscription_id(pending_requests, subscription_id) else {
                    tracing::warn!(
                        id = ?subscription_id,
                        "Ignoring cancellation for unknown or non-subscription request"
                    );
                    return;
                };
                if let Some(pending) = pending_requests.remove(&key) {
                    let message = reason.as_deref().map_or_else(
                        || "subscription cancelled by server".to_string(),
                        |reason| format!("subscription cancelled by server: {reason}"),
                    );
                    let _ = pending.response_tx.send(Err(Error::Transport(message)));
                }
                true
            }
            _ => true,
        };
        if should_dispatch {
            handler.on_notification(notification).await;
        }
    }
}

fn matching_subscription_id(
    pending_requests: &HashMap<RequestId, PendingRequest>,
    id: &RequestId,
) -> Option<RequestId> {
    if pending_requests
        .get(id)
        .is_some_and(|pending| pending.method == "subscriptions/listen")
    {
        return Some(id.clone());
    }
    pending_requests.iter().find_map(|(candidate, pending)| {
        (pending.method == "subscriptions/listen" && request_ids_match(candidate, id))
            .then(|| candidate.clone())
    })
}

fn request_ids_match(left: &RequestId, right: &RequestId) -> bool {
    left == right
        || matches!(
            (left, right),
            (RequestId::Number(number), RequestId::String(value))
                | (RequestId::String(value), RequestId::Number(number))
                if value.parse::<i64>() == Ok(*number)
        )
}

async fn invalidate_response_cache(
    response_cache: &ClientResponseCache,
    method: &str,
    params: Option<&serde_json::Value>,
) {
    match method {
        notifications::TOOLS_LIST_CHANGED => {
            response_cache.evict_method("tools/list").await;
        }
        notifications::PROMPTS_LIST_CHANGED => {
            response_cache.evict_method("prompts/list").await;
        }
        notifications::RESOURCES_LIST_CHANGED => {
            response_cache.evict_method("resources/list").await;
            response_cache
                .evict_method("resources/templates/list")
                .await;
        }
        notifications::RESOURCE_UPDATED => {
            if let Some(uri) = params
                .and_then(|value| value.get("uri"))
                .and_then(serde_json::Value::as_str)
            {
                response_cache.evict_resource(uri).await;
            }
        }
        _ => {}
    }
}

/// Handle a JSON-RPC response by routing to the pending request.
fn handle_response(
    parsed: &serde_json::Value,
    pending_requests: &mut HashMap<RequestId, PendingRequest>,
) {
    let id = match parse_request_id(parsed) {
        Some(id) => id,
        None => {
            tracing::warn!("Response without id");
            return;
        }
    };

    // Exact match first; genuine string IDs always take precedence. As a
    // fallback, accept a response whose id is the string form of a numeric
    // request id ("42" matching 42) -- some servers stringify numeric ids
    // when echoing them (rmcp #1021 analog).
    let pending = match pending_requests.remove(&id) {
        Some(p) => p,
        None => {
            let numeric_fallback = match &id {
                RequestId::String(s) => s
                    .parse::<i64>()
                    .ok()
                    .and_then(|n| pending_requests.remove(&RequestId::Number(n))),
                _ => None,
            };
            match numeric_fallback {
                Some(p) => p,
                None => {
                    tracing::warn!(id = ?id, "Response for unknown request");
                    return;
                }
            }
        }
    };

    tracing::debug!(id = ?id, "Received response");

    if let Some(error) = parsed.get("error") {
        let code = error.get("code").and_then(|c| c.as_i64()).unwrap_or(-1) as i32;
        let message = error
            .get("message")
            .and_then(|m| m.as_str())
            .unwrap_or("Unknown error")
            .to_string();
        let data = error.get("data").cloned();

        // -32005 = SessionNotFound: signal session expiry for recovery
        if code == -32005 {
            let _ = pending.response_tx.send(Err(Error::SessionExpired));
            return;
        }

        let json_rpc_error = JsonRpcError {
            code,
            message,
            data,
        };
        let _ = pending
            .response_tx
            .send(Err(Error::JsonRpc(json_rpc_error)));
    } else if let Some(result) = parsed.get("result") {
        if pending.method == "subscriptions/listen" && pending.acknowledgment_tx.is_some() {
            let _ = pending.response_tx.send(Err(Error::Transport(
                "subscriptions/listen completed before acknowledgment".to_string(),
            )));
            return;
        }
        let _ = pending.response_tx.send(Ok(result.clone()));
    } else {
        let _ = pending
            .response_tx
            .send(Err(Error::Transport("Invalid response".to_string())));
    }
}

/// Dispatch a server-initiated request to the handler.
async fn dispatch_server_request<H: ClientHandler>(
    handler: &Arc<H>,
    roots: &Arc<RwLock<Vec<Root>>>,
    method: &str,
    params: Option<serde_json::Value>,
) -> std::result::Result<serde_json::Value, JsonRpcError> {
    match method {
        "sampling/createMessage" => {
            let p = serde_json::from_value(params.unwrap_or_default())
                .map_err(|e| JsonRpcError::invalid_params(e.to_string()))?;
            let result = handler.handle_create_message(p).await?;
            serde_json::to_value(result).map_err(|e| JsonRpcError::internal_error(e.to_string()))
        }
        "elicitation/create" => {
            let p = serde_json::from_value(params.unwrap_or_default())
                .map_err(|e| JsonRpcError::invalid_params(e.to_string()))?;
            let result = handler.handle_elicit(p).await?;
            serde_json::to_value(result).map_err(|e| JsonRpcError::internal_error(e.to_string()))
        }
        "roots/list" => {
            // Use client-configured roots if available, otherwise delegate to handler
            let roots_list = roots.read().await;
            if !roots_list.is_empty() {
                let result = ListRootsResult {
                    roots: roots_list.clone(),
                    meta: None,
                };
                return serde_json::to_value(result)
                    .map_err(|e| JsonRpcError::internal_error(e.to_string()));
            }
            drop(roots_list);

            let result = handler.handle_list_roots().await?;
            serde_json::to_value(result).map_err(|e| JsonRpcError::internal_error(e.to_string()))
        }
        "ping" => Ok(serde_json::json!({})),
        _ => Err(JsonRpcError::method_not_found(method)),
    }
}

/// Parse a request ID from a JSON-RPC message.
fn parse_request_id(parsed: &serde_json::Value) -> Option<RequestId> {
    parsed.get("id").and_then(|id| {
        if let Some(n) = id.as_i64() {
            Some(RequestId::Number(n))
        } else {
            id.as_str().map(|s| RequestId::String(s.to_string()))
        }
    })
}

/// Parse a server notification into the typed enum.
fn parse_server_notification(
    method: &str,
    params: Option<serde_json::Value>,
) -> ServerNotification {
    if method == notifications::SUBSCRIPTIONS_ACKNOWLEDGED {
        if let Some(params) = &params
            && let Ok(acknowledgment) =
                serde_json::from_value::<SubscriptionsAcknowledgedParams>(params.clone())
            && let Some(subscription_id) = acknowledgment.meta.and_then(|meta| meta.subscription_id)
        {
            return ServerNotification::SubscriptionAcknowledged {
                subscription_id,
                notifications: acknowledgment.notifications,
            };
        }
        return ServerNotification::Unknown {
            method: method.to_string(),
            params,
        };
    }
    if method == notifications::CANCELLED {
        if let Some(params) = &params
            && let Ok(cancelled) = serde_json::from_value::<CancelledParams>(params.clone())
            && let Some(subscription_id) = cancelled.request_id
        {
            return ServerNotification::SubscriptionCancelled {
                subscription_id,
                reason: cancelled.reason,
            };
        }
        return ServerNotification::Unknown {
            method: method.to_string(),
            params,
        };
    }

    let subscription_id = params
        .as_ref()
        .and_then(|params| params.pointer("/_meta/io.modelcontextprotocol~1subscriptionId"))
        .and_then(|id| serde_json::from_value::<RequestId>(id.clone()).ok());
    let notification = match method {
        notifications::PROGRESS => {
            if let Some(params) = params.clone()
                && let Ok(p) = serde_json::from_value(params)
            {
                ServerNotification::Progress(p)
            } else {
                ServerNotification::Unknown {
                    method: method.to_string(),
                    params: None,
                }
            }
        }
        notifications::MESSAGE => {
            if let Some(params) = params.clone()
                && let Ok(p) = serde_json::from_value(params)
            {
                ServerNotification::LogMessage(p)
            } else {
                ServerNotification::Unknown {
                    method: method.to_string(),
                    params: None,
                }
            }
        }
        notifications::RESOURCE_UPDATED => {
            if let Some(params) = &params
                && let Some(uri) = params.get("uri").and_then(|u| u.as_str())
            {
                ServerNotification::ResourceUpdated {
                    uri: uri.to_string(),
                }
            } else {
                ServerNotification::Unknown {
                    method: method.to_string(),
                    params: params.clone(),
                }
            }
        }
        notifications::RESOURCES_LIST_CHANGED => ServerNotification::ResourcesListChanged,
        notifications::TOOLS_LIST_CHANGED => ServerNotification::ToolsListChanged,
        notifications::PROMPTS_LIST_CHANGED => ServerNotification::PromptsListChanged,
        notifications::TASK_STATUS_CHANGED => {
            let is_final = params
                .as_ref()
                .and_then(serde_json::Value::as_object)
                .is_some_and(|params| params.contains_key("ttlMs"));
            match (is_final, params.clone()) {
                (true, Some(params)) => {
                    match serde_json::from_value::<crate::tasks::TaskStatusNotificationParams>(
                        params.clone(),
                    ) {
                        Ok(params) => ServerNotification::FinalTaskStatusChanged(params),
                        Err(_) => ServerNotification::Unknown {
                            method: method.to_string(),
                            params: Some(params),
                        },
                    }
                }
                (false, Some(params)) => {
                    match serde_json::from_value::<TaskStatusParams>(params.clone()) {
                        Ok(params) => ServerNotification::TaskStatusChanged(params),
                        Err(_) => ServerNotification::Unknown {
                            method: method.to_string(),
                            params: Some(params),
                        },
                    }
                }
                (_, None) => ServerNotification::Unknown {
                    method: method.to_string(),
                    params: None,
                },
            }
        }
        _ => ServerNotification::Unknown {
            method: method.to_string(),
            params: params.clone(),
        },
    };
    if let Some(subscription_id) = subscription_id {
        ServerNotification::Subscription {
            subscription_id,
            notification: Box::new(notification),
        }
    } else {
        notification
    }
}

/// Fail all pending requests with the given error message.
fn fail_all_pending(pending: &mut HashMap<RequestId, PendingRequest>, reason: &str) {
    for (_, req) in pending.drain() {
        let _ = req
            .response_tx
            .send(Err(Error::Transport(reason.to_string())));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use async_trait::async_trait;
    use std::sync::Mutex;

    /// Mock transport for testing that auto-responds to requests.
    ///
    /// When the client sends a request via `send()`, the mock extracts the
    /// request ID, pairs it with the next preconfigured response, and feeds
    /// it back through a channel that `recv()` awaits on. This ensures
    /// `recv()` blocks when no messages are available (instead of returning
    /// EOF), keeping the background message loop alive.
    struct MockTransport {
        /// Pre-configured result or error replies (not full envelopes).
        responses: Arc<Mutex<Vec<MockReply>>>,
        /// Index of the next response to use.
        response_idx: Arc<std::sync::atomic::AtomicUsize>,
        /// Channel sender for feeding responses back to `recv()`.
        incoming_tx: mpsc::Sender<String>,
        /// Channel receiver for `recv()` to await on.
        incoming_rx: mpsc::Receiver<String>,
        /// Collected outgoing messages from `send()`.
        outgoing: Arc<Mutex<Vec<String>>>,
        connected: Arc<AtomicBool>,
    }

    enum MockReply {
        Result(serde_json::Value),
        Error(JsonRpcError),
    }

    #[allow(dead_code)]
    impl MockTransport {
        fn new() -> Self {
            let (tx, rx) = mpsc::channel(32);
            Self {
                responses: Arc::new(Mutex::new(Vec::new())),
                response_idx: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
                incoming_tx: tx,
                incoming_rx: rx,
                outgoing: Arc::new(Mutex::new(Vec::new())),
                connected: Arc::new(AtomicBool::new(true)),
            }
        }

        /// Create a mock that auto-responds with the given result payloads.
        ///
        /// When `send()` receives a JSON-RPC request, it extracts the request
        /// ID and pairs it with the next response from this list, sending the
        /// complete JSON-RPC response through the channel for `recv()`.
        fn with_responses(responses: Vec<serde_json::Value>) -> Self {
            let (tx, rx) = mpsc::channel(32);
            Self {
                responses: Arc::new(Mutex::new(
                    responses.into_iter().map(MockReply::Result).collect(),
                )),
                response_idx: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
                incoming_tx: tx,
                incoming_rx: rx,
                outgoing: Arc::new(Mutex::new(Vec::new())),
                connected: Arc::new(AtomicBool::new(true)),
            }
        }

        fn with_replies(responses: Vec<MockReply>) -> Self {
            let (tx, rx) = mpsc::channel(32);
            Self {
                responses: Arc::new(Mutex::new(responses)),
                response_idx: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
                incoming_tx: tx,
                incoming_rx: rx,
                outgoing: Arc::new(Mutex::new(Vec::new())),
                connected: Arc::new(AtomicBool::new(true)),
            }
        }
    }

    #[async_trait]
    impl ClientTransport for MockTransport {
        async fn send(&mut self, message: &str) -> Result<()> {
            self.outgoing.lock().unwrap().push(message.to_string());

            // Parse the outgoing message to extract the request ID
            if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(message) {
                // Only respond to requests (messages with an id and method)
                if let Some(id) = parsed.get("id") {
                    let idx = self
                        .response_idx
                        .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                    let responses = self.responses.lock().unwrap();
                    if let Some(reply) = responses.get(idx) {
                        let response = match reply {
                            MockReply::Result(result) => serde_json::json!({
                                "jsonrpc": "2.0",
                                "id": id,
                                "result": result
                            }),
                            MockReply::Error(error) => serde_json::json!({
                                "jsonrpc": "2.0",
                                "id": id,
                                "error": error
                            }),
                        };
                        let _ = self.incoming_tx.try_send(response.to_string());
                    }
                }
            }

            Ok(())
        }

        async fn recv(&mut self) -> Result<Option<String>> {
            // Await on the channel -- blocks until a message is available
            // or the sender is dropped (returns None = EOF).
            match self.incoming_rx.recv().await {
                Some(msg) => Ok(Some(msg)),
                None => Ok(None),
            }
        }

        fn is_connected(&self) -> bool {
            self.connected.load(Ordering::Relaxed)
        }

        async fn close(&mut self) -> Result<()> {
            self.connected.store(false, Ordering::Relaxed);
            Ok(())
        }
    }

    fn mock_initialize_response() -> serde_json::Value {
        serde_json::json!({
            "protocolVersion": "2025-11-25",
            "serverInfo": {
                "name": "test-server",
                "version": "1.0.0"
            },
            "capabilities": {
                "tools": {}
            }
        })
    }

    #[tokio::test]
    async fn test_client_not_initialized() {
        let client = McpClient::connect(MockTransport::with_responses(vec![]))
            .await
            .unwrap();

        let result = client.list_tools().await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not initialized"));
    }

    #[tokio::test]
    async fn test_client_initialize() {
        let client = McpClient::connect(MockTransport::with_responses(vec![
            mock_initialize_response(),
        ]))
        .await
        .unwrap();

        assert!(!client.is_initialized());

        let result = client.initialize("test-client", "1.0.0").await;
        assert!(result.is_ok());
        assert!(client.is_initialized());

        let server_info = client.server_info().await.unwrap();
        assert_eq!(server_info.server_info.name, "test-server");
    }

    #[cfg(any(feature = "protocol-2026-07-28", feature = "stateless"))]
    #[tokio::test]
    async fn final_discover_injects_metadata_on_every_request() {
        let transport = MockTransport::with_responses(vec![
            serde_json::json!({
                "resultType": "complete",
                "supportedVersions": ["2026-07-28"],
                "capabilities": {}
            }),
            serde_json::json!({
                "resultType": "complete",
                "tools": [],
                "ttlMs": 0,
                "cacheScope": "private"
            }),
        ]);
        let outgoing = transport.outgoing.clone();
        let client = McpClient::builder()
            .protocol_support(ProtocolSupport::try_new(["2026-07-28"]).unwrap())
            .with_elicitation()
            .connect_simple(transport)
            .await
            .unwrap();

        client.discover("test-client", "1.0.0").await.unwrap();
        client.list_tools().await.unwrap();
        assert_eq!(
            client.selected_protocol_version().await.as_deref(),
            Some("2026-07-28")
        );

        let messages: Vec<serde_json::Value> = outgoing
            .lock()
            .unwrap()
            .iter()
            .map(|message| serde_json::from_str(message).unwrap())
            .collect();
        assert_eq!(messages.len(), 2);
        assert_eq!(messages[0]["method"], "server/discover");
        assert_eq!(messages[1]["method"], "tools/list");
        for message in messages {
            let meta = &message["params"]["_meta"];
            assert_eq!(
                meta["io.modelcontextprotocol/protocolVersion"],
                "2026-07-28"
            );
            assert_eq!(
                meta["io.modelcontextprotocol/clientInfo"]["name"],
                "test-client"
            );
            assert!(meta["io.modelcontextprotocol/clientCapabilities"].is_object());
        }
    }

    #[cfg(any(feature = "protocol-2026-07-28", feature = "stateless"))]
    fn final_discover_result() -> serde_json::Value {
        serde_json::json!({
            "resultType": "complete",
            "supportedVersions": ["2026-07-28"],
            "capabilities": {},
            "ttlMs": 0,
            "cacheScope": "private"
        })
    }

    #[cfg(any(feature = "protocol-2026-07-28", feature = "stateless"))]
    struct SubscriptionTestTransport {
        incoming_tx: mpsc::Sender<String>,
        incoming_rx: mpsc::Receiver<String>,
        outgoing: Arc<Mutex<Vec<String>>>,
        connected: Arc<AtomicBool>,
    }

    #[cfg(any(feature = "protocol-2026-07-28", feature = "stateless"))]
    impl SubscriptionTestTransport {
        fn new() -> Self {
            let (incoming_tx, incoming_rx) = mpsc::channel(32);
            Self {
                incoming_tx,
                incoming_rx,
                outgoing: Arc::new(Mutex::new(Vec::new())),
                connected: Arc::new(AtomicBool::new(true)),
            }
        }
    }

    #[cfg(any(feature = "protocol-2026-07-28", feature = "stateless"))]
    #[async_trait]
    impl ClientTransport for SubscriptionTestTransport {
        async fn send(&mut self, message: &str) -> Result<()> {
            self.outgoing.lock().unwrap().push(message.to_string());
            let value: serde_json::Value = serde_json::from_str(message)
                .map_err(|error| Error::Transport(error.to_string()))?;
            let Some(id) = value.get("id").cloned() else {
                return Ok(());
            };
            match value
                .get("method")
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default()
            {
                "server/discover" => {
                    self.incoming_tx
                        .send(
                            serde_json::json!({
                                "jsonrpc": "2.0",
                                "id": id,
                                "result": final_discover_result()
                            })
                            .to_string(),
                        )
                        .await
                        .map_err(|_| Error::Transport("test channel closed".to_string()))?;
                }
                "subscriptions/listen" => {
                    let notifications = value["params"]["notifications"].clone();
                    self.incoming_tx
                        .send(
                            serde_json::json!({
                                "jsonrpc": "2.0",
                                "method": notifications::SUBSCRIPTIONS_ACKNOWLEDGED,
                                "params": {
                                    "_meta": {
                                        "io.modelcontextprotocol/subscriptionId": id
                                    },
                                    "notifications": notifications
                                }
                            })
                            .to_string(),
                        )
                        .await
                        .map_err(|_| Error::Transport("test channel closed".to_string()))?;

                    if value["params"]["notifications"]["promptsListChanged"]
                        == serde_json::Value::Bool(true)
                    {
                        self.incoming_tx
                            .send(
                                serde_json::json!({
                                    "jsonrpc": "2.0",
                                    "id": id,
                                    "result": {
                                        "resultType": "complete",
                                        "_meta": {
                                            "io.modelcontextprotocol/subscriptionId": id
                                        }
                                    }
                                })
                                .to_string(),
                            )
                            .await
                            .map_err(|_| Error::Transport("test channel closed".to_string()))?;
                    } else {
                        self.incoming_tx
                            .send(
                                serde_json::json!({
                                    "jsonrpc": "2.0",
                                    "method": notifications::TOOLS_LIST_CHANGED,
                                    "params": {
                                        "_meta": {
                                            "io.modelcontextprotocol/subscriptionId": id
                                        }
                                    }
                                })
                                .to_string(),
                            )
                            .await
                            .map_err(|_| Error::Transport("test channel closed".to_string()))?;
                    }
                }
                _ => {}
            }
            Ok(())
        }

        async fn recv(&mut self) -> Result<Option<String>> {
            Ok(self.incoming_rx.recv().await)
        }

        fn is_connected(&self) -> bool {
            self.connected.load(Ordering::Acquire)
        }

        async fn close(&mut self) -> Result<()> {
            self.connected.store(false, Ordering::Release);
            Ok(())
        }
    }

    #[cfg(any(feature = "protocol-2026-07-28", feature = "stateless"))]
    #[tokio::test]
    async fn final_subscriptions_correlate_and_cancel_over_message_transport() {
        let transport = SubscriptionTestTransport::new();
        let outgoing = transport.outgoing.clone();
        let incoming = transport.incoming_tx.clone();
        let received = Arc::new(Mutex::new(Vec::new()));

        struct RecordingHandler(Arc<Mutex<Vec<ServerNotification>>>);

        #[async_trait]
        impl ClientHandler for RecordingHandler {
            async fn on_notification(&self, notification: ServerNotification) {
                self.0.lock().unwrap().push(notification);
            }
        }

        let client = McpClient::builder()
            .protocol_support(ProtocolSupport::try_new(["2026-07-28"]).unwrap())
            .connect(transport, RecordingHandler(received.clone()))
            .await
            .unwrap();
        client.discover("test-client", "1.0.0").await.unwrap();

        let requested = SubscriptionFilter {
            tools_list_changed: Some(true),
            ..Default::default()
        };
        let mut first = client
            .listen_subscriptions(requested.clone())
            .await
            .unwrap();
        let mut second = client.listen_subscriptions(requested).await.unwrap();
        assert_ne!(first.id(), second.id());
        assert_eq!(
            first.acknowledged().await.unwrap().tools_list_changed,
            Some(true)
        );
        assert_eq!(
            second.acknowledged().await.unwrap().tools_list_changed,
            Some(true)
        );

        for _ in 0..100 {
            if received
                .lock()
                .unwrap()
                .iter()
                .filter(|notification| {
                    matches!(
                        notification,
                        ServerNotification::Subscription {
                            notification,
                            ..
                        } if matches!(notification.as_ref(), ServerNotification::ToolsListChanged)
                    )
                })
                .count()
                == 2
            {
                break;
            }
            tokio::task::yield_now().await;
        }
        let subscription_ids: Vec<RequestId> = received
            .lock()
            .unwrap()
            .iter()
            .filter_map(|notification| match notification {
                ServerNotification::Subscription {
                    subscription_id,
                    notification,
                } if matches!(notification.as_ref(), ServerNotification::ToolsListChanged) => {
                    Some(subscription_id.clone())
                }
                _ => None,
            })
            .collect();
        assert_eq!(subscription_ids, [first.id().clone(), second.id().clone()]);

        incoming
            .send(
                serde_json::json!({
                    "jsonrpc": "2.0",
                    "method": notifications::CANCELLED,
                    "params": {
                        "requestId": 999,
                        "reason": "not a subscription"
                    }
                })
                .to_string(),
            )
            .await
            .unwrap();
        tokio::task::yield_now().await;
        assert!(
            !received.lock().unwrap().iter().any(|notification| matches!(
                notification,
                ServerNotification::SubscriptionCancelled { subscription_id, .. }
                    if subscription_id == &RequestId::Number(999)
            ))
        );

        let first_id = first.id().clone();
        let second_id = second.id().clone();
        first.cancel().await.unwrap();
        second.cancel().await.unwrap();
        let cancellation_ids: Vec<RequestId> = outgoing
            .lock()
            .unwrap()
            .iter()
            .filter_map(|message| {
                let value: serde_json::Value = serde_json::from_str(message).unwrap();
                (value["method"] == notifications::CANCELLED)
                    .then(|| serde_json::from_value(value["params"]["requestId"].clone()).unwrap())
            })
            .collect();
        assert_eq!(cancellation_ids, [first_id, second_id]);
    }

    #[cfg(any(feature = "protocol-2026-07-28", feature = "stateless"))]
    #[tokio::test]
    async fn final_subscription_observes_graceful_completion() {
        let client = McpClient::builder()
            .protocol_support(ProtocolSupport::try_new(["2026-07-28"]).unwrap())
            .connect_simple(SubscriptionTestTransport::new())
            .await
            .unwrap();
        client.discover("test-client", "1.0.0").await.unwrap();

        let mut handle = client
            .listen_subscriptions(SubscriptionFilter {
                prompts_list_changed: Some(true),
                ..Default::default()
            })
            .await
            .unwrap();
        assert_eq!(
            handle.acknowledged().await.unwrap().prompts_list_changed,
            Some(true)
        );
        let expected_id = handle.id().clone();
        let result = handle.wait().await.unwrap();
        assert!(result.result_type.is_complete());
        assert_eq!(result.meta.subscription_id, expected_id);
    }

    #[cfg(any(feature = "protocol-2026-07-28", feature = "stateless"))]
    #[tokio::test]
    async fn final_subscription_accepts_server_cancellation_only_for_active_listen() {
        let transport = SubscriptionTestTransport::new();
        let incoming = transport.incoming_tx.clone();
        let client = McpClient::builder()
            .protocol_support(ProtocolSupport::try_new(["2026-07-28"]).unwrap())
            .connect_simple(transport)
            .await
            .unwrap();
        client.discover("test-client", "1.0.0").await.unwrap();

        let mut handle = client
            .listen_subscriptions(SubscriptionFilter {
                tools_list_changed: Some(true),
                ..Default::default()
            })
            .await
            .unwrap();
        handle.acknowledged().await.unwrap();
        let id = handle.id().clone();
        incoming
            .send(
                serde_json::json!({
                    "jsonrpc": "2.0",
                    "method": notifications::CANCELLED,
                    "params": {
                        "requestId": id,
                        "reason": "server shutdown"
                    }
                })
                .to_string(),
            )
            .await
            .unwrap();

        let error = handle.wait().await.unwrap_err();
        assert!(
            error
                .to_string()
                .contains("subscription cancelled by server: server shutdown")
        );
    }

    #[cfg(any(feature = "protocol-2026-07-28", feature = "stateless"))]
    fn cacheable_tools_result(name: &str) -> serde_json::Value {
        serde_json::json!({
            "resultType": "complete",
            "tools": [{
                "name": name,
                "inputSchema": {
                    "type": "object",
                    "properties": {}
                }
            }],
            "ttlMs": 60_000,
            "cacheScope": "private"
        })
    }

    #[cfg(any(feature = "protocol-2026-07-28", feature = "stateless"))]
    #[tokio::test]
    async fn final_cache_serves_a_fresh_list_without_a_round_trip() {
        let transport = MockTransport::with_responses(vec![
            final_discover_result(),
            cacheable_tools_result("cached"),
        ]);
        let outgoing = transport.outgoing.clone();
        let client = McpClient::builder()
            .protocol_support(ProtocolSupport::try_new(["2026-07-28"]).unwrap())
            .connect_simple(transport)
            .await
            .unwrap();
        client.discover("test-client", "1.0.0").await.unwrap();

        let first = client.list_tools().await.unwrap();
        let second = client.list_tools().await.unwrap();

        assert_eq!(first.tools[0].name, "cached");
        assert_eq!(second.tools[0].name, "cached");
        assert_eq!(outgoing.lock().unwrap().len(), 2);
        assert_eq!(client.response_cache_len().await, 1);
    }

    #[cfg(any(feature = "protocol-2026-07-28", feature = "stateless"))]
    #[tokio::test]
    async fn disabling_final_cache_forces_each_list_request() {
        let transport = MockTransport::with_responses(vec![
            final_discover_result(),
            cacheable_tools_result("first"),
            cacheable_tools_result("second"),
        ]);
        let outgoing = transport.outgoing.clone();
        let client = McpClient::builder()
            .protocol_support(ProtocolSupport::try_new(["2026-07-28"]).unwrap())
            .disable_response_cache()
            .connect_simple(transport)
            .await
            .unwrap();
        client.discover("test-client", "1.0.0").await.unwrap();

        assert_eq!(client.list_tools().await.unwrap().tools[0].name, "first");
        assert_eq!(client.list_tools().await.unwrap().tools[0].name, "second");
        assert_eq!(outgoing.lock().unwrap().len(), 3);
        assert_eq!(client.response_cache_len().await, 0);
    }

    #[cfg(any(feature = "protocol-2026-07-28", feature = "stateless"))]
    #[tokio::test]
    async fn list_changed_notification_invalidates_a_fresh_entry() {
        let transport = MockTransport::with_responses(vec![
            final_discover_result(),
            cacheable_tools_result("first"),
            cacheable_tools_result("second"),
        ]);
        let incoming = transport.incoming_tx.clone();
        let outgoing = transport.outgoing.clone();
        let notification_seen = Arc::new(AtomicBool::new(false));
        let handler = NotificationHandler::new().on_tools_changed({
            let notification_seen = notification_seen.clone();
            move || notification_seen.store(true, Ordering::Release)
        });
        let client = McpClient::builder()
            .protocol_support(ProtocolSupport::try_new(["2026-07-28"]).unwrap())
            .connect(transport, handler)
            .await
            .unwrap();
        client.discover("test-client", "1.0.0").await.unwrap();
        assert_eq!(client.list_tools().await.unwrap().tools[0].name, "first");

        incoming
            .send(
                serde_json::json!({
                    "jsonrpc": "2.0",
                    "method": notifications::TOOLS_LIST_CHANGED,
                    "params": {}
                })
                .to_string(),
            )
            .await
            .unwrap();
        for _ in 0..100 {
            if notification_seen.load(Ordering::Acquire) {
                break;
            }
            tokio::task::yield_now().await;
        }
        assert!(notification_seen.load(Ordering::Acquire));

        assert_eq!(client.list_tools().await.unwrap().tools[0].name, "second");
        assert_eq!(outgoing.lock().unwrap().len(), 3);
    }

    #[cfg(any(feature = "protocol-2026-07-28", feature = "stateless"))]
    #[tokio::test]
    async fn rotating_private_partition_refetches_resource() {
        let resource_result = |text: &str| {
            serde_json::json!({
                "resultType": "complete",
                "contents": [{
                    "uri": "config://app",
                    "text": text
                }],
                "ttlMs": 60_000,
                "cacheScope": "private"
            })
        };
        let transport = MockTransport::with_responses(vec![
            final_discover_result(),
            resource_result("principal-a"),
            resource_result("principal-b"),
        ]);
        let outgoing = transport.outgoing.clone();
        let client = McpClient::builder()
            .protocol_support(ProtocolSupport::try_new(["2026-07-28"]).unwrap())
            .response_cache(ClientCacheConfig::default().with_partition("principal-a"))
            .connect_simple(transport)
            .await
            .unwrap();
        client.discover("test-client", "1.0.0").await.unwrap();

        assert_eq!(
            client
                .read_resource("config://app")
                .await
                .unwrap()
                .first_text(),
            Some("principal-a")
        );
        client.set_cache_partition("principal-b").await;
        assert_eq!(
            client
                .read_resource("config://app")
                .await
                .unwrap()
                .first_text(),
            Some("principal-b")
        );
        assert_eq!(outgoing.lock().unwrap().len(), 3);
    }

    #[cfg(any(feature = "protocol-2026-07-28", feature = "stateless"))]
    #[tokio::test]
    async fn final_tool_call_refreshes_stale_schema_and_retries_once() {
        let transport = MockTransport::with_replies(vec![
            MockReply::Result(final_discover_result()),
            MockReply::Result(cacheable_tools_result("changing-tool")),
            MockReply::Error(JsonRpcError::header_mismatch("stale x-mcp-header mapping")),
            MockReply::Result(cacheable_tools_result("changing-tool")),
            MockReply::Result(serde_json::json!({
                "resultType": "complete",
                "content": [{"type": "text", "text": "retried"}]
            })),
        ]);
        let outgoing = transport.outgoing.clone();
        let client = McpClient::builder()
            .protocol_support(ProtocolSupport::try_new(["2026-07-28"]).unwrap())
            .connect_simple(transport)
            .await
            .unwrap();
        client.discover("test-client", "1.0.0").await.unwrap();
        client.list_tools().await.unwrap();

        let result = client
            .call_tool("changing-tool", serde_json::json!({}))
            .await
            .unwrap();
        assert_eq!(result.first_text(), Some("retried"));

        let methods: Vec<String> = outgoing
            .lock()
            .unwrap()
            .iter()
            .map(|message| {
                serde_json::from_str::<serde_json::Value>(message).unwrap()["method"]
                    .as_str()
                    .unwrap()
                    .to_string()
            })
            .collect();
        assert_eq!(
            methods,
            [
                "server/discover",
                "tools/list",
                "tools/call",
                "tools/list",
                "tools/call"
            ]
        );
    }

    #[cfg(any(feature = "protocol-2026-07-28", feature = "stateless"))]
    #[tokio::test]
    async fn final_call_tool_as_task_sends_no_legacy_task_parameter() {
        let transport = MockTransport::with_responses(vec![
            final_discover_result(),
            serde_json::json!({
                "resultType": "task",
                "taskId": "task-final",
                "status": "working",
                "createdAt": "2026-07-31T00:00:00Z",
                "lastUpdatedAt": "2026-07-31T00:00:00Z",
                "ttlMs": null,
                "pollIntervalMs": 50
            }),
        ]);
        let outgoing = transport.outgoing.clone();
        let client = McpClient::builder()
            .protocol_support(ProtocolSupport::try_new(["2026-07-28"]).unwrap())
            .with_tasks()
            .connect_simple(transport)
            .await
            .unwrap();
        client.discover("test-client", "1.0.0").await.unwrap();

        let created = client
            .call_tool_as_task("long-tool", serde_json::json!({}), None)
            .await
            .unwrap();
        assert_eq!(created.task.task_id, "task-final");

        let messages = outgoing.lock().unwrap();
        let call: serde_json::Value = serde_json::from_str(&messages[1]).unwrap();
        assert_eq!(call["method"], "tools/call");
        assert!(
            call["params"].get("task").is_none(),
            "final tools/call leaked the legacy task parameter: {call}"
        );
        assert!(
            call["params"]["_meta"]["io.modelcontextprotocol/clientCapabilities"]["extensions"]
                .get(crate::protocol::TASKS_EXTENSION_ID)
                .is_some()
        );
    }

    #[cfg(any(feature = "protocol-2026-07-28", feature = "stateless"))]
    #[tokio::test]
    async fn final_stale_schema_retry_is_bounded() {
        let transport = MockTransport::with_replies(vec![
            MockReply::Result(final_discover_result()),
            MockReply::Result(cacheable_tools_result("changing-tool")),
            MockReply::Error(JsonRpcError::header_mismatch("first rejection")),
            MockReply::Result(cacheable_tools_result("changing-tool")),
            MockReply::Error(JsonRpcError::header_mismatch("second rejection")),
        ]);
        let outgoing = transport.outgoing.clone();
        let client = McpClient::builder()
            .protocol_support(ProtocolSupport::try_new(["2026-07-28"]).unwrap())
            .connect_simple(transport)
            .await
            .unwrap();
        client.discover("test-client", "1.0.0").await.unwrap();
        client.list_tools().await.unwrap();

        let error = client
            .call_tool("changing-tool", serde_json::json!({}))
            .await
            .unwrap_err();
        assert!(matches!(
            error,
            Error::JsonRpc(error) if error.code == McpErrorCode::HeaderMismatch.code()
        ));
        assert_eq!(outgoing.lock().unwrap().len(), 5);
    }

    #[tokio::test]
    async fn legacy_tool_call_does_not_retry_a_header_mismatch() {
        let transport = MockTransport::with_replies(vec![
            MockReply::Result(mock_initialize_response()),
            MockReply::Error(JsonRpcError::header_mismatch("legacy rejection")),
        ]);
        let outgoing = transport.outgoing.clone();
        let client = McpClient::connect(transport).await.unwrap();
        client.initialize("test-client", "1.0.0").await.unwrap();

        let error = client
            .call_tool("changing-tool", serde_json::json!({}))
            .await
            .unwrap_err();
        assert!(matches!(
            error,
            Error::JsonRpc(error) if error.code == McpErrorCode::HeaderMismatch.code()
        ));
        let messages = outgoing.lock().unwrap();
        assert_eq!(messages.len(), 3);
        assert!(
            !messages
                .iter()
                .any(|message| message.contains("tools/list"))
        );
    }

    #[test]
    fn stale_tool_schema_errors_are_pre_execution_protocol_errors() {
        for error in [
            Error::JsonRpc(JsonRpcError::header_mismatch("mismatch")),
            Error::JsonRpc(JsonRpcError::method_not_found("tool")),
            Error::JsonRpc(JsonRpcError::invalid_params("arguments")),
        ] {
            assert!(is_stale_tool_schema_error(&error));
        }
        assert!(!is_stale_tool_schema_error(&Error::JsonRpc(
            JsonRpcError::internal_error("executed")
        )));
    }

    #[tokio::test]
    async fn test_list_tools() {
        let client = McpClient::connect(MockTransport::with_responses(vec![
            mock_initialize_response(),
            serde_json::json!({
                "tools": [
                    {
                        "name": "test_tool",
                        "description": "A test tool",
                        "inputSchema": {
                            "type": "object",
                            "properties": {}
                        }
                    }
                ]
            }),
        ]))
        .await
        .unwrap();

        client.initialize("test-client", "1.0.0").await.unwrap();
        let tools = client.list_tools().await.unwrap();

        assert_eq!(tools.tools.len(), 1);
        assert_eq!(tools.tools[0].name, "test_tool");
    }

    #[tokio::test]
    async fn test_call_tool() {
        let client = McpClient::connect(MockTransport::with_responses(vec![
            mock_initialize_response(),
            serde_json::json!({
                "content": [
                    {
                        "type": "text",
                        "text": "Tool result"
                    }
                ]
            }),
        ]))
        .await
        .unwrap();

        client.initialize("test-client", "1.0.0").await.unwrap();
        let result = client
            .call_tool("test_tool", serde_json::json!({"arg": "value"}))
            .await
            .unwrap();

        assert!(!result.content.is_empty());
    }

    #[tokio::test]
    async fn test_list_resources() {
        let client = McpClient::connect(MockTransport::with_responses(vec![
            mock_initialize_response(),
            serde_json::json!({
                "resources": [
                    {
                        "uri": "file://test.txt",
                        "name": "Test File"
                    }
                ]
            }),
        ]))
        .await
        .unwrap();

        client.initialize("test-client", "1.0.0").await.unwrap();
        let resources = client.list_resources().await.unwrap();

        assert_eq!(resources.resources.len(), 1);
        assert_eq!(resources.resources[0].uri, "file://test.txt");
    }

    #[tokio::test]
    async fn test_read_resource() {
        let client = McpClient::connect(MockTransport::with_responses(vec![
            mock_initialize_response(),
            serde_json::json!({
                "contents": [
                    {
                        "uri": "file://test.txt",
                        "text": "File contents"
                    }
                ]
            }),
        ]))
        .await
        .unwrap();

        client.initialize("test-client", "1.0.0").await.unwrap();
        let result = client.read_resource("file://test.txt").await.unwrap();

        assert_eq!(result.contents.len(), 1);
        assert_eq!(result.contents[0].text.as_deref(), Some("File contents"));
    }

    #[tokio::test]
    async fn test_list_prompts() {
        let client = McpClient::connect(MockTransport::with_responses(vec![
            mock_initialize_response(),
            serde_json::json!({
                "prompts": [
                    {
                        "name": "test_prompt",
                        "description": "A test prompt"
                    }
                ]
            }),
        ]))
        .await
        .unwrap();

        client.initialize("test-client", "1.0.0").await.unwrap();
        let prompts = client.list_prompts().await.unwrap();

        assert_eq!(prompts.prompts.len(), 1);
        assert_eq!(prompts.prompts[0].name, "test_prompt");
    }

    #[tokio::test]
    async fn test_get_prompt() {
        let client = McpClient::connect(MockTransport::with_responses(vec![
            mock_initialize_response(),
            serde_json::json!({
                "messages": [
                    {
                        "role": "user",
                        "content": {
                            "type": "text",
                            "text": "Prompt message"
                        }
                    }
                ]
            }),
        ]))
        .await
        .unwrap();

        client.initialize("test-client", "1.0.0").await.unwrap();
        let result = client.get_prompt("test_prompt", None).await.unwrap();

        assert_eq!(result.messages.len(), 1);
    }

    #[tokio::test]
    async fn test_ping() {
        let client = McpClient::connect(MockTransport::with_responses(vec![
            mock_initialize_response(),
            serde_json::json!({}),
        ]))
        .await
        .unwrap();

        client.initialize("test-client", "1.0.0").await.unwrap();
        let result = client.ping().await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_with_roots() {
        let roots = vec![Root::new("file:///test")];
        let client = McpClient::builder()
            .with_roots(roots)
            .connect_simple(MockTransport::with_responses(vec![]))
            .await
            .unwrap();

        let current_roots = client.roots().await;
        assert_eq!(current_roots.len(), 1);
    }

    #[tokio::test]
    async fn test_roots_management() {
        let client = McpClient::connect(MockTransport::with_responses(vec![
            mock_initialize_response(),
        ]))
        .await
        .unwrap();

        // Initially no roots
        assert!(client.roots().await.is_empty());

        // Add a root before initialization (no notification sent)
        client.add_root(Root::new("file:///project")).await.unwrap();
        assert_eq!(client.roots().await.len(), 1);

        // Initialize
        client.initialize("test-client", "1.0.0").await.unwrap();

        // Remove a root
        let removed = client.remove_root("file:///project").await.unwrap();
        assert!(removed);
        assert!(client.roots().await.is_empty());

        // Try to remove non-existent root
        let not_removed = client.remove_root("file:///nonexistent").await.unwrap();
        assert!(!not_removed);
    }

    #[tokio::test]
    async fn test_list_roots() {
        let roots = vec![
            Root::new("file:///project1"),
            Root::with_name("file:///project2", "Project 2"),
        ];
        let client = McpClient::builder()
            .with_roots(roots)
            .connect_simple(MockTransport::with_responses(vec![]))
            .await
            .unwrap();

        let result = client.list_roots().await;
        assert_eq!(result.roots.len(), 2);
        assert_eq!(result.roots[1].name, Some("Project 2".to_string()));
    }

    #[test]
    fn test_builder_with_sampling() {
        let builder = McpClientBuilder::new().with_sampling();
        assert!(builder.capabilities.sampling.is_some());
    }

    #[test]
    fn test_builder_with_elicitation() {
        let builder = McpClientBuilder::new().with_elicitation();
        assert!(builder.capabilities.elicitation.is_some());
    }

    #[test]
    fn builder_adds_protocol_extension_without_replacing_other_capabilities() {
        let extension = crate::ExtensionDeclaration::new(
            "com.example/rendering",
            serde_json::json!({"formats": ["html"]}),
        )
        .unwrap();
        let builder = McpClientBuilder::new()
            .with_sampling()
            .with_protocol_extension(extension);

        assert!(builder.capabilities.sampling.is_some());
        assert_eq!(
            builder.capabilities.extensions.as_ref().unwrap()["com.example/rendering"]["formats"]
                [0],
            "html"
        );
    }

    #[test]
    fn test_builder_chaining() {
        let builder = McpClientBuilder::new()
            .with_sampling()
            .with_elicitation()
            .with_roots(vec![Root::new("file:///project")]);
        assert!(builder.capabilities.sampling.is_some());
        assert!(builder.capabilities.elicitation.is_some());
        assert!(builder.capabilities.roots.is_some());
    }

    #[tokio::test]
    async fn test_bidirectional_sampling_round_trip() {
        use crate::protocol::{
            ContentRole, CreateMessageParams, CreateMessageResult, SamplingContent,
            SamplingContentOrArray,
        };

        // A handler that records whether handle_create_message was called
        struct RecordingHandler {
            called: Arc<AtomicBool>,
        }

        #[async_trait]
        impl ClientHandler for RecordingHandler {
            async fn handle_create_message(
                &self,
                _params: CreateMessageParams,
            ) -> std::result::Result<CreateMessageResult, tower_mcp_types::JsonRpcError>
            {
                self.called.store(true, Ordering::SeqCst);
                Ok(CreateMessageResult {
                    content: SamplingContentOrArray::Single(SamplingContent::Text {
                        text: "test response".to_string(),
                        annotations: None,
                        meta: None,
                    }),
                    model: "test-model".to_string(),
                    role: ContentRole::Assistant,
                    stop_reason: Some("end_turn".to_string()),
                    meta: None,
                })
            }
        }

        let called = Arc::new(AtomicBool::new(false));
        let handler = RecordingHandler {
            called: called.clone(),
        };

        // Build a mock transport, keeping a clone of incoming_tx so we can
        // inject a server-initiated request after the transport is consumed.
        let (inject_tx, rx) = mpsc::channel::<String>(32);
        let responses = vec![mock_initialize_response()];
        let inject_tx_clone = inject_tx.clone();

        let transport = MockTransport {
            responses: Arc::new(Mutex::new(
                responses.into_iter().map(MockReply::Result).collect(),
            )),
            response_idx: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
            incoming_tx: inject_tx,
            incoming_rx: rx,
            outgoing: Arc::new(Mutex::new(Vec::new())),
            connected: Arc::new(AtomicBool::new(true)),
        };

        let client = McpClient::builder()
            .with_sampling()
            .connect(transport, handler)
            .await
            .unwrap();

        // Initialize the client (this sends initialize request + notification)
        client.initialize("test-client", "1.0.0").await.unwrap();

        // Inject a server-initiated sampling/createMessage request
        let sampling_request = serde_json::json!({
            "jsonrpc": "2.0",
            "id": 100,
            "method": "sampling/createMessage",
            "params": {
                "messages": [
                    {
                        "role": "user",
                        "content": {
                            "type": "text",
                            "text": "Hello"
                        }
                    }
                ],
                "maxTokens": 100
            }
        });
        inject_tx_clone
            .send(sampling_request.to_string())
            .await
            .unwrap();

        // Give the background loop time to process
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;

        // Verify the handler was called
        assert!(
            called.load(Ordering::SeqCst),
            "handle_create_message should have been called"
        );
    }

    #[tokio::test]
    async fn test_list_resource_templates() {
        let client = McpClient::connect(MockTransport::with_responses(vec![
            mock_initialize_response(),
            serde_json::json!({
                "resourceTemplates": [
                    {
                        "uriTemplate": "file:///{path}",
                        "name": "File Template",
                        "description": "A file template"
                    }
                ]
            }),
        ]))
        .await
        .unwrap();

        client.initialize("test-client", "1.0.0").await.unwrap();
        let result = client.list_resource_templates().await.unwrap();

        assert_eq!(result.resource_templates.len(), 1);
        assert_eq!(result.resource_templates[0].name, "File Template");
    }

    #[tokio::test]
    async fn test_list_all_tools_single_page() {
        let client = McpClient::connect(MockTransport::with_responses(vec![
            mock_initialize_response(),
            serde_json::json!({
                "tools": [
                    {
                        "name": "tool_a",
                        "description": "Tool A",
                        "inputSchema": { "type": "object", "properties": {} }
                    },
                    {
                        "name": "tool_b",
                        "description": "Tool B",
                        "inputSchema": { "type": "object", "properties": {} }
                    }
                ]
            }),
        ]))
        .await
        .unwrap();

        client.initialize("test-client", "1.0.0").await.unwrap();
        let tools = client.list_all_tools().await.unwrap();

        assert_eq!(tools.len(), 2);
        assert_eq!(tools[0].name, "tool_a");
        assert_eq!(tools[1].name, "tool_b");
    }

    #[tokio::test]
    async fn test_list_all_tools_paginated() {
        let client = McpClient::connect(MockTransport::with_responses(vec![
            mock_initialize_response(),
            // First page with a next_cursor
            serde_json::json!({
                "tools": [
                    {
                        "name": "tool_a",
                        "description": "Tool A",
                        "inputSchema": { "type": "object", "properties": {} }
                    }
                ],
                "nextCursor": "page2"
            }),
            // Second page with no next_cursor
            serde_json::json!({
                "tools": [
                    {
                        "name": "tool_b",
                        "description": "Tool B",
                        "inputSchema": { "type": "object", "properties": {} }
                    }
                ]
            }),
        ]))
        .await
        .unwrap();

        client.initialize("test-client", "1.0.0").await.unwrap();
        let tools = client.list_all_tools().await.unwrap();

        assert_eq!(tools.len(), 2);
        assert_eq!(tools[0].name, "tool_a");
        assert_eq!(tools[1].name, "tool_b");
    }

    #[tokio::test]
    async fn test_call_tool_text_success() {
        let client = McpClient::connect(MockTransport::with_responses(vec![
            mock_initialize_response(),
            serde_json::json!({
                "content": [
                    { "type": "text", "text": "Hello " },
                    { "type": "text", "text": "World" }
                ]
            }),
        ]))
        .await
        .unwrap();

        client.initialize("test-client", "1.0.0").await.unwrap();
        let text = client
            .call_tool_text("test_tool", serde_json::json!({}))
            .await
            .unwrap();

        assert_eq!(text, "Hello World");
    }

    #[tokio::test]
    async fn test_call_tool_text_error() {
        let client = McpClient::connect(MockTransport::with_responses(vec![
            mock_initialize_response(),
            serde_json::json!({
                "content": [
                    { "type": "text", "text": "something went wrong" }
                ],
                "isError": true
            }),
        ]))
        .await
        .unwrap();

        client.initialize("test-client", "1.0.0").await.unwrap();
        let result = client
            .call_tool_text("test_tool", serde_json::json!({}))
            .await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("something went wrong"),
            "Error message should contain tool error text, got: {}",
            err
        );
    }

    #[tokio::test]
    async fn test_server_notification_parsing() {
        let notification = parse_server_notification("notifications/tools/list_changed", None);
        assert!(matches!(notification, ServerNotification::ToolsListChanged));

        let notification = parse_server_notification("notifications/resources/list_changed", None);
        assert!(matches!(
            notification,
            ServerNotification::ResourcesListChanged
        ));

        let notification = parse_server_notification(
            "notifications/resources/updated",
            Some(serde_json::json!({"uri": "file:///test"})),
        );
        match notification {
            ServerNotification::ResourceUpdated { uri } => {
                assert_eq!(uri, "file:///test");
            }
            _ => panic!("Expected ResourceUpdated"),
        }

        let notification =
            parse_server_notification("custom/notification", Some(serde_json::json!({"data": 42})));
        match notification {
            ServerNotification::Unknown { method, params } => {
                assert_eq!(method, "custom/notification");
                assert!(params.is_some());
            }
            _ => panic!("Expected Unknown"),
        }

        let notification = parse_server_notification(
            notifications::SUBSCRIPTIONS_ACKNOWLEDGED,
            Some(serde_json::json!({
                "_meta": {
                    "io.modelcontextprotocol/subscriptionId": 7
                },
                "notifications": {
                    "toolsListChanged": true
                }
            })),
        );
        assert!(matches!(
            notification,
            ServerNotification::SubscriptionAcknowledged {
                subscription_id: RequestId::Number(7),
                ..
            }
        ));

        let notification = parse_server_notification(
            notifications::TOOLS_LIST_CHANGED,
            Some(serde_json::json!({
                "_meta": {
                    "io.modelcontextprotocol/subscriptionId": "stream-a"
                }
            })),
        );
        assert!(matches!(
            notification,
            ServerNotification::Subscription {
                subscription_id: RequestId::String(id),
                notification,
            } if id == "stream-a"
                && matches!(notification.as_ref(), ServerNotification::ToolsListChanged)
        ));

        let notification = parse_server_notification(
            notifications::CANCELLED,
            Some(serde_json::json!({
                "requestId": 7,
                "reason": "done"
            })),
        );
        assert!(matches!(
            notification,
            ServerNotification::SubscriptionCancelled {
                subscription_id: RequestId::Number(7),
                reason: Some(reason),
            } if reason == "done"
        ));

        let notification = parse_server_notification(
            notifications::TASK_STATUS_CHANGED,
            Some(serde_json::json!({
                "taskId": "legacy-task",
                "status": "completed",
                "createdAt": "2026-08-02T00:00:00Z",
                "lastUpdatedAt": "2026-08-02T00:00:01Z",
                "ttl": null
            })),
        );
        assert!(matches!(
            notification,
            ServerNotification::TaskStatusChanged(TaskStatusParams {
                task_id,
                status: crate::protocol::TaskStatus::Completed,
                ..
            }) if task_id == "legacy-task"
        ));

        let notification = parse_server_notification(
            notifications::TASK_STATUS_CHANGED,
            Some(serde_json::json!({
                "taskId": "final-task",
                "status": "cancelled",
                "createdAt": "2026-08-02T00:00:00Z",
                "lastUpdatedAt": "2026-08-02T00:00:01Z",
                "ttlMs": null,
                "_meta": {
                    "io.modelcontextprotocol/subscriptionId": "task-stream"
                }
            })),
        );
        assert!(matches!(
            notification,
            ServerNotification::Subscription {
                subscription_id: RequestId::String(id),
                notification,
            } if id == "task-stream"
                && matches!(
                    notification.as_ref(),
                    ServerNotification::FinalTaskStatusChanged(params)
                        if params.task.task_id() == "final-task"
                            && params.task.status() == crate::protocol::TaskStatus::Cancelled
                )
        ));
    }

    // =========================================================================
    // handle_response ID correlation
    // =========================================================================

    fn pending_with(
        ids: &[RequestId],
    ) -> (
        HashMap<RequestId, PendingRequest>,
        Vec<oneshot::Receiver<Result<serde_json::Value>>>,
    ) {
        let mut map = HashMap::new();
        let mut rxs = Vec::new();
        for id in ids {
            let (tx, rx) = oneshot::channel();
            map.insert(
                id.clone(),
                PendingRequest {
                    method: "test".to_string(),
                    response_tx: tx,
                    acknowledgment_tx: None,
                },
            );
            rxs.push(rx);
        }
        (map, rxs)
    }

    #[tokio::test]
    async fn test_stringified_numeric_response_id_correlates() {
        // rmcp #1021 analog: a numeric request id 42 answered with a
        // stringified id "42" still correlates.
        let (mut pending, mut rxs) = pending_with(&[RequestId::Number(42)]);

        let response = serde_json::json!({
            "jsonrpc": "2.0",
            "id": "42",
            "result": {"ok": true}
        });
        handle_response(&response, &mut pending);

        assert!(pending.is_empty(), "pending request should be resolved");
        let result = rxs.remove(0).await.unwrap().unwrap();
        assert_eq!(result, serde_json::json!({"ok": true}));
    }

    #[tokio::test]
    async fn test_exact_string_id_takes_precedence() {
        // A genuine string id "42" must match exactly and win over the
        // numeric interpretation when both are pending.
        let (mut pending, mut rxs) =
            pending_with(&[RequestId::String("42".to_string()), RequestId::Number(42)]);

        let response = serde_json::json!({
            "jsonrpc": "2.0",
            "id": "42",
            "result": {"which": "string"}
        });
        handle_response(&response, &mut pending);

        // The string entry resolved; the numeric entry is still pending.
        assert_eq!(pending.len(), 1);
        assert!(pending.contains_key(&RequestId::Number(42)));
        let result = rxs.remove(0).await.unwrap().unwrap();
        assert_eq!(result, serde_json::json!({"which": "string"}));
    }

    #[tokio::test]
    async fn test_non_numeric_string_id_does_not_correlate() {
        // A string id that is not the string form of the pending numeric
        // id must not resolve it.
        let (mut pending, _rxs) = pending_with(&[RequestId::Number(42)]);

        let response = serde_json::json!({
            "jsonrpc": "2.0",
            "id": "not-a-number",
            "result": {}
        });
        handle_response(&response, &mut pending);

        assert_eq!(pending.len(), 1, "numeric request should stay pending");
    }
}