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
//! Utilities for the MCP client

use crate::error::{Error, ErrorCode};
use crate::shared;
use crate::transport::Transport;
use crate::types::Root;
use crate::types::sampling::{CreateMessageRequestParams, CreateMessageResult, SamplingHandler};
use crate::types::{
    CallToolRequestParams, CallToolResponse, GetPromptRequestParams, GetPromptResult,
    Implementation, ListPromptsRequestParams, ListPromptsResult,
    ListResourceTemplatesRequestParams, ListResourceTemplatesResult, ListResourcesRequestParams,
    ListResourcesResult, ListToolsRequestParams, ListToolsResult, MessageEnvelope,
    ReadResourceRequestParams, ReadResourceResult, Request, RequestId, RequestParamsMeta, Response,
    ServerCapabilities, Uri,
    cursor::Cursor,
    elicitation::{ElicitRequestParams, ElicitResult, ElicitationHandler},
    notification::Notification,
    resource::{SubscribeRequestParams, UnsubscribeRequestParams},
};
use crate::types::{ClientCapabilities, InitializeRequestParams, InitializeResult};
#[cfg(not(feature = "legacy-spec"))]
use crate::types::{SubscriptionFilter, SubscriptionsListenRequestParams};
use handler::RequestHandler;
use options::McpOptions;
use serde::Serialize;
use std::fmt::{Debug, Formatter};
use std::{future::Future, sync::Arc};
use tokio_util::sync::CancellationToken;

#[cfg(feature = "tasks")]
#[cfg(feature = "legacy-spec")]
use serde::de::DeserializeOwned;

#[cfg(feature = "tasks")]
use crate::types::{CancelTaskRequestParams, GetTaskRequestParams, TaskMetadata};
#[cfg(all(feature = "tasks", not(feature = "legacy-spec")))]
use crate::types::{DetailedTask, UpdateTaskRequestParams};
#[cfg(all(feature = "tasks", feature = "legacy-spec"))]
use crate::types::{
    GetTaskPayloadRequestParams, ListTasksRequestParams, ListTasksResult, Task, TaskPayload,
};

pub mod batch;
mod handler;
mod notification_handler;
pub mod options;
pub mod subscribe;
#[cfg(not(feature = "legacy-spec"))]
pub mod subscription;
#[cfg(feature = "tasks")]
pub mod task;

pub use batch::BatchBuilder;
#[cfg(not(feature = "legacy-spec"))]
pub use subscription::{Subscription, SubscriptionEnd};
#[cfg(feature = "tasks")]
pub use task::TaskBuilder;

/// Represents an MCP client app
pub struct Client {
    /// MCP client options.
    options: McpOptions,

    /// Capabilities supported by the connected server.
    server_capabilities: Option<ServerCapabilities>,

    /// Implementation information of the connected server.
    server_info: Option<Implementation>,

    /// A [`CancellationToken`] that cancels transport background processes.
    cancellation_token: Option<CancellationToken>,

    /// Request handler
    handler: Option<RequestHandler>,
}

impl Debug for Client {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Client")
            .field("options", &self.options)
            .field("server_capabilities", &self.server_capabilities)
            .field("server_info", &self.server_info)
            .finish()
    }
}

impl Default for Client {
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

impl Client {
    /// Initializes a new client app
    pub fn new() -> Self {
        Self {
            options: McpOptions::default(),
            server_capabilities: None,
            server_info: None,
            cancellation_token: None,
            handler: None,
        }
    }

    /// Configure MCP client options
    pub fn with_options<F>(mut self, config: F) -> Self
    where
        F: FnOnce(McpOptions) -> McpOptions,
    {
        self.options = config(self.options);
        self
    }

    /// Adds a new Root
    ///
    /// # Example
    /// ```no_run
    /// use neva::client::Client;
    /// # use neva::error::Error;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Error> {
    /// let mut client = Client::new();
    /// client.add_root("file:///home/user/projects/my_project", "My Project");
    /// # client.disconnect().await
    /// # }
    /// ```
    #[deprecated(
        note = "Roots are deprecated in MCP 2026-07-28: the capability-driven `roots/list` request is gone and the ability is re-homed onto MRTR -- see `Context::list_roots`. Under MCP 2026-07-28 this configures what the client answers MRTR `roots/list` input requests with."
    )]
    #[allow(deprecated)]
    pub fn add_root(&mut self, uri: impl Into<Uri>, name: impl Into<String>) -> &mut Self {
        self.options.add_root(Root::new(uri, name));
        self.publish_roots_changed();
        self
    }

    /// Adds multiple new Roots.
    ///
    /// # Example
    /// ```no_run
    /// use neva::client::Client;
    /// # use neva::error::Error;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Error> {
    /// let mut client = Client::new();
    /// client.add_roots([
    ///     ("file:///home/user/projects/my_project", "My Project"),
    ///     ("file:///home/user/projects/another_project", "My Another Project")
    /// ]);
    /// # client.disconnect().await
    /// # }
    /// ```
    #[deprecated(
        note = "Roots are deprecated in MCP 2026-07-28: the capability-driven `roots/list` request is gone and the ability is re-homed onto MRTR -- see `Context::list_roots`. Under MCP 2026-07-28 this configures what the client answers MRTR `roots/list` input requests with."
    )]
    #[allow(deprecated)]
    pub fn add_roots<T, I>(&mut self, roots: I) -> &mut Self
    where
        T: Into<Root>,
        I: IntoIterator<Item = T>,
    {
        self.options.add_roots(roots);
        self.publish_roots_changed();
        self
    }

    /// Sends the "notifications/roots/list_changed" notification to the server
    #[deprecated(
        note = "Roots are deprecated in MCP 2026-07-28: the capability-driven `roots/list` request is gone and the ability is re-homed onto MRTR -- see `Context::list_roots`. Under MCP 2026-07-28 this configures what the client answers MRTR `roots/list` input requests with."
    )]
    pub fn publish_roots_changed(&mut self) {
        if let Some(handler) = self.handler.as_mut() {
            let roots = self.options.roots();
            handler.notify_roots_changed(roots);
        }
    }

    /// Registers a handler that will be running when a "sampling/createMessage" request is received
    #[deprecated(
        note = "Sampling is deprecated in MCP 2026-07-28: the capability-driven `sampling/createMessage` request is gone and the ability is re-homed onto MRTR -- see `Context::sample`. Under MCP 2026-07-28 this handler fulfils MRTR `sampling/createMessage` input requests."
    )]
    pub fn map_sampling<F, R>(&mut self, handler: F) -> &mut Self
    where
        F: Fn(CreateMessageRequestParams) -> R + Clone + Send + Sync + 'static,
        R: Future + Send,
        R::Output: Into<CreateMessageResult>,
    {
        let handler: SamplingHandler = make_handler(handler);
        self.options.add_sampling_handler(handler);
        self
    }

    /// Registers a handler that will be running when an "elicitation/create" request is received
    pub fn map_elicitation<F, R>(&mut self, handler: F) -> &mut Self
    where
        F: Fn(ElicitRequestParams) -> R + Clone + Send + Sync + 'static,
        R: Future + Send,
        R::Output: Into<ElicitResult>,
    {
        let handler: ElicitationHandler = make_handler(handler);
        self.options.add_elicitation_handler(handler);
        self
    }

    /// Connects the MCP client to the MCP server
    ///
    /// # Example
    /// ```no_run
    /// use neva::client::Client;
    /// use neva::error::Error;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Error> {
    ///     let mut client = Client::new();
    ///
    ///     client.connect().await?;
    ///
    ///     // call tools, read resources, etc.
    ///
    ///     client.disconnect().await
    /// }
    /// ```
    pub async fn connect(&mut self) -> Result<(), Error> {
        #[cfg(feature = "macros")]
        self.register_methods();

        let mut transport = self.options.transport();
        let token = transport.start();

        #[cfg(feature = "tracing")]
        self.register_tracing_notification_handlers();

        self.cancellation_token = Some(token.clone());
        self.handler = Some(RequestHandler::new(transport, &self.options, token));

        self.wait_for_shutdown_signal();
        self.init().await
    }

    /// Disconnects the MCP client from the MCP server
    ///
    /// # Example
    /// ```no_run
    /// use neva::client::Client;
    /// use neva::error::Error;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Error> {
    ///     let mut client = Client::new();
    ///
    ///     client.connect().await?;
    ///
    ///     // call tools, read resources, etc.
    ///
    ///     client.disconnect().await
    /// }
    /// ```
    pub async fn disconnect(mut self) -> Result<(), Error> {
        self.send_notification(crate::types::notification::commands::CANCELLED, None)
            .await?;
        if let Some(token) = self.cancellation_token {
            token.cancel();
        }
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        Ok(())
    }

    /// The protocol version this client expects from the connected peer.
    ///
    /// Under MCP 2026-07-28 the 2026-07-28 expectation is pinned to
    /// [`crate::LATEST_PROTOCOL_VERSION`]: a `with_mcp_version` override only
    /// selects which legacy version the dual-mode fallback negotiates --
    /// it must never make `server/discover` reject a valid 2026-07-28 server.
    fn expected_protocol_ver(&self) -> &'static str {
        #[cfg(not(feature = "legacy-spec"))]
        {
            if self.is_legacy_peer() {
                self.options.legacy_protocol_ver()
            } else {
                crate::LATEST_PROTOCOL_VERSION
            }
        }
        #[cfg(feature = "legacy-spec")]
        {
            self.options.protocol_ver()
        }
    }

    /// Validates a server-reported protocol version against what this client
    /// negotiated, cancelling the transport on mismatch.
    fn validate_server_version(&mut self, server_ver: &str) -> Result<(), Error> {
        if !crate::PROTOCOL_VERSIONS.contains(&server_ver) {
            self.cancel_transport();
            return Err(Error::new(
                ErrorCode::InvalidRequest,
                format!("Unsupported server protocol version: {server_ver}"),
            ));
        }
        if server_ver != self.expected_protocol_ver() {
            self.cancel_transport();
            return Err(Error::new(
                ErrorCode::InvalidRequest,
                format!(
                    "Server protocol version mismatch: expected {}, got {server_ver}",
                    self.expected_protocol_ver()
                ),
            ));
        }
        Ok(())
    }

    /// Sends `initialize` request to an MCP server (legacy handshake).
    #[cfg(feature = "legacy-spec")]
    pub async fn init(&mut self) -> Result<(), Error> {
        self.legacy_init().await
    }

    /// The `initialize`/`initialized` handshake: the only handshake for
    /// the legacy build, the dual-mode fallback for the 2026-07-28 build.
    async fn legacy_init(&mut self) -> Result<(), Error> {
        #[cfg(feature = "legacy-spec")]
        let protocol_ver = self.options.protocol_ver().to_string();
        // The fallback negotiates the newest legacy version -- offering
        // the 2026-07-28 version to a server that just rejected `server/discover`
        // would only get refused again.
        #[cfg(not(feature = "legacy-spec"))]
        let protocol_ver = self.options.legacy_protocol_ver().to_string();

        let params = InitializeRequestParams {
            protocol_ver,
            client_info: Some(self.options.implementation.clone()),
            capabilities: Some(ClientCapabilities {
                roots: self.options.roots_capability(),
                sampling: self.options.sampling_capability(),
                elicitation: self.options.elicitation_capability(),
                #[cfg(feature = "tasks")]
                tasks: self.options.tasks_capability(),
                #[cfg(not(feature = "legacy-spec"))]
                extensions: None,
                experimental: None,
            }),
        };

        let req = Request::new(
            Some(RequestId::Uuid(uuid::Uuid::new_v4())),
            crate::commands::INIT,
            Some(params),
        );

        let resp = self.send_request(req).await?;

        let init_result = resp.into_result::<InitializeResult>()?;

        self.validate_server_version(init_result.protocol_ver.as_str())?;

        self.server_capabilities = Some(init_result.capabilities);
        self.server_info = Some(init_result.server_info);

        self.send_notification(crate::types::notification::commands::INITIALIZED, None)
            .await
    }

    /// Discovers server capabilities via `server/discover` (MCP 2026-07-28).
    ///
    /// Replaces the `initialize`/`initialized` handshake. No `initialized`
    /// notification is sent -- the transport is stateless.
    #[cfg(not(feature = "legacy-spec"))]
    pub async fn discover(&mut self) -> Result<(), Error> {
        let resp = self.send_request(Self::discover_request()).await?;
        let result = resp.into_result::<crate::types::DiscoverResult>()?;
        self.apply_discover(result)
    }

    /// Builds the `server/discover` request.
    #[cfg(not(feature = "legacy-spec"))]
    fn discover_request() -> Request {
        Request::new(
            Some(RequestId::Uuid(uuid::Uuid::new_v4())),
            crate::commands::DISCOVER,
            Some(crate::types::DiscoverRequestParams::default()),
        )
    }

    /// Applies a successful `server/discover` result: validates the
    /// reported protocol version and stores the capabilities.
    #[cfg(not(feature = "legacy-spec"))]
    fn apply_discover(&mut self, result: crate::types::DiscoverResult) -> Result<(), Error> {
        // Discovery advertises a *set*; the handshake succeeds when the version
        // this client speaks is among them.
        let expected = self.expected_protocol_ver();
        if !result.supported_versions.iter().any(|v| v == expected) {
            // `connect` has already started the transport; leaving it running
            // would park background HTTP/SSE tasks behind a client that never
            // completed its handshake.
            self.cancel_transport();
            return Err(Error::new(
                ErrorCode::UnsupportedProtocolVersion,
                format!(
                    "Server supports {:?} but the client speaks {expected}",
                    result.supported_versions
                ),
            ));
        }
        self.server_capabilities = Some(result.capabilities);
        // `serverInfo` left `DiscoverResult` in the final spec: servers now
        // report themselves in every result's `_meta`, so it is picked up from
        // there instead.
        Ok(())
    }

    /// The dual-mode handshake (issue #84): tries `server/discover`
    /// first and, when the server clearly doesn't speak the 2026-07-28 protocol,
    /// falls back to the legacy `initialize` handshake and marks the
    /// peer as legacy -- subsequent traffic uses legacy semantics
    /// (session header, SSE stream, no MRTR, no 2026-07-28 routing headers).
    ///
    /// Only **wire-phase** failures classify for the fallback: transport
    /// errors and the server's JSON-RPC *error* reply. Once the server
    /// answers `server/discover` successfully, the peer has committed to
    /// the 2026-07-28 protocol -- later local failures (a malformed result, an
    /// unsupported/mismatched `protocolVersion`) surface as real errors
    /// instead of a misleading fallback attempt on a transport that
    /// version validation may already have cancelled.
    #[cfg(not(feature = "legacy-spec"))]
    pub async fn init(&mut self) -> Result<(), Error> {
        let resp = match self.send_request(Self::discover_request()).await {
            Ok(resp) => resp,
            Err(err) if is_fallback_trigger(&err) => return self.fallback_init(&err).await,
            Err(err) => return Err(err),
        };

        let is_error_reply = matches!(resp, Response::Err(_));
        let result = match resp.into_result::<crate::types::DiscoverResult>() {
            Ok(result) => result,
            Err(err) if is_error_reply && is_fallback_trigger(&err) => {
                return self.fallback_init(&err).await;
            }
            Err(err) => return Err(err),
        };

        self.apply_discover(result)
    }

    /// Runs the legacy half of the dual-mode handshake after a
    /// classified `server/discover` rejection.
    #[cfg(not(feature = "legacy-spec"))]
    async fn fallback_init(&mut self, _err: &Error) -> Result<(), Error> {
        #[cfg(feature = "tracing")]
        tracing::info!(
            logger = "neva",
            "`server/discover` rejected ({_err}); falling back to `initialize`"
        );
        self.options.peer_mode.set_legacy();
        self.legacy_init().await
    }

    /// Whether the peer negotiated the legacy protocol through the
    /// dual-mode fallback.
    #[cfg(not(feature = "legacy-spec"))]
    fn is_legacy_peer(&self) -> bool {
        self.options.peer_mode.is_legacy()
    }

    /// Sends a ping to the MCP server
    ///
    /// Removed in MCP 2026-07-28; available only under `legacy-spec`.
    #[cfg(feature = "legacy-spec")]
    pub async fn ping(&mut self) -> Result<Response, Error> {
        self.command::<()>(crate::commands::PING, None).await
    }

    /// Sends a command to the MCP server
    ///
    /// # Example
    /// ```no_run
    /// use neva::prelude::*;
    ///
    /// #[derive(serde::Serialize)]
    /// struct MyCommandParams {
    ///     param: String,
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Error> {
    ///     let mut client = Client::new();
    ///
    ///     client.connect().await?;
    ///
    ///     let params = MyCommandParams { param: "Hello MCP!".to_string() };
    ///     let tools = client.command("my-command", Some(params)).await?;
    ///
    ///     client.disconnect().await
    /// }
    /// ```
    #[inline]
    pub async fn command<T: Serialize>(
        &mut self,
        command: impl Into<String>,
        params: Option<T>,
    ) -> Result<Response, Error> {
        let id = self.generate_id()?;
        let request = Request::new(Some(id), command, params);
        self.send_request(request).await
    }

    /// Requests a list of tools that MCP server provides
    ///
    /// # Example
    /// ```no_run
    /// use neva::client::Client;
    /// use neva::error::Error;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Error> {
    ///     let mut client = Client::new();
    ///
    ///     client.connect().await?;
    ///
    ///     // Fetch all or initial list of tools if the MCP server provides pagination
    ///     let tools = client.list_tools(None).await?;
    ///     
    ///     // Fetch the next page of tools is any   
    ///     let tools = client.list_tools(tools.next_cursor).await?;
    ///
    ///     client.disconnect().await
    /// }
    /// ```
    pub async fn list_tools(&mut self, cursor: Option<Cursor>) -> Result<ListToolsResult, Error> {
        // A cursor-less call starts the listing over, so it replaces what the
        // previous traversal registered rather than merging into it.
        #[cfg(all(feature = "http-client", not(feature = "legacy-spec")))]
        let fresh = cursor.is_none();
        let params = ListToolsRequestParams { cursor };

        #[allow(unused_mut)]
        let mut result: ListToolsResult = self
            .command(crate::types::tool::commands::LIST, Some(params))
            .await?
            .into_result()?;

        #[cfg(all(feature = "http-client", not(feature = "legacy-spec")))]
        self.register_param_headers(&mut result, fresh);

        Ok(result)
    }

    /// Runs a batched `tools/list` response through the same registry update a
    /// direct [`Self::list_tools`] performs, rewriting the response in place so
    /// the caller never sees a tool the client refuses to call.
    ///
    /// A batched listing is always a fresh traversal: [`BatchBuilder`] enqueues
    /// it without a cursor. A response that does not parse as a listing is left
    /// alone -- it is the caller's to interpret, and it registers nothing.
    #[cfg(all(feature = "http-client", not(feature = "legacy-spec")))]
    pub(super) fn register_batched_tools(&mut self, resp: &mut Response) {
        let Response::Ok(ok) = resp else { return };
        let Ok(mut result) = serde_json::from_value::<ListToolsResult>(ok.result.clone()) else {
            return;
        };
        self.register_param_headers(&mut result, true);
        if let Ok(value) = serde_json::to_value(&result) {
            ok.result = value;
        }
    }

    /// Records each tool's `x-mcp-header` annotations and drops any tool whose
    /// annotations are invalid.
    ///
    /// The spec makes rejection per-tool on purpose: one malformed definition
    /// must not take the whole listing down, and must not be callable either --
    /// so the offending tool is removed from the result the caller sees.
    ///
    /// A refreshed listing replaces what the previous one registered, including
    /// replacing it with nothing: a server that drops an annotation -- or drops
    /// the whole tool -- must stop the client from mirroring that argument into
    /// a header, which a leftover registration would keep doing even though the
    /// current listing no longer designates it.
    ///
    /// `fresh` marks the first page of a traversal, which clears the registry;
    /// later pages accumulate onto it, since a tool absent from page two has
    /// not been withdrawn, only listed elsewhere.
    ///
    /// The name of a rejected tool is remembered as well, so that hiding it
    /// from the listing is not all that hiding it does -- see
    /// [`Self::blocked_tool_error`].
    #[cfg(all(feature = "http-client", not(feature = "legacy-spec")))]
    fn register_param_headers(&mut self, result: &mut ListToolsResult, fresh: bool) {
        use crate::shared::param_headers;

        if fresh {
            self.options.param_headers.clear();
            self.options.rejected_tools.clear();
        }

        result.tools.retain(|tool| {
            self.options.param_headers.remove(&*tool.name);
            self.options.rejected_tools.remove(&*tool.name);
            let schema = match serde_json::to_value(&tool.input_schema) {
                Ok(schema) => schema,
                Err(_) => return true,
            };
            match param_headers::collect(&schema) {
                Ok(headers) => {
                    if !headers.is_empty() {
                        self.options
                            .param_headers
                            .insert(tool.name.to_string(), headers);
                    }
                    true
                }
                Err(_err) => {
                    #[cfg(feature = "tracing")]
                    tracing::warn!(logger = "neva", "Dropping tool `{}`: {_err}", tool.name);
                    self.options.rejected_tools.insert(tool.name.to_string());
                    false
                }
            }
        });
    }

    /// Refuses a `tools/call` naming a tool the current listing withdrew for a
    /// malformed `x-mcp-header` declaration.
    ///
    /// Dropping such a tool from `tools/list` is what the spec asks for, but on
    /// its own it only hides the name: a caller holding one from somewhere else
    /// -- hard-coded, cached, read off a log -- still reaches `call_tool`, and
    /// since the declaration never parsed there are no annotations to mirror,
    /// so the call would travel with none of the `Mcp-Param-*` headers it asked
    /// for. An intermediary would see a call it cannot route or police, which
    /// is the one outcome the annotation exists to prevent -- so the call is
    /// refused instead of quietly sent unannotated.
    ///
    /// Only tools this client has seen rejected are known; one it never listed
    /// cannot be recognized.
    ///
    /// Sits on the send seam, so every request pays for it -- an empty set is
    /// checked first precisely so that the requests it is not about (and, in a
    /// healthy connection, all of them) stop at a single branch.
    #[cfg(all(feature = "http-client", not(feature = "legacy-spec")))]
    #[inline]
    fn blocked_tool_error(&self, req: &Request) -> Option<Error> {
        if self.options.rejected_tools.is_empty()
            || req.method.as_str() != crate::types::tool::commands::CALL
        {
            return None;
        }

        let name = req.params.as_ref()?.get("name")?.as_str()?;
        if !self.options.rejected_tools.contains(name) {
            return None;
        }

        Some(Error::new(
            ErrorCode::InvalidParams,
            format!(
                "Tool `{name}` was rejected for an invalid `x-mcp-header` declaration and cannot be called"
            ),
        ))
    }

    /// Requests a list of resources that MCP server provides
    ///
    /// # Example
    /// ```no_run
    /// use neva::client::Client;
    /// use neva::error::Error;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Error> {
    ///     let mut client = Client::new();
    ///
    ///     client.connect().await?;
    ///
    ///     // Fetch all or initial list of resources if the MCP server provides pagination
    ///     let resources = client.list_resources(None).await?;
    ///     
    ///     // Fetch the next page of resources is any   
    ///     let resources = client.list_resources(resources.next_cursor).await?;
    ///
    ///     client.disconnect().await
    /// }
    /// ```
    pub async fn list_resources(
        &mut self,
        cursor: Option<Cursor>,
    ) -> Result<ListResourcesResult, Error> {
        let params = ListResourcesRequestParams { cursor };
        self.command(crate::types::resource::commands::LIST, Some(params))
            .await?
            .into_result()
    }

    /// Requests a list of resource templates that MCP server provides
    ///
    /// # Example
    /// ```no_run
    /// use neva::client::Client;
    /// use neva::error::Error;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Error> {
    ///     let mut client = Client::new();
    ///
    ///     client.connect().await?;
    ///
    ///     // Fetch all or initial list of resource templates if the MCP server provides pagination
    ///     let templates = client.list_resource_templates(None).await?;
    ///     
    ///     // Fetch the next page of resource templates is any   
    ///     let templates = client.list_resource_templates(templates.next_cursor).await?;
    ///
    ///     client.disconnect().await
    /// }
    /// ```
    pub async fn list_resource_templates(
        &mut self,
        cursor: Option<Cursor>,
    ) -> Result<ListResourceTemplatesResult, Error> {
        let params = ListResourceTemplatesRequestParams { cursor };
        self.command(
            crate::types::resource::commands::TEMPLATES_LIST,
            Some(params),
        )
        .await?
        .into_result()
    }

    /// Requests a list of prompts that MCP server provides
    ///
    /// # Example
    /// ```no_run
    /// use neva::client::Client;
    /// use neva::error::Error;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Error> {
    ///     let mut client = Client::new();
    ///
    ///     client.connect().await?;
    ///
    ///     // Fetch all or initial list of prompts if the MCP server provides pagination
    ///     let prompts = client.list_prompts(None).await?;
    ///     
    ///     // Fetch the next page of prompts templates is any   
    ///     let prompts = client.list_prompts(prompts.next_cursor).await?;
    ///
    ///     client.disconnect().await
    /// }
    /// ```
    pub async fn list_prompts(
        &mut self,
        cursor: Option<Cursor>,
    ) -> Result<ListPromptsResult, Error> {
        let params = ListPromptsRequestParams { cursor };
        self.command(crate::types::prompt::commands::LIST, Some(params))
            .await?
            .into_result()
    }

    /// Calls a tool that MCP server supports
    ///
    /// # Example
    /// ```no_run
    /// use neva::client::Client;
    /// use neva::error::Error;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Error> {
    ///     let mut client = Client::new();
    ///
    ///     client.connect().await?;
    ///
    ///     let args = [("message", "Hello MCP!")]; // or let args = ("message", "Hello MCP!");
    ///     let result = client.call_tool("echo", args).await?;
    ///     // Do something with the result
    ///
    ///     client.disconnect().await
    /// }
    /// ```
    ///
    /// # Structured output
    /// ```no_run
    /// use neva::prelude::*;
    ///
    /// #[json_schema(de)]
    /// struct Weather {
    ///     conditions: String,
    ///     temperature: f32,
    ///     humidity: f32,
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Error> {
    ///     let mut client = Client::new();
    ///
    ///     client.connect().await?;
    ///
    ///     let tools = client.list_tools(None).await?;
    ///
    ///     // Get the tool by name
    ///     let tool: &Tool = tools.get("weather-forecast")
    ///         .expect("Weather forecast tool not found");
    ///
    ///     let args = ("location", "London");
    ///     let result = client.call_tool("weather-forecast", args).await?;
    ///
    ///     // Validate the output structure and deserialize the result
    ///     let weather: Weather = tool
    ///         .validate(&result)
    ///         .and_then(|res| res.as_json())?;
    ///     
    ///     // Do something with the result
    ///
    ///     client.disconnect().await
    /// }
    /// ```
    pub async fn call_tool<N, Args>(
        &mut self,
        name: N,
        args: Args,
    ) -> Result<CallToolResponse, Error>
    where
        N: Into<String>,
        Args: shared::IntoArgs,
    {
        let params = CallToolRequestParams {
            name: name.into(),
            meta: None,
            args: args.into_args(),
            #[cfg(feature = "tasks")]
            task: None,
        };

        self.call_tool_raw(params).await?.into_result()
    }

    /// Calls a task-augmented tool that MCP server supports
    ///
    /// # Example
    /// ```no_run
    /// use neva::client::Client;
    /// use neva::error::Error;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Error> {
    ///     let mut client = Client::new();
    ///
    ///     client.connect().await?;
    ///
    ///     let args = [("message", "Hello MCP!")]; // or let args = ("message", "Hello MCP!");
    ///     let result = client.call_tool_as_task("echo", args, None).await?;
    ///     // Do something with the result
    ///
    ///     client.disconnect().await
    /// }
    /// ```
    ///
    /// # Structured output
    /// ```no_run
    /// use neva::prelude::*;
    ///
    /// #[json_schema(de)]
    /// struct Weather {
    ///     conditions: String,
    ///     temperature: f32,
    ///     humidity: f32,
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Error> {
    ///     let mut client = Client::new();
    ///
    ///     client.connect().await?;
    ///
    ///     let tools = client.list_tools(None).await?;
    ///
    ///     // Get the tool by name
    ///     let tool: &Tool = tools.get("weather-forecast")
    ///         .expect("Weather forecast tool not found");
    ///
    ///     let args = ("location", "London");
    ///     let result = client.call_tool_as_task("weather-forecast", args, None).await?;
    ///
    ///     // Validate the output structure and deserialize the result
    ///     let weather: Weather = tool
    ///         .validate(&result)
    ///         .and_then(|res| res.as_json())?;
    ///     
    ///     // Do something with the result
    ///
    ///     client.disconnect().await
    /// }
    /// ```
    #[cfg(feature = "tasks")]
    pub async fn call_tool_as_task<N, Args>(
        &mut self,
        name: N,
        args: Args,
        ttl: Option<usize>,
    ) -> Result<CallToolResponse, Error>
    where
        N: Into<String>,
        Args: shared::IntoArgs,
    {
        let builder = self.task();
        let builder = if let Some(t) = ttl {
            builder.with_ttl(t)
        } else {
            builder
        };
        builder.call_tool(name, args).await
    }

    /// Calls a tool
    #[inline]
    pub async fn call_tool_raw(
        &mut self,
        params: CallToolRequestParams,
    ) -> Result<Response, Error> {
        let id = self.generate_id()?;

        let request = Request::new(
            Some(id.clone()),
            crate::types::tool::commands::CALL,
            Some(params.with_meta(RequestParamsMeta::new(&id))),
        );

        self.send_request(request).await
    }

    /// Requests resource contents from MCP server
    ///
    /// # Example
    /// ```no_run
    /// use neva::client::Client;
    /// use neva::error::Error;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Error> {
    ///     let mut client = Client::new();
    ///
    ///     client.connect().await?;
    ///
    ///     let resource = client.read_resource("res://res_1").await?;
    ///     // Do something with the resource
    ///
    ///     client.disconnect().await
    /// }
    /// ```
    pub async fn read_resource(
        &mut self,
        uri: impl Into<Uri>,
    ) -> Result<ReadResourceResult, Error> {
        let id = self.generate_id()?;
        let request = Request::new(
            Some(id.clone()),
            crate::types::resource::commands::READ,
            Some(ReadResourceRequestParams {
                uri: uri.into(),
                meta: Some(RequestParamsMeta::new(&id)),
                #[cfg(feature = "server")]
                args: None,
            }),
        );

        self.send_request(request).await?.into_result()
    }

    /// Gets a prompt that MCP server provides
    ///
    /// # Example
    /// ```no_run
    /// use neva::client::Client;
    /// use neva::error::Error;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Error> {
    ///     let mut client = Client::new();
    ///
    ///     client.connect().await?;
    ///
    ///     let args = [
    ///         ("temperature", "50"),
    ///         ("style", "anything")
    ///     ];
    ///     let prompt = client.get_prompt("complex_prompt", args).await?;
    ///     // Do something with the prompt
    ///
    ///     client.disconnect().await
    /// }
    /// ```
    pub async fn get_prompt<N, Args>(
        &mut self,
        name: N,
        args: Args,
    ) -> Result<GetPromptResult, Error>
    where
        N: Into<String>,
        Args: shared::IntoArgs,
    {
        let id = self.generate_id()?;
        let request = Request::new(
            Some(id.clone()),
            crate::types::prompt::commands::GET,
            Some(GetPromptRequestParams {
                name: name.into(),
                meta: Some(RequestParamsMeta::new(&id)),
                args: args.into_args(),
            }),
        );

        self.send_request(request).await?.into_result()
    }

    /// Opens a long-lived notification subscription (MCP 2026-07-28).
    ///
    /// Sends `subscriptions/listen` and returns once the server has
    /// acknowledged the filter. Notifications delivered on the stream are
    /// dispatched to the handlers registered with [`Self::subscribe`] and its
    /// helpers ([`Self::on_tools_changed`] and friends), so those must be in
    /// place before listening -- and, for the capability-gated helpers, after
    /// [`Self::connect`], which is what discovers the capabilities they assert
    /// on.
    ///
    /// The returned [`Subscription`] carries the accepted filter -- the server
    /// silently drops types it does not advertise -- and ends the stream on
    /// [`Subscription::cancel`].
    ///
    /// # Example
    /// ```no_run
    /// use neva::{Client, error::Error, types::SubscriptionFilter};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Error> {
    ///     let mut client = Client::new();
    ///     client.connect().await?;
    ///     client.on_tools_changed(|_| async { println!("tools changed"); });
    ///
    ///     let subscription = client
    ///         .listen(SubscriptionFilter::new().with_tools_changed())
    ///         .await?;
    ///
    ///     println!("accepted: {:?}", subscription.acknowledged());
    ///     Ok(())
    /// }
    /// ```
    #[cfg(not(feature = "legacy-spec"))]
    pub async fn listen(
        &mut self,
        notifications: SubscriptionFilter,
    ) -> Result<Subscription, Error> {
        if self.is_legacy_peer() {
            return Err(Error::new(
                ErrorCode::MethodNotFound,
                "Peer speaks the legacy protocol; use subscribe_to_resource instead",
            ));
        }

        let id = self.generate_id()?;
        let mut request = Request::new(
            Some(id.clone()),
            crate::types::subscription::commands::LISTEN,
            Some(SubscriptionsListenRequestParams::new(notifications.clone())),
        );
        self.apply_client_meta(&mut request, None, None);

        let handler = self
            .handler
            .as_mut()
            .ok_or_else(|| Error::new(ErrorCode::InternalError, "Connection closed"))?;

        // Watch for the acknowledgment before sending: it is the first thing
        // the server puts on the stream, and the receive loop drops one nobody
        // is waiting for.
        let ack = handler.watch_ack(&id, &notifications);
        let sender = handler.sender();
        let release = handler.subscription_release();

        // Armed before the send, not after it. `watch_ack` has already
        // registered the waiter and the pending state, `send_listen` takes the
        // untimed request slot before it awaits the transport, and that await
        // is a suspension point like any other: a caller who drops this future
        // (an outer `tokio::time::timeout`, a lost `select!` branch) runs none
        // of the branches below, and everything registered so far would be left
        // behind. Nothing between here and `watch_ack` awaits, so there is no
        // gap left to fall into.
        let guard =
            subscription::EstablishmentGuard::new(id.clone(), release.clone(), sender.clone());

        let mut response = match handler.send_listen(request).await {
            Ok(response) => response,
            // Never reached the wire, so there is no stream to cancel -- only
            // this client's own bookkeeping to drop.
            Err(err) => {
                guard.forget();
                return Err(err);
            }
        };

        // Race the acknowledgment against the request's own reply: a peer that
        // rejects the subscription outright -- `MethodNotFound`, an
        // authorization failure, invalid params -- answers instead of
        // acknowledging, and waiting only on the acknowledgment would sit out
        // the whole timeout and report that instead of the server's reason.
        let timeout = self.options.timeout;
        let established = tokio::select! {
            biased;
            acknowledged = ack => Ok(acknowledged),
            answered = &mut response => Err(match answered {
                Ok(shared::PendingResponse::Response(resp)) => match resp {
                    // An error reply is the server's own explanation; surface it.
                    Response::Err(err) => err.error.into(),
                    // A success reply this early is the graceful-close result
                    // for a subscription that never carried anything.
                    Response::Ok(_) => Error::new(
                        ErrorCode::InternalError,
                        "Subscription ended before it was acknowledged",
                    ),
                },
                Ok(shared::PendingResponse::Timeout) => {
                    Error::new(ErrorCode::Timeout, "Subscription was not acknowledged")
                }
                // The slot's sender was dropped: the receive loop released it
                // on its way out, so the transport is gone. That is a lost
                // connection, not a peer that would not acknowledge, and
                // callers act on the two differently.
                Err(_) => Error::new(ErrorCode::InternalError, "Connection closed"),
            }),
            _ = tokio::time::sleep(timeout) => Err(Error::new(
                ErrorCode::Timeout,
                "Subscription was not acknowledged",
            )),
        };

        let acknowledged = match established {
            Ok(Ok(filter)) => filter,
            // The waiter's sender was dropped: the receive loop is gone.
            Ok(Err(_)) => {
                guard.abandon().await;
                return Err(Error::new(ErrorCode::InternalError, "Connection closed"));
            }
            Err(err) => {
                guard.abandon().await;
                return Err(err);
            }
        };

        // The server may narrow the filter -- that is the whole point of the
        // acknowledgment -- but it must not widen it. Notifications are
        // dispatched to the client's own handlers with no per-subscription
        // filtering, so an acknowledgment claiming a category or URI this call
        // never asked for would deliver events outside the requested scope.
        if !acknowledged.is_subset_of(&notifications) {
            guard.abandon().await;
            return Err(Error::new(
                ErrorCode::InvalidRequest,
                "Server acknowledged a subscription broader than the one requested",
            ));
        }

        // The handle takes over from here.
        guard.disarm();

        Ok(Subscription::new(
            id,
            notifications,
            acknowledged,
            response,
            sender,
            release,
        ))
    }

    /// Subscribes to a resource on the server to receive notifications when it changes.
    ///
    /// Legacy only in effect: MCP 2026-07-28 folds per-resource subscriptions
    /// into the `listen` filter, so against a 2026-07-28 peer this fails and
    /// `listen` with a `resourceSubscriptions` entry is the way. The method
    /// stays available because the dual-mode fallback still reaches legacy
    /// peers.
    pub async fn subscribe_to_resource(&mut self, uri: impl Into<Uri>) -> Result<(), Error> {
        #[cfg(not(feature = "legacy-spec"))]
        if !self.is_legacy_peer() {
            return Err(Error::new(
                ErrorCode::MethodNotFound,
                "resources/subscribe is legacy-only; use listen with a resource filter",
            ));
        }
        if !self.is_resource_subscription_supported() {
            return Err(Error::new(
                ErrorCode::MethodNotFound,
                "Server does not support resource subscriptions",
            ));
        }

        let params = SubscribeRequestParams::from(uri);
        let resp = self
            .command(crate::types::resource::commands::SUBSCRIBE, Some(params))
            .await?;

        match resp {
            Response::Ok(_) => Ok(()),
            Response::Err(err) => Err(err.error.into()),
        }
    }

    /// Unsubscribes from a resource on the server to stop receiving notifications about its changes.
    ///
    /// Legacy only in effect; see [`Self::subscribe_to_resource`]. Under MCP
    /// 2026-07-28 a subscription ends with the stream that carries it
    /// (`Subscription::cancel`).
    pub async fn unsubscribe_from_resource(&mut self, uri: impl Into<Uri>) -> Result<(), Error> {
        #[cfg(not(feature = "legacy-spec"))]
        if !self.is_legacy_peer() {
            return Err(Error::new(
                ErrorCode::MethodNotFound,
                "resources/unsubscribe is legacy-only; cancel the subscription instead",
            ));
        }
        if !self.is_resource_subscription_supported() {
            return Err(Error::new(
                ErrorCode::MethodNotFound,
                "Server does not support resource subscriptions",
            ));
        }

        let params = UnsubscribeRequestParams::from(uri);
        let resp = self
            .command(crate::types::resource::commands::UNSUBSCRIBE, Some(params))
            .await?;

        match resp {
            Response::Ok(_) => Ok(()),
            Response::Err(err) => Err(err.error.into()),
        }
    }

    /// Maps the `handler` to a specific `event`
    pub fn subscribe<E, F, R>(&mut self, event: E, handler: F)
    where
        E: Into<String>,
        F: Fn(Notification) -> R + Clone + Send + Sync + 'static,
        R: Future<Output = ()> + Send,
    {
        self.options
            .notification_handler
            .get_or_insert_default()
            .subscribe(event, handler);
    }

    /// Unsubscribe a handler from the `event`
    pub fn unsubscribe(&mut self, event: impl AsRef<str>) {
        if let Some(notification_handler) = &self.options.notification_handler {
            notification_handler.unsubscribe(event);
        }
    }

    /// Returns whether the server is configured to send the "notifications/resources/updated"
    #[inline]
    fn is_resource_subscription_supported(&self) -> bool {
        self.server_capabilities
            .as_ref()
            .and_then(|cap| cap.resources.as_ref())
            .is_some_and(|res| res.subscribe)
    }

    /// Returns whether the server is configured to send the "notifications/resources/list_changed"
    #[inline]
    fn is_resource_list_changed_supported(&self) -> bool {
        self.server_capabilities
            .as_ref()
            .and_then(|cap| cap.resources.as_ref())
            .is_some_and(|res| res.list_changed)
    }

    /// Returns whether the server is configured to send the "notifications/tools/list_changed"
    #[inline]
    fn is_tools_list_changed_supported(&self) -> bool {
        self.server_capabilities
            .as_ref()
            .and_then(|cap| cap.tools.as_ref())
            .is_some_and(|tool| tool.list_changed)
    }

    /// Returns whether the server is configured to send the "notifications/prompts/list_changed"
    #[inline]
    fn is_prompts_list_changed_supported(&self) -> bool {
        self.server_capabilities
            .as_ref()
            .and_then(|cap| cap.prompts.as_ref())
            .is_some_and(|prompt| prompt.list_changed)
    }

    /// Returns whether the client has elicitation capabilities
    #[inline]
    #[cfg(feature = "legacy-spec")]
    fn is_elicitation_supported(&self) -> bool {
        self.options.elicitation_capability.as_ref().is_some()
    }

    /// Returns whether the client has task augmentation capabilities
    #[inline]
    #[cfg(feature = "tasks")]
    fn is_client_supports_tasks(&self) -> bool {
        self.options.tasks_capability.as_ref().is_some()
    }

    /// Resolves the server's tasks capability from the negotiated server
    /// capabilities. Pre-2026-07-28 it is the top-level `tasks` field; under
    /// MCP 2026-07-28 tasks are an extension, so it is read from
    /// `capabilities.extensions["io.modelcontextprotocol/tasks"]`.
    #[cfg(all(feature = "tasks", feature = "legacy-spec"))]
    fn server_tasks_capability(&self) -> Option<crate::types::ServerTasksCapability> {
        self.server_capabilities
            .as_ref()
            .and_then(|c| c.tasks.clone())
    }

    /// Resolves the server's tasks capability from the negotiated server
    /// capabilities (MCP 2026-07-28 build).
    ///
    /// Tasks are an extension here, so the one place they can be advertised is
    /// `capabilities.extensions["io.modelcontextprotocol/tasks"]`. The
    /// pre-2026-07-28 top-level `tasks` field is deliberately not read: it can
    /// only come from a peer reached through the dual-mode fallback, whose task
    /// protocol this build does not speak (see
    /// [`Self::is_server_supports_tasks`]), so resolving it would only ever
    /// promise support that cannot be delivered.
    #[cfg(all(feature = "tasks", not(feature = "legacy-spec")))]
    fn server_tasks_capability(&self) -> Option<crate::types::ServerTasksCapability> {
        self.server_capabilities
            .as_ref()?
            .extensions
            .as_ref()
            .and_then(|ext| ext.get(crate::types::task::TASKS_EXTENSION_ID))
            .and_then(|v| serde_json::from_value(v.clone()).ok())
    }

    /// Returns whether the server has task augmentation capabilities
    #[inline]
    #[cfg(all(feature = "tasks", feature = "legacy-spec"))]
    fn is_server_supports_tasks(&self) -> bool {
        self.server_tasks_capability().is_some()
    }

    /// Returns whether the server has task augmentation capabilities
    ///
    /// A peer reached through the dual-mode fallback speaks the *legacy* task
    /// protocol -- different method set (`tasks/result`, `tasks/list`), a
    /// nested `CreateTaskResult`, a differently named status notification --
    /// and none of that wire surface is compiled into this build. It is
    /// reported as unsupported rather than answered with 2026-07-28 messages
    /// it cannot read; talking tasks to a legacy server needs a `legacy-spec`
    /// build, or the peers must simply agree on a generation. The peer check
    /// is belt-and-braces on top of
    /// [`Self::server_tasks_capability`](Self::server_tasks_capability) only
    /// reading the 2026-07-28 form: it also covers a peer that advertises the
    /// extension and then falls back.
    #[inline]
    #[cfg(all(feature = "tasks", not(feature = "legacy-spec")))]
    fn is_server_supports_tasks(&self) -> bool {
        !self.is_legacy_peer() && self.server_tasks_capability().is_some()
    }

    /// Returns whether the client supports cancelling tasks
    #[inline]
    #[cfg(all(feature = "tasks", feature = "legacy-spec"))]
    fn is_client_support_cancelling_tasks(&self) -> bool {
        self.options
            .tasks_capability
            .as_ref()
            .is_some_and(|c| c.cancel.is_some())
    }

    /// Returns whether the server supports cancelling tasks
    #[inline]
    #[cfg(all(feature = "tasks", feature = "legacy-spec"))]
    fn is_server_support_cancelling_tasks(&self) -> bool {
        self.server_tasks_capability()
            .is_some_and(|c| c.cancel.is_some())
    }

    /// Returns whether the server supports retrieving a task list
    #[inline]
    #[cfg(all(feature = "tasks", feature = "legacy-spec"))]
    fn is_server_support_task_list(&self) -> bool {
        self.server_tasks_capability()
            .is_some_and(|c| c.list.is_some())
    }

    /// Returns whether the client supports retrieving a task list
    #[inline]
    #[cfg(all(feature = "tasks", feature = "legacy-spec"))]
    fn is_client_support_task_list(&self) -> bool {
        self.options
            .tasks_capability
            .as_ref()
            .is_some_and(|c| c.list.is_some())
    }

    /// Returns whether the server supports task-augmented tools
    ///
    /// Under MCP 2026-07-28 the Tasks extension capability carries no
    /// per-request settings: a peer that advertises the extension at all
    /// accepts task-augmented requests, and the server decides per request
    /// whether to defer. A peer that fell back to the legacy protocol is
    /// excluded -- see [`Self::is_server_supports_tasks`].
    #[inline]
    #[cfg(all(feature = "tasks", not(feature = "legacy-spec")))]
    fn is_server_support_call_tool_with_tasks(&self) -> bool {
        self.is_server_supports_tasks()
    }

    /// Returns whether the server supports task-augmented tools
    #[inline]
    #[cfg(all(feature = "tasks", feature = "legacy-spec"))]
    fn is_server_support_call_tool_with_tasks(&self) -> bool {
        self.server_tasks_capability()
            .and_then(|c| c.requests)
            .and_then(|r| r.tools)
            .is_some_and(|t| t.call.is_some())
    }

    /// Sends a request to the MCP server
    #[inline]
    async fn send_request(&mut self, req: Request) -> Result<Response, Error> {
        // Checked at the send seam rather than in `call_tool`, so every way of
        // reaching a tool -- the plain call, the task builder -- goes past it.
        #[cfg(all(feature = "http-client", not(feature = "legacy-spec")))]
        if let Some(err) = self.blocked_tool_error(&req) {
            return Err(err);
        }

        #[cfg(not(feature = "legacy-spec"))]
        {
            // A legacy peer (dual-mode fallback) never speaks MRTR -- its
            // requests take the plain path, elicitation rides the legacy
            // server-push channel instead.
            if self.is_legacy_peer() {
                return self.plain_send_request(req).await;
            }
            self.run_with_mrtr(req).await
        }
        #[cfg(feature = "legacy-spec")]
        {
            self.plain_send_request(req).await
        }
    }

    /// Sends a request without the MRTR loop.
    #[inline]
    async fn plain_send_request(&mut self, req: Request) -> Result<Response, Error> {
        let resp = self
            .handler
            .as_mut()
            .ok_or_else(|| Error::new(ErrorCode::InternalError, "Connection closed"))?
            .send_request(req)
            .await?;
        #[cfg(not(feature = "legacy-spec"))]
        self.record_server_info(&resp);
        Ok(resp)
    }

    /// Picks up `io.modelcontextprotocol/serverInfo` from a result's `_meta`.
    ///
    /// Under MCP 2026-07-28 the server identifies itself on every result rather
    /// than once in a handshake, so the first result that carries it is what
    /// populates [`Self::server_info`].
    #[cfg(not(feature = "legacy-spec"))]
    fn record_server_info(&mut self, resp: &Response) {
        if self.server_info.is_some() {
            return;
        }
        let Response::Ok(ok) = resp else { return };
        if let Some(info) = ok
            .result
            .get("_meta")
            .and_then(|m| m.get("io.modelcontextprotocol/serverInfo"))
            .and_then(|v| serde_json::from_value::<Implementation>(v.clone()).ok())
        {
            self.server_info = Some(info);
        }
    }

    /// Sends a request and transparently drives the MRTR loop: while the
    /// server responds with an `input_required` result, fulfil each
    /// elicitation via the configured handler and re-issue the original
    /// request (new id) with `inputResponses` + the echoed `requestState`.
    #[cfg(not(feature = "legacy-spec"))]
    async fn run_with_mrtr(&mut self, req: Request) -> Result<Response, Error> {
        let max_rounds = self.options.max_mrtr_rounds;
        let method = req.method.clone();
        let original_params = req.params.clone();
        let mrtr_method = shared::is_mrtr_method(method.as_str());

        let mut req = req;
        self.apply_client_meta(&mut req, None, None);

        // The budget counts re-issue rounds, not the initial send, so allow the
        // first attempt plus `max_rounds` retries. `0..=max_rounds` (vs.
        // `max_rounds + 1`) also avoids overflow at `usize::MAX`.
        for _ in 0..=max_rounds {
            let resp = self
                .handler
                .as_mut()
                .ok_or_else(|| Error::new(ErrorCode::InternalError, "Connection closed"))?
                .send_request(req)
                .await?;
            self.record_server_info(&resp);

            // MRTR only applies to success results carrying the
            // `input_required` discriminator; anything else -- including a
            // result with no `resultType` at all -- is final.
            let input_required_result = match &resp {
                Response::Ok(ok)
                    if mrtr_method
                        && resp.result_type() == Some(crate::types::ResultType::InputRequired) =>
                {
                    serde_json::from_value::<crate::types::mrtr::InputRequiredResult>(
                        ok.result.clone(),
                    )
                    .map_err(Error::from)?
                }
                _ => return Ok(resp),
            };
            let ir = input_required_result;

            let mut input_responses = crate::types::mrtr::InputResponses::new();
            if let Some(reqs) = ir.input_requests {
                for (key, request) in reqs {
                    input_responses.insert(key, self.fulfil_input(request).await?);
                }
            }

            let new_id = self.generate_id()?;
            let mut retry = Request::new(Some(new_id), method.clone(), original_params.clone());
            self.apply_client_meta(&mut retry, Some(input_responses), ir.request_state);
            req = retry;
        }

        Err(Error::new(
            ErrorCode::InternalError,
            "MRTR exceeded the maximum number of rounds",
        ))
    }

    /// Sets `clientInfo` + MRTR capability `_meta` on a request, and optionally
    /// the MRTR `inputResponses` / `requestState`, preserving existing `_meta`.
    ///
    /// Also populates W3C Trace Context (`traceparent` / `tracestate`) from the
    /// configured [`trace_context_provider`](crate::client::options::McpOptions::with_trace_context_provider),
    /// when installed. This is the single assembly point for outbound 2026-07-28 `_meta`,
    /// so both single sends (via [`Self::run_with_mrtr`]) and batched requests
    /// (via [`Self::run_batch_with_mrtr`]) carry trace context.
    #[cfg(not(feature = "legacy-spec"))]
    fn apply_client_meta(
        &self,
        req: &mut Request,
        input_responses: Option<crate::types::mrtr::InputResponses>,
        request_state: Option<String>,
    ) {
        let mut meta = req.meta().unwrap_or_default();
        meta.client_info = Some(self.options.implementation.clone());
        // Required on every request under MCP 2026-07-28, and it must agree
        // with the `MCP-Protocol-Version` header the HTTP transport sets.
        meta.protocol_version = Some(self.expected_protocol_ver().to_string());
        // Each flag reflects what this client can actually fulfil right now: a
        // configured handler for elicitation/sampling, and -- since roots are
        // data rather than a handler -- a declared roots capability. That is
        // either an explicit `with_roots(..)` or simply having roots, and it
        // deliberately stays true for an empty list: an empty
        // `ListRootsResult` is a valid answer, so a client that opted in must
        // not be gated out of being asked.
        meta.client_capabilities = Some(crate::types::mrtr::ClientMrtrCapabilities {
            elicitation: self.options.elicitation_handler.is_some(),
            sampling: self.options.sampling_handler.is_some(),
            roots: self.options.roots_capability().is_some(),
        });

        if input_responses.is_some() {
            meta.input_responses = input_responses;
        }

        if request_state.is_some() {
            meta.request_state = request_state;
        }

        if let Some(provider) = self.options.trace_context_provider.as_ref()
            && let Some(tc) = provider()
        {
            meta.traceparent = Some(tc.traceparent);
            meta.tracestate = tc.tracestate;
            meta.baggage = tc.baggage;
        }

        // Request-scoped logging level (replaces the removed `logging/setLevel`).
        if self.options.log_level.is_some() {
            meta.log_level = self.options.log_level;
        }

        req.set_meta(meta);
    }

    /// Applies the initial per-request 2026-07-28 client metadata (`clientInfo` /
    /// `clientCapabilities`, plus trace context) to every [`Request`] in a
    /// batch. The MRTR re-run fields (`inputResponses` / `requestState`) stay
    /// `None` here -- they are filled per request on each retry round by
    /// [`Self::run_batch_with_mrtr`]. Notifications are left untouched.
    #[cfg(not(feature = "legacy-spec"))]
    fn apply_client_meta_to_batch(&self, items: &mut [MessageEnvelope]) {
        for envelope in items {
            if let MessageEnvelope::Request(req) = envelope {
                self.apply_client_meta(req, None, None);
            }
        }
    }

    /// Fulfils one server-requested input, whatever its kind, and returns the
    /// raw result to echo back under the request's key.
    ///
    /// Sampling and roots are fulfilled here, on the MRTR loop -- *not* as
    /// server-initiated pushes: under MCP 2026-07-28 there is no such channel. The
    /// client only ever gets asked for a kind it declared in
    /// [`ClientMrtrCapabilities`](crate::types::mrtr::ClientMrtrCapabilities),
    /// so a missing handler here means the server ignored those flags.
    #[cfg(not(feature = "legacy-spec"))]
    async fn fulfil_input(
        &self,
        request: crate::types::mrtr::InputRequest,
    ) -> Result<serde_json::Value, Error> {
        use crate::types::mrtr::InputRequest;

        #[allow(deprecated)]
        let value = match request {
            InputRequest::Elicitation(params) => match self.options.elicitation_handler.clone() {
                Some(handler) => serde_json::to_value(handler(params).await)?,
                None => return Err(no_fulfiller("elicitation")),
            },
            InputRequest::Sampling(params) => match self.options.sampling_handler.clone() {
                Some(handler) => serde_json::to_value(handler(*params).await)?,
                None => return Err(no_fulfiller("sampling")),
            },
            // Roots are configured data, not a handler: the client answers
            // from the list it was built with.
            InputRequest::Roots(_) => serde_json::to_value(crate::types::root::ListRootsResult {
                roots: self.options.roots(),
                meta: None,
            })?,
        };
        Ok(value)
    }

    /// Creates a [`BatchBuilder`] for sending multiple requests in a single batch.
    ///
    /// # Example
    /// ```no_run
    /// use neva::client::Client;
    /// use neva::error::Error;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Error> {
    ///     let mut client = Client::new();
    ///     client.connect().await?;
    ///
    ///     let responses = client
    ///         .batch()
    ///         .list_tools()
    ///         .list_prompts()
    ///         .send()
    ///         .await?;
    ///
    ///     client.disconnect().await
    /// }
    /// ```
    pub fn batch(&mut self) -> BatchBuilder<'_> {
        BatchBuilder {
            client: self,
            items: Vec::new(),
        }
    }

    /// Returns a [`TaskBuilder`] for constructing a task-augmented request.
    ///
    /// Chain setters such as [`TaskBuilder::with_ttl`] to configure the task,
    /// then call [`TaskBuilder::call_tool`] to execute.
    ///
    /// # Example
    /// ```no_run
    /// use neva::client::Client;
    /// use neva::error::Error;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Error> {
    ///     let mut client = Client::new();
    ///     client.connect().await?;
    ///
    ///     let result = client
    ///         .task()
    ///         .with_ttl(5000)
    ///         .call_tool("echo", [("message", "Hello MCP!")])
    ///         .await?;
    ///
    ///     client.disconnect().await
    /// }
    /// ```
    #[cfg(feature = "tasks")]
    pub fn task(&mut self) -> TaskBuilder<'_> {
        TaskBuilder {
            client: self,
            metadata: TaskMetadata::default(),
        }
    }

    /// Sends a batch of messages to the MCP server and awaits all responses.
    ///
    /// Items that are [`MessageEnvelope::Request`] each get a response slot in
    /// the returned `Vec`, in the same order they appear in `items`.
    /// [`MessageEnvelope::Notification`] items are sent fire-and-forget and
    /// produce no slot.
    ///
    /// All in-flight requests are awaited concurrently; a failure in one
    /// does not cancel the others.
    ///
    /// # Errors
    /// Returns [`Error`] if the client is not connected, the batch is empty,
    /// or any response channel is closed or times out.
    pub async fn call_batch(
        &mut self,
        items: Vec<MessageEnvelope>,
    ) -> Result<Vec<Response>, Error> {
        // One blocked tool fails the whole batch, the same as a duplicate id
        // does: the batch is one write, and there is no way to drop a single
        // entry from it without silently changing what the caller asked for.
        #[cfg(all(feature = "http-client", not(feature = "legacy-spec")))]
        if let Some(err) = items.iter().find_map(|env| match env {
            MessageEnvelope::Request(req) => self.blocked_tool_error(req),
            _ => None,
        }) {
            return Err(err);
        }

        // Under MCP 2026-07-28 a batched request may elicit just like a single send, so
        // the batch is driven through the same MRTR retry loop (see
        // `run_batch_with_mrtr`) rather than returning the protocol-intermediate
        // `input_required` result as final. A legacy peer (dual-mode
        // fallback) never speaks MRTR and takes the plain path.
        #[cfg(not(feature = "legacy-spec"))]
        {
            if !self.is_legacy_peer() {
                return self.run_batch_with_mrtr(items).await;
            }
        }
        let handler = self
            .handler
            .as_mut()
            .ok_or_else(|| Error::new(ErrorCode::InternalError, "Connection closed"))?;

        let request_timeout = handler.timeout();
        let pending = handler.pending().clone();
        let token = handler.cancellation();
        let receivers = handler.send_batch(items).await?;

        collect_batch_responses(receivers, &pending, request_timeout, token)
            .await
            .into_iter()
            .collect()
    }

    /// Drives the MRTR retry loop across an entire batch.
    ///
    /// Each batched [`Request`] that elicits -- the server replies with an
    /// `input_required` result -- is fulfilled via the configured elicitation
    /// handler and re-issued (carrying `inputResponses` + the echoed
    /// `requestState`) alongside any other still-eliciting requests, so the
    /// whole batch is driven to completion in lock-step rounds. One transport
    /// write per round preserves the batching benefit; final
    /// (non-`input_required`) responses are retained and not re-sent. Each
    /// request keeps its slot in the returned `Vec`, in input order;
    /// notifications (and any non-request envelopes) are sent once, in the
    /// first round, and produce no slot.
    #[cfg(not(feature = "legacy-spec"))]
    async fn run_batch_with_mrtr(
        &mut self,
        items: Vec<MessageEnvelope>,
    ) -> Result<Vec<Response>, Error> {
        let max_rounds = self.options.max_mrtr_rounds;

        // A per-request slot: either still eliciting (carrying what is needed to
        // re-issue) or resolved to its final response.
        enum Slot {
            Pending {
                method: String,
                original_params: Option<serde_json::Value>,
                req: Option<Request>,
            },
            Done(Response),
        }

        // Seed round-0 metadata (`clientInfo` / `clientCapabilities` / trace
        // context) on every request via the shared assembly path, then split
        // requests (which get ordered slots) from fire-and-forget extras
        // (notifications) sent only in the first round.
        let mut items = items;
        self.apply_client_meta_to_batch(&mut items);

        let mut slots: Vec<Slot> = Vec::new();
        let mut extras: Vec<MessageEnvelope> = Vec::new();
        for envelope in items {
            match envelope {
                MessageEnvelope::Request(req) => slots.push(Slot::Pending {
                    method: req.method.clone(),
                    original_params: req.params.clone(),
                    req: Some(req),
                }),
                other => extras.push(other),
            }
        }

        // No requests to drive through MRTR: send any extras (notifications)
        // once and let `send_batch` surface the same connection-closed /
        // empty-batch errors a non-eliciting batch would.
        if slots.is_empty() {
            let handler = self
                .handler
                .as_mut()
                .ok_or_else(|| Error::new(ErrorCode::InternalError, "Connection closed"))?;
            let request_timeout = handler.timeout();
            let pending = handler.pending().clone();
            let token = handler.cancellation();
            let receivers = handler.send_batch(extras).await?;
            return collect_batch_responses(receivers, &pending, request_timeout, token)
                .await
                .into_iter()
                .collect();
        }

        // Round 0 is the initial batch send; rounds `1..=max_rounds` are the
        // re-issues the budget allows (the cap counts retries, not the first
        // send). `0..=max_rounds` also avoids overflow at `usize::MAX`.
        for round in 0..=max_rounds {
            // Collect this round's outgoing requests; notifications ride along once.
            let mut envelopes: Vec<MessageEnvelope> = Vec::new();
            if round == 0 {
                envelopes.append(&mut extras);
            }

            let mut round_slots: Vec<usize> = Vec::new();
            for (i, slot) in slots.iter_mut().enumerate() {
                if let Slot::Pending { req, .. } = slot
                    && let Some(request) = req.take()
                {
                    round_slots.push(i);
                    envelopes.push(MessageEnvelope::Request(request));
                }
            }

            if round_slots.is_empty() {
                break;
            }

            // One transport write; await this round's replies concurrently.
            let handler = self
                .handler
                .as_mut()
                .ok_or_else(|| Error::new(ErrorCode::InternalError, "Connection closed"))?;

            let request_timeout = handler.timeout();
            let pending = handler.pending().clone();
            let token = handler.cancellation();
            let receivers = handler.send_batch(envelopes).await?;
            let responses =
                collect_batch_responses(receivers, &pending, request_timeout, token).await;

            // `responses` aligns with `round_slots`: `send_batch` preserves
            // request order and extras produce no receiver. Final responses fill
            // their slot; `input_required` ones are fulfilled and re-issued.
            for (slot_i, resp) in round_slots.into_iter().zip(responses) {
                let resp = resp?;
                self.record_server_info(&resp);
                let (method, original_params) = match &slots[slot_i] {
                    Slot::Pending {
                        method,
                        original_params,
                        ..
                    } => (method.clone(), original_params.clone()),
                    Slot::Done(_) => unreachable!("a round slot is always pending"),
                };

                let is_input_required = shared::is_mrtr_method(method.as_str())
                    && resp.result_type() == Some(crate::types::ResultType::InputRequired);

                if !is_input_required {
                    slots[slot_i] = Slot::Done(resp);
                    continue;
                }

                let ir = match &resp {
                    Response::Ok(ok) => serde_json::from_value::<
                        crate::types::mrtr::InputRequiredResult,
                    >(ok.result.clone())
                    .map_err(Error::from)?,
                    Response::Err(_) => unreachable!("input_required is a success result"),
                };

                let mut input_responses = crate::types::mrtr::InputResponses::new();
                if let Some(reqs) = ir.input_requests {
                    for (key, request) in reqs {
                        input_responses.insert(key, self.fulfil_input(request).await?);
                    }
                }

                let new_id = self.generate_id()?;
                let mut retry = Request::new(Some(new_id), method, original_params);

                self.apply_client_meta(&mut retry, Some(input_responses), ir.request_state);

                if let Slot::Pending { req, .. } = &mut slots[slot_i] {
                    *req = Some(retry);
                }
            }
        }

        // Assemble in slot order; a slot still pending exhausted the rounds.
        let mut out = Vec::with_capacity(slots.len());
        for slot in slots {
            match slot {
                Slot::Done(resp) => out.push(resp),
                Slot::Pending { .. } => {
                    return Err(Error::new(
                        ErrorCode::InternalError,
                        "MRTR exceeded the maximum number of rounds",
                    ));
                }
            }
        }
        Ok(out)
    }

    /// Sends a response to the MCP server
    ///
    /// Only the legacy profile has server->client requests to answer.
    #[inline]
    #[cfg(all(feature = "tasks", feature = "legacy-spec"))]
    async fn send_response(&mut self, req: Response) -> Result<(), Error> {
        self.handler
            .as_mut()
            .ok_or_else(|| Error::new(ErrorCode::InternalError, "Connection closed"))?
            .send_response(req)
            .await;
        Ok(())
    }

    /// Sends a notification to the MCP server
    #[inline]
    async fn send_notification(
        &mut self,
        method: &str,
        params: Option<serde_json::Value>,
    ) -> Result<(), Error> {
        let notification = Notification::new(method, params);
        self.handler
            .as_mut()
            .ok_or_else(|| Error::new(ErrorCode::InternalError, "Connection closed"))?
            .send_notification(notification)
            .await
    }

    #[cfg(feature = "tracing")]
    fn register_tracing_notification_handlers(&mut self) {
        use crate::types::notification::commands::*;

        self.subscribe(MESSAGE, Self::default_notification_handler);
        self.subscribe(STDERR, Self::default_notification_handler);
        self.subscribe(PROGRESS, Self::default_notification_handler);
    }

    #[cfg(feature = "tracing")]
    async fn default_notification_handler(notification: Notification) {
        notification.write();
    }

    /// Generates a new [`RequestId`]
    #[inline]
    fn generate_id(&self) -> Result<RequestId, Error> {
        self.handler
            .as_ref()
            .ok_or_else(|| Error::new(ErrorCode::InternalError, "Connection closed"))
            .map(|h| h.next_id())
    }

    /// Cancels the transport and clears connection state without sending a
    /// notification. Used when initialization fails after the transport has
    /// already been started (e.g. protocol version mismatch in `init()`).
    #[inline]
    fn cancel_transport(&mut self) {
        if let Some(token) = self.cancellation_token.take() {
            token.cancel();
        }
        self.handler = None;
    }

    #[inline]
    fn wait_for_shutdown_signal(&mut self) {
        if let Some(token) = self.cancellation_token.clone() {
            shared::wait_for_shutdown_signal(token);
        };
    }

    #[cfg(feature = "tasks")]
    pub(crate) fn ensure_tasks_supported(&self) {
        assert!(
            self.is_client_supports_tasks(),
            "Client does not support task-augmented requests. You may configure it with `Client::with_options(|opt| opt.with_tasks(...))` method."
        );

        assert!(
            self.is_server_supports_tasks(),
            "Server does not support task-augmented requests."
        );
    }
}

#[cfg(all(feature = "tasks", not(feature = "legacy-spec")))]
impl shared::TaskApi for Client {
    /// Retrieves the full task state: status plus, depending on it, the
    /// outstanding input requests, the terminal result, or the error.
    async fn get_task(&mut self, id: impl Into<String>) -> Result<DetailedTask, Error> {
        let params = GetTaskRequestParams { id: id.into() };
        self.command(crate::types::task::commands::GET, Some(params))
            .await?
            .into_result()
    }

    /// Submits responses to a task's outstanding input requests.
    async fn update_task(
        &mut self,
        id: impl Into<String>,
        responses: crate::types::mrtr::InputResponses,
    ) -> Result<(), Error> {
        let params = UpdateTaskRequestParams {
            id: id.into(),
            input_responses: responses,
        };
        self.command(crate::types::task::commands::UPDATE, Some(params))
            .await
            .map(|_| ())
    }

    /// Cancels a task that is currently running.
    ///
    /// The reply is an empty acknowledgement: cancellation is cooperative, so
    /// the task may still reach a non-`cancelled` terminal status. Poll
    /// `get_task` to learn the outcome.
    async fn cancel_task(&mut self, id: impl Into<String>) -> Result<(), Error> {
        let params = CancelTaskRequestParams { id: id.into() };
        self.command(crate::types::task::commands::CANCEL, Some(params))
            .await
            .map(|_| ())
    }

    /// Answers one outstanding input request with the client's configured
    /// handler for that kind.
    async fn fulfil_input(
        &mut self,
        request: &crate::types::mrtr::InputRequest,
    ) -> Result<serde_json::Value, Error> {
        use crate::types::mrtr::InputRequest;

        match request {
            InputRequest::Elicitation(params) => {
                let handler = self.options.elicitation_handler.as_ref().ok_or_else(|| {
                    Error::new(
                        ErrorCode::InvalidRequest,
                        "Client has no elicitation handler. Configure one with `Client::map_elicitation(...)`.",
                    )
                })?;
                let result = handler(params.clone()).await;
                serde_json::to_value(result).map_err(Into::into)
            }
            other => Err(Error::new(
                ErrorCode::InvalidRequest,
                format!(
                    "Client cannot fulfil `{}` input requests on the task substrate",
                    other.method()
                ),
            )),
        }
    }
}

#[cfg(all(feature = "tasks", feature = "legacy-spec"))]
impl shared::TaskApi for Client {
    /// Retrieves task result. If the task is not completed yet, waits until it completes or cancels.
    async fn get_task_result<T>(&mut self, id: impl Into<String>) -> Result<T, Error>
    where
        T: DeserializeOwned,
    {
        let params = GetTaskPayloadRequestParams { id: id.into() };
        self.command(crate::types::task::commands::RESULT, Some(params))
            .await?
            .into_result()
    }

    /// Retrieve task status
    async fn get_task(&mut self, id: impl Into<String>) -> Result<Task, Error> {
        let params = GetTaskRequestParams { id: id.into() };
        self.command(crate::types::task::commands::GET, Some(params))
            .await?
            .into_result()
    }

    /// Cancels a task that is currently running
    ///
    /// # Panics
    /// If the client or server does not support cancelling tasks
    async fn cancel_task(&mut self, id: impl Into<String>) -> Result<Task, Error> {
        assert!(
            self.is_client_support_cancelling_tasks(),
            "Client does not support cancelling tasks.  You may configure it with `Client::with_options(|opt| opt.with_tasks(...))` method."
        );

        assert!(
            self.is_server_support_cancelling_tasks(),
            "Server does not support cancelling tasks."
        );

        let params = CancelTaskRequestParams { id: id.into() };
        self.command(crate::types::task::commands::CANCEL, Some(params))
            .await?
            .into_result()
    }

    /// Retrieves a list of tasks
    ///
    /// # Panics
    /// If the client or server does not support retrieving a task list
    async fn list_tasks(&mut self, cursor: Option<Cursor>) -> Result<ListTasksResult, Error> {
        assert!(
            self.is_client_support_task_list(),
            "Client does not support retrieving a task list.  You may configure it with `Client::with_options(|opt| opt.with_tasks(...))` method."
        );

        assert!(
            self.is_server_support_task_list(),
            "Server does not support retrieving a task list."
        );

        let params = ListTasksRequestParams { cursor };
        self.command(crate::types::task::commands::LIST, Some(params))
            .await?
            .into_result()
    }

    async fn handle_input(&mut self, id: &str, params: TaskPayload) -> Result<(), Error> {
        let params = params.to::<ElicitRequestParams>()?;
        if let Some(handler) = &self.options.elicitation_handler {
            use crate::types::IntoResponse;

            let result = handler(params).await.with_related_task(id);

            let id = id.parse::<RequestId>().expect("Invalid Request Id");

            self.send_response(result.into_response(id)).await?;
        }
        Ok(())
    }
}

/// Awaits a batch's per-request receivers concurrently, returning one result
/// per receiver in input order, with the same per-request timeout and pending
/// cleanup as a single [`RequestHandler::send_request`].
///
/// Uses `join_all` (not `try_join_all`) so every future runs to completion: the
/// timeout-cleanup branch (`pending.pop`) executes for each timed-out request
/// even when another request in the same batch has already failed.
async fn collect_batch_responses(
    receivers: Vec<(
        RequestId,
        tokio::sync::oneshot::Receiver<crate::shared::PendingResponse>,
    )>,
    pending: &crate::shared::RequestQueue,
    request_timeout: std::time::Duration,
    token: tokio_util::sync::CancellationToken,
) -> Vec<Result<Response, Error>> {
    use futures_util::future::join_all;

    let futures = receivers.into_iter().map(|(id, rx)| {
        let pending = pending.clone();
        let token = token.clone();
        async move {
            tokio::select! {
                biased;
                // The transport died (or a shutdown signal cancelled it)
                // -- no response is coming for any receiver.
                _ = token.cancelled() => {
                    let _ = pending.pop(&id);
                    Err(Error::new(ErrorCode::InternalError, "Connection closed"))
                }
                result = tokio::time::timeout(request_timeout, rx) => match result {
                    Ok(Ok(crate::shared::PendingResponse::Response(resp))) => Ok(resp),
                    Ok(Ok(crate::shared::PendingResponse::Timeout)) => {
                        Err(Error::new(ErrorCode::Timeout, "Batch request timed out"))
                    }
                    Ok(Err(_)) => Err(Error::new(
                        ErrorCode::InternalError,
                        "Response channel closed",
                    )),
                    Err(_) => {
                        let _ = pending.pop(&id);
                        Err(Error::new(ErrorCode::Timeout, "Batch request timed out"))
                    }
                }
            }
        }
    });

    join_all(futures).await
}

/// The error for an input kind the server asked for but this client has no
/// fulfiller for -- only reachable if the server ignored the declared
/// [`ClientMrtrCapabilities`](crate::types::mrtr::ClientMrtrCapabilities).
#[cfg(not(feature = "legacy-spec"))]
fn no_fulfiller(kind: &str) -> Error {
    Error::new(
        ErrorCode::InvalidRequest,
        format!("server requested {kind} but no handler is configured"),
    )
}

/// Whether a `server/discover` failure means "this server doesn't speak
/// the 2026-07-28 protocol" -- the dual-mode fallback triggers only then.
///
/// * `MethodNotFound` -- a legacy server rejecting the unknown method
///   (neva's own legacy build answers exactly this);
/// * `InvalidRequest` -- strict servers rejecting the 2026-07-28 request shape;
/// * `ParseError` -- a non-JSON-RPC reply (an HTTP 4xx page) or an error
///   code outside neva's `ErrorCode` set (e.g. the TS SDK's `-32000`
///   "server not initialized"), both of which surface as parse failures.
///
/// Network-level failures (`Timeout`, `InternalError`/"Connection
/// closed") are *not* triggers: the server never answered, so falling
/// back would only mask the outage.
#[cfg(not(feature = "legacy-spec"))]
fn is_fallback_trigger(err: &Error) -> bool {
    matches!(
        err.code,
        ErrorCode::MethodNotFound | ErrorCode::InvalidRequest | ErrorCode::ParseError
    )
}

#[inline]
fn make_handler<F, R, P, O>(handler: F) -> Handler<P, O>
where
    F: Fn(P) -> R + Clone + Send + Sync + 'static,
    R: Future + Send,
    R::Output: Into<O>,
    P: Send + 'static,
    O: Send + 'static,
{
    Arc::new(move |params: P| {
        let handler = handler.clone();
        Box::pin(async move { handler(params).await.into() })
    })
}

type Handler<P, O> =
    Arc<dyn Fn(P) -> std::pin::Pin<Box<dyn Future<Output = O> + Send>> + Send + Sync>;

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

    #[tokio::test]
    async fn call_batch_requires_connected_client() {
        let mut client = Client::new();
        let result = client.call_batch(vec![]).await;
        assert!(
            result.is_err(),
            "disconnected client should return an error"
        );
    }

    #[cfg(not(feature = "legacy-spec"))]
    #[test]
    fn batch_injects_rc_client_meta_per_request() {
        use serde_json::json;

        let mut client = Client::new();
        // Registering an elicitation handler makes the client declare
        // `clientCapabilities.elicitation = true`.
        client.map_elicitation(|_params: ElicitRequestParams| async { ElicitResult::accept() });

        let req = Request::new(
            Some(RequestId::Number(1)),
            "tools/call",
            Some(json!({ "name": "greet", "arguments": {} })),
        );
        let mut items = vec![
            MessageEnvelope::Request(req),
            // Notifications must be left untouched.
            MessageEnvelope::Notification(Notification::new("notifications/progress", None)),
        ];

        client.apply_client_meta_to_batch(&mut items);

        let MessageEnvelope::Request(req) = &items[0] else {
            panic!("first item must be a request");
        };
        let meta = &req.params.as_ref().expect("params present")["_meta"];
        // Without this injection a batched eliciting tools/call is rejected as
        // if the client did not support elicitation.
        assert_eq!(
            meta["io.modelcontextprotocol/clientCapabilities"]["elicitation"],
            json!(true)
        );
        assert!(meta["io.modelcontextprotocol/clientInfo"].is_object());
        assert_eq!(
            meta["io.modelcontextprotocol/protocolVersion"],
            json!("2026-07-28")
        );

        // The notification carries no params/_meta.
        let MessageEnvelope::Notification(notif) = &items[1] else {
            panic!("second item must be a notification");
        };
        assert!(notif.params.is_none());
    }

    /// A configured trace-context provider is invoked during 2026-07-28 metadata
    /// assembly, so `_meta.traceparent`/`tracestate` reach the wire alongside
    /// `clientInfo` -- for both single sends and (via the same path) batches.
    #[cfg(not(feature = "legacy-spec"))]
    #[test]
    fn apply_client_meta_injects_trace_context() {
        use crate::client::options::TraceContext;
        use serde_json::json;

        let client = Client::new().with_options(|o| {
            o.with_trace_context_provider(|| {
                Some(TraceContext {
                    traceparent: "tp".into(),
                    tracestate: Some("ts".into()),
                    baggage: Some("bg".into()),
                })
            })
        });

        let mut req = Request::new(
            Some(RequestId::Number(1)),
            "tools/call",
            Some(json!({ "name": "greet", "arguments": {} })),
        );
        client.apply_client_meta(&mut req, None, None);

        let meta = &req.params.as_ref().expect("params present")["_meta"];
        assert_eq!(meta["traceparent"], json!("tp"));
        assert_eq!(meta["tracestate"], json!("ts"));
        // Trace context is assembled alongside the rest of the 2026-07-28 metadata.
        assert!(meta["io.modelcontextprotocol/clientInfo"].is_object());
    }

    /// With no provider installed, no trace fields are emitted.
    #[cfg(not(feature = "legacy-spec"))]
    #[test]
    fn apply_client_meta_omits_trace_context_without_provider() {
        use serde_json::json;

        let client = Client::new();
        let mut req = Request::new(
            Some(RequestId::Number(1)),
            "tools/call",
            Some(json!({ "name": "greet", "arguments": {} })),
        );
        client.apply_client_meta(&mut req, None, None);

        let meta = &req.params.as_ref().expect("params present")["_meta"];
        assert!(meta.get("traceparent").is_none());
        assert!(meta.get("tracestate").is_none());
    }
}

#[cfg(all(test, not(feature = "legacy-spec")))]
mod fallback_trigger_tests {
    use super::*;

    fn err(code: ErrorCode) -> Error {
        Error::new(code, "test")
    }

    #[test]
    fn protocol_level_rejections_trigger_the_fallback() {
        assert!(is_fallback_trigger(&err(ErrorCode::MethodNotFound)));
        assert!(is_fallback_trigger(&err(ErrorCode::InvalidRequest)));
        // Non-JSON-RPC replies (HTTP 4xx pages) and unknown error codes
        // (e.g. the TS SDK's -32000) surface as parse failures.
        assert!(is_fallback_trigger(&err(ErrorCode::ParseError)));
    }

    #[test]
    fn transport_failures_do_not_trigger_the_fallback() {
        assert!(!is_fallback_trigger(&err(ErrorCode::Timeout)));
        assert!(!is_fallback_trigger(&err(ErrorCode::InternalError)));
        assert!(!is_fallback_trigger(&err(ErrorCode::InvalidParams)));
    }
}

/// The dual-mode "Done when" (issue #84): a 2026-07-28 client completes calls
/// against a 2025-11-25 server via the `initialize` fallback. The legacy
/// server is a raw-HTTP mock because a legacy neva server cannot exist
/// in an 2026-07-28 build.
#[cfg(all(test, feature = "http-client", not(feature = "legacy-spec")))]
mod dual_mode_tests {
    use super::*;
    use std::sync::Mutex;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::{TcpListener, TcpStream};

    const LEGACY_SESSION_ID: &str = "6f2f0dc8-6a5e-4f6e-9c1a-2b7f9d3f1c11";

    /// Reads one HTTP/1.1 request; returns `(head, body)`.
    async fn read_request(stream: &mut TcpStream) -> Option<(String, String)> {
        let mut buf = Vec::new();
        let mut tmp = [0u8; 2048];
        let header_end = loop {
            let n = stream.read(&mut tmp).await.ok()?;
            if n == 0 {
                return None;
            }
            buf.extend_from_slice(&tmp[..n]);
            if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
                break pos + 4;
            }
            if buf.len() > 65536 {
                return None;
            }
        };
        let head = String::from_utf8_lossy(&buf[..header_end]).to_string();
        let content_length = head
            .lines()
            .find_map(|l| {
                l.to_ascii_lowercase()
                    .strip_prefix("content-length:")
                    .map(|v| v.trim().parse::<usize>().ok())
            })
            .flatten()
            .unwrap_or(0);
        while buf.len() < header_end + content_length {
            let n = stream.read(&mut tmp).await.ok()?;
            if n == 0 {
                return None;
            }
            buf.extend_from_slice(&tmp[..n]);
        }
        let body =
            String::from_utf8_lossy(&buf[header_end..header_end + content_length]).to_string();
        Some((head, body))
    }

    async fn write_response(stream: &mut TcpStream, status: &str, extra_headers: &str, body: &str) {
        let resp = format!(
            "HTTP/1.1 {status}\r\n{extra_headers}Content-Length: {}\r\nConnection: keep-alive\r\n\r\n{body}",
            body.len()
        );
        let _ = stream.write_all(resp.as_bytes()).await;
    }

    fn rpc_result(id: &serde_json::Value, result: serde_json::Value) -> String {
        serde_json::json!({ "jsonrpc": "2.0", "id": id, "result": result }).to_string()
    }

    /// A minimal 2025-11-25 server: rejects `server/discover` with
    /// `MethodNotFound`, answers `initialize` with a session id, serves
    /// an SSE GET stream and an empty `tools/list`.
    /// How the mock answers `server/discover`: legacy servers reject it
    /// with a JSON-RPC `MethodNotFound` (neva's own legacy build) or a
    /// plain non-JSON-RPC 4xx page (framework routers, the TS SDK's
    /// "server not initialized" family); a future server answers
    /// *successfully* but with a `protocolVersion` this build does not
    /// support -- which must NOT trigger the fallback.
    /// A protected endpoint answering `401` with a non-JSON body must not
    /// trigger the fallback either -- that is an authentication failure,
    /// not evidence of a legacy peer.
    #[derive(Clone, Copy)]
    enum DiscoverReply {
        MethodNotFound,
        Html400,
        UnsupportedVersion,
        Unauthorized401,
        Unavailable503,
    }

    async fn serve_legacy(
        listener: TcpListener,
        log: Arc<Mutex<Vec<String>>>,
        reply: DiscoverReply,
    ) {
        loop {
            let Ok((mut stream, _)) = listener.accept().await else {
                return;
            };
            let log = log.clone();
            tokio::spawn(async move {
                loop {
                    let Some((head, body)) = read_request(&mut stream).await else {
                        return;
                    };
                    log.lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .push(format!("{head}{body}"));

                    if head.starts_with("GET") {
                        let _ = stream
                            .write_all(
                                b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\n\r\n: hi\n\n",
                            )
                            .await;
                        // Hold the stream open like a real legacy server.
                        tokio::time::sleep(std::time::Duration::from_secs(60)).await;
                        return;
                    }

                    let msg: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
                    let id = msg.get("id").cloned().unwrap_or(serde_json::Value::Null);
                    match msg
                        .get("method")
                        .and_then(|m| m.as_str())
                        .unwrap_or_default()
                    {
                        crate::commands::DISCOVER => match reply {
                            DiscoverReply::MethodNotFound => {
                                let body = serde_json::json!({
                                    "jsonrpc": "2.0",
                                    "id": id,
                                    "error": { "code": -32601, "message": "Method not found" }
                                })
                                .to_string();
                                write_response(
                                    &mut stream,
                                    "200 OK",
                                    "Content-Type: application/json\r\n",
                                    &body,
                                )
                                .await;
                            }
                            DiscoverReply::Html400 => {
                                write_response(
                                    &mut stream,
                                    "400 Bad Request",
                                    "Content-Type: text/html\r\n",
                                    "<html><body>Bad Request</body></html>",
                                )
                                .await;
                            }
                            DiscoverReply::Unavailable503 => {
                                write_response(
                                    &mut stream,
                                    "503 Service Unavailable",
                                    "Content-Type: text/html\r\n",
                                    "<html><body>upstream down</body></html>",
                                )
                                .await;
                            }
                            DiscoverReply::Unauthorized401 => {
                                write_response(
                                    &mut stream,
                                    "401 Unauthorized",
                                    "Content-Type: text/html\r\nWWW-Authenticate: Bearer\r\n",
                                    "<html><body>Unauthorized</body></html>",
                                )
                                .await;
                            }
                            DiscoverReply::UnsupportedVersion => {
                                let body = rpc_result(
                                    &id,
                                    serde_json::json!({
                                        "supportedVersions": ["2099-01-01"],
                                        "capabilities": { "tools": {} }
                                    }),
                                );
                                write_response(
                                    &mut stream,
                                    "200 OK",
                                    "Content-Type: application/json\r\n",
                                    &body,
                                )
                                .await;
                            }
                        },
                        crate::commands::INIT => {
                            let body = rpc_result(
                                &id,
                                serde_json::json!({
                                    "protocolVersion": "2025-11-25",
                                    "capabilities": { "tools": {} },
                                    "serverInfo": { "name": "legacy-mock", "version": "1.0.0" }
                                }),
                            );
                            let headers = format!(
                                "Content-Type: application/json\r\nMcp-Session-Id: {LEGACY_SESSION_ID}\r\n"
                            );
                            write_response(&mut stream, "200 OK", &headers, &body).await;
                        }
                        crate::types::tool::commands::LIST => {
                            let body = rpc_result(&id, serde_json::json!({ "tools": [] }));
                            write_response(
                                &mut stream,
                                "200 OK",
                                "Content-Type: application/json\r\n",
                                &body,
                            )
                            .await;
                        }
                        // notifications (initialized / cancelled)
                        _ => write_response(&mut stream, "202 Accepted", "", "").await,
                    }
                }
            });
        }
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn client_falls_back_to_initialize_against_legacy_server() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let log = Arc::new(Mutex::new(Vec::<String>::new()));
        tokio::spawn(serve_legacy(
            listener,
            log.clone(),
            DiscoverReply::MethodNotFound,
        ));

        let mut client = Client::new().with_options(|opt| {
            opt.with_http(|http| http.bind(addr.to_string()))
                .with_timeout(std::time::Duration::from_secs(5))
        });

        client
            .connect()
            .await
            .expect("fallback connect must succeed");
        assert!(client.is_legacy_peer(), "peer must be marked legacy");
        assert_eq!(
            client.server_info.as_ref().map(|i| i.name.as_str()),
            Some("legacy-mock")
        );

        let tools = client
            .list_tools(None)
            .await
            .expect("tools/list must work after the fallback");
        assert!(tools.tools.is_empty());

        let log = log
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let discover = log
            .iter()
            .find(|r| r.contains("server/discover"))
            .expect("discover must be attempted first");
        assert!(
            discover
                .to_ascii_lowercase()
                .contains("mcp-protocol-version"),
            "the 2026-07-28 attempt carries the protocol-version header"
        );

        let init = log
            .iter()
            .find(|r| r.contains("\"method\":\"initialize\""))
            .expect("initialize must be sent after the rejection");
        assert!(
            init.contains("2025-11-25"),
            "the fallback negotiates the newest legacy version"
        );

        let list = log
            .iter()
            .find(|r| r.contains(crate::types::tool::commands::LIST))
            .expect("tools/list recorded");
        let list_lower = list.to_ascii_lowercase();
        assert!(
            !list_lower.contains("mcp-protocol-version"),
            "legacy peers must not receive the 2026-07-28 protocol-version header"
        );
        assert!(
            !list_lower.contains("mcp-method:"),
            "legacy peers must not receive 2026-07-28 routing headers"
        );
        assert!(
            list_lower.contains(&format!("mcp-session-id: {LEGACY_SESSION_ID}")),
            "the captured session id must ride every request"
        );
    }

    /// A legacy server that rejects `server/discover` with a plain
    /// non-JSON-RPC 4xx page (no JSON-RPC error at all) must also
    /// trigger the fallback: the transport completes the request with an
    /// id-bound `ParseError` response instead of a bare channel error.
    #[tokio::test(flavor = "multi_thread")]
    async fn client_falls_back_when_discover_gets_a_non_json_4xx() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let log = Arc::new(Mutex::new(Vec::<String>::new()));
        tokio::spawn(serve_legacy(listener, log.clone(), DiscoverReply::Html400));

        let mut client = Client::new().with_options(|opt| {
            opt.with_http(|http| http.bind(addr.to_string()))
                .with_timeout(std::time::Duration::from_secs(5))
        });

        client
            .connect()
            .await
            .expect("fallback connect must succeed");
        assert!(client.is_legacy_peer(), "peer must be marked legacy");

        let tools = client
            .list_tools(None)
            .await
            .expect("tools/list must work after the fallback");
        assert!(tools.tools.is_empty());
    }

    /// A server that answers `server/discover` *successfully* but with a
    /// protocol version this build does not support has committed to the
    /// 2026-07-28 path -- the client must surface the real version error, not
    /// mark the peer legacy and chase `initialize` on a cancelled
    /// transport.
    #[tokio::test(flavor = "multi_thread")]
    async fn successful_discover_with_unsupported_version_does_not_fall_back() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let log = Arc::new(Mutex::new(Vec::<String>::new()));
        tokio::spawn(serve_legacy(
            listener,
            log.clone(),
            DiscoverReply::UnsupportedVersion,
        ));

        let mut client = Client::new().with_options(|opt| {
            opt.with_http(|http| http.bind(addr.to_string()))
                .with_timeout(std::time::Duration::from_secs(5))
        });

        let err = client
            .connect()
            .await
            .expect_err("an unsupported 2026-07-28 version must fail the connect");
        assert!(
            err.to_string().contains("but the client speaks"),
            "the real version error must surface, got: {err}"
        );
        assert!(
            !client.is_legacy_peer(),
            "a successful discovery must never mark the peer legacy"
        );
        assert!(
            client.handler.is_none() && client.cancellation_token.is_none(),
            "a failed negotiation must not leave the transport running"
        );

        let log = log
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert!(
            !log.iter().any(|r| r.contains("\"method\":\"initialize\"")),
            "no initialize fallback may be attempted after successful discovery"
        );
    }

    /// `notifications/roots/list_changed` is gone from MCP 2026-07-28, but a
    /// peer reached through the fallback negotiated `roots.listChanged` on the
    /// legacy protocol -- and would otherwise hold a stale root list forever.
    // Roots are deprecated under MCP 2026-07-28 -- which is exactly why the
    // fallback still owes the legacy peer this notification.
    #[allow(deprecated)]
    #[tokio::test(flavor = "multi_thread")]
    async fn roots_changes_are_pushed_to_a_fallback_peer() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let log = Arc::new(Mutex::new(Vec::<String>::new()));
        tokio::spawn(serve_legacy(
            listener,
            log.clone(),
            DiscoverReply::MethodNotFound,
        ));

        let mut client = Client::new().with_options(|opt| {
            opt.with_http(|http| http.bind(addr.to_string()))
                .with_roots(|roots| roots.with_list_changed())
                .with_timeout(std::time::Duration::from_secs(5))
        });

        client.connect().await.expect("fallback must connect");
        assert!(client.is_legacy_peer(), "the mock is a legacy server");

        client.add_root("file:///tmp/project", "Project");

        // The push is fire-and-forget through a spawned task.
        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
        loop {
            let seen = log
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .iter()
                .any(|r| r.contains("notifications/roots/list_changed"));
            if seen {
                break;
            }
            assert!(
                tokio::time::Instant::now() < deadline,
                "a legacy peer must be told its root list changed"
            );
            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        }
    }

    /// A protected 2026-07-28 endpoint replying `401` with a non-JSON body must
    /// surface the authentication failure, not be mistaken for a legacy
    /// peer -- otherwise the client silently drops the 2026-07-28 headers and
    /// retries `initialize`, masking the real cause.
    #[tokio::test(flavor = "multi_thread")]
    async fn unauthorized_discover_does_not_fall_back() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let log = Arc::new(Mutex::new(Vec::<String>::new()));
        tokio::spawn(serve_legacy(
            listener,
            log.clone(),
            DiscoverReply::Unauthorized401,
        ));

        let mut client = Client::new().with_options(|opt| {
            opt.with_http(|http| http.bind(addr.to_string()))
                .with_timeout(std::time::Duration::from_secs(5))
        });

        let err = client
            .connect()
            .await
            .expect_err("an unauthenticated connect must fail");
        assert!(
            err.to_string().contains("401"),
            "the HTTP status must be carried through, got: {err}"
        );
        assert!(
            !client.is_legacy_peer(),
            "an auth failure must never mark the peer legacy"
        );

        let log = log
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert!(
            !log.iter().any(|r| r.contains("\"method\":\"initialize\"")),
            "no initialize fallback may be attempted after an auth failure"
        );
    }

    /// An upstream outage (reverse proxy `503`, rate limit, gateway
    /// timeout) says nothing about the peer's protocol generation: the
    /// failure must surface instead of being read as "legacy" and retried
    /// as `initialize` into the very same outage.
    #[tokio::test(flavor = "multi_thread")]
    async fn upstream_failure_during_discover_does_not_fall_back() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let log = Arc::new(Mutex::new(Vec::<String>::new()));
        tokio::spawn(serve_legacy(
            listener,
            log.clone(),
            DiscoverReply::Unavailable503,
        ));

        let mut client = Client::new().with_options(|opt| {
            opt.with_http(|http| http.bind(addr.to_string()))
                .with_timeout(std::time::Duration::from_secs(5))
        });

        let err = client
            .connect()
            .await
            .expect_err("an upstream outage must fail the connect");
        assert!(
            err.to_string().contains("503"),
            "the upstream status must surface, got: {err}"
        );
        assert!(
            !client.is_legacy_peer(),
            "an upstream outage must never mark the peer legacy"
        );

        let log = log
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert!(
            !log.iter().any(|r| r.contains("\"method\":\"initialize\"")),
            "no initialize fallback may be attempted on an upstream failure"
        );
    }

    /// A `with_mcp_version` legacy override must not leak into the 2026-07-28
    /// expectation: `server/discover` still expects the 2026-07-28 version, the
    /// override only selects the fallback's negotiated legacy version.
    #[test]
    fn legacy_version_override_keeps_the_latest_expectation() {
        let client = Client::new().with_options(|opt| opt.with_mcp_version("2025-06-18"));
        assert_eq!(
            client.expected_protocol_ver(),
            crate::LATEST_PROTOCOL_VERSION
        );

        client.options.peer_mode.set_legacy();
        assert_eq!(client.expected_protocol_ver(), "2025-06-18");
    }
}

/// The other half of the "Done when": against a 2026-07-28 server the client
/// keeps using `server/discover` (no fallback).
#[cfg(all(
    test,
    feature = "http-client",
    feature = "http-server-volga",
    not(feature = "legacy-spec")
))]
mod roundtrip_tests {
    use super::*;

    #[tokio::test(flavor = "multi_thread")]
    async fn client_discovers_a_2026_07_28_server() {
        let mut app = crate::App::new()
            .with_options(|opt| opt.with_http(|http| http.bind("127.0.0.1:39817")));
        app.map_tool("echo", |name: String| async move { name });
        tokio::spawn(app.run());

        // Wait until the server socket actually accepts connections --
        // a fixed sleep is not enough on loaded CI machines.
        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(10);
        loop {
            match tokio::net::TcpStream::connect("127.0.0.1:39817").await {
                Ok(_) => break,
                Err(_) if tokio::time::Instant::now() < deadline => {
                    tokio::time::sleep(std::time::Duration::from_millis(50)).await
                }
                Err(err) => panic!("2026-07-28 server never became reachable: {err}"),
            }
        }

        let mut client = Client::new().with_options(|opt| {
            opt.with_http(|http| http.bind("127.0.0.1:39817"))
                .with_timeout(std::time::Duration::from_secs(5))
        });

        client.connect().await.expect("discover must succeed");
        assert!(!client.is_legacy_peer(), "2026-07-28 peers never fall back");

        let tools = client.list_tools(None).await.expect("tools/list");
        assert_eq!(tools.tools.len(), 1);
        assert_eq!(tools.tools[0].name, "echo");

        // `serverInfo` left `DiscoverResult`: it now rides in every result's
        // `_meta`, and the MRTR send path -- which every 2026-07-28 request
        // takes -- is what has to pick it up.
        assert!(
            client.server_info.is_some(),
            "the server identifies itself in every result's `_meta`"
        );
    }
}

/// What the client will mirror into `Mcp-Param-*` headers is decided by the
/// current listing and nothing else: a tool the server no longer designates --
/// or no longer lists at all -- must stop sending its argument in a header.
#[cfg(all(test, feature = "http-client", not(feature = "legacy-spec")))]
mod param_header_registry_tests {
    use super::*;

    fn listing(tools: serde_json::Value) -> ListToolsResult {
        serde_json::from_value(serde_json::json!({ "tools": tools })).expect("valid listing")
    }

    fn annotated(name: &str) -> serde_json::Value {
        serde_json::json!({
            "name": name,
            "inputSchema": {
                "type": "object",
                "properties": { "region": { "type": "string", "x-mcp-header": "Region" } }
            }
        })
    }

    fn plain(name: &str) -> serde_json::Value {
        serde_json::json!({
            "name": name,
            "inputSchema": { "type": "object", "properties": { "q": { "type": "string" } } }
        })
    }

    #[test]
    fn a_fresh_listing_forgets_a_tool_it_no_longer_lists() {
        let mut client = Client::new();

        let mut first = listing(serde_json::json!([annotated("search")]));
        client.register_param_headers(&mut first, true);
        assert!(client.options.param_headers.contains_key("search"));

        // The tool is gone from the refreshed listing -- a later direct
        // `call_tool("search", ..)` must not keep mirroring its argument.
        let mut second = listing(serde_json::json!([plain("other")]));
        client.register_param_headers(&mut second, true);
        assert!(client.options.param_headers.is_empty());
    }

    #[test]
    fn a_dropped_annotation_is_forgotten_on_the_same_tool() {
        let mut client = Client::new();

        let mut first = listing(serde_json::json!([annotated("search")]));
        client.register_param_headers(&mut first, true);

        let mut second = listing(serde_json::json!([plain("search")]));
        client.register_param_headers(&mut second, true);
        assert!(client.options.param_headers.is_empty());
    }

    /// Where a listing came from does not change what it binds: a batched
    /// `tools/list` registers and filters exactly as a direct one does.
    #[test]
    fn a_batched_listing_registers_and_filters() {
        let mut client = Client::new();

        let mut resp = Response::success(
            RequestId::Number(1),
            serde_json::json!({
                "tools": [
                    annotated("search"),
                    {
                        "name": "broken",
                        "inputSchema": {
                            "type": "object",
                            "properties": {
                                "p": { "type": "array", "items": { "x-mcp-header": "P" } }
                            }
                        }
                    }
                ]
            }),
        );
        client.register_batched_tools(&mut resp);

        assert!(client.options.param_headers.contains_key("search"));
        assert!(!client.options.param_headers.contains_key("broken"));

        // The caller must not be handed a tool the client refuses to call.
        let Response::Ok(ok) = &resp else {
            panic!("a successful listing")
        };
        let tools = ok.result["tools"].as_array().expect("tools array");
        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0]["name"], "search");
    }

    /// A slot that is not a listing is the caller's to interpret.
    #[test]
    fn a_non_listing_response_is_left_alone() {
        let mut client = Client::new();
        let mut resp = Response::success(
            RequestId::Number(1),
            serde_json::json!({ "content": [{ "type": "text", "text": "hi" }] }),
        );
        let before = match &resp {
            Response::Ok(ok) => ok.result.clone(),
            Response::Err(_) => panic!("a successful response"),
        };

        client.register_batched_tools(&mut resp);

        let Response::Ok(ok) = &resp else {
            panic!("a successful response")
        };
        assert_eq!(ok.result, before);
        assert!(client.options.param_headers.is_empty());
    }

    #[test]
    fn later_pages_accumulate_onto_the_traversal() {
        let mut client = Client::new();

        let mut page1 = listing(serde_json::json!([annotated("search")]));
        client.register_param_headers(&mut page1, true);

        // A tool absent from page two was not withdrawn, only listed earlier.
        let mut page2 = listing(serde_json::json!([annotated("lookup")]));
        client.register_param_headers(&mut page2, false);

        assert!(client.options.param_headers.contains_key("search"));
        assert!(client.options.param_headers.contains_key("lookup"));
    }

    #[test]
    fn an_invalid_definition_drops_the_tool_and_its_registration() {
        let mut client = Client::new();

        let mut first = listing(serde_json::json!([annotated("search")]));
        client.register_param_headers(&mut first, true);

        // Same tool, now annotated somewhere the client cannot reach.
        let mut second = listing(serde_json::json!([{
            "name": "search",
            "inputSchema": {
                "type": "object",
                "properties": {
                    "region": { "type": "array", "items": { "x-mcp-header": "Region" } }
                }
            }
        }]));
        client.register_param_headers(&mut second, true);

        assert!(second.tools.is_empty(), "a malformed tool is not callable");
        assert!(client.options.param_headers.is_empty());
    }

    fn call(name: &str) -> Request {
        Request::new(
            Some(RequestId::Number(1)),
            crate::types::tool::commands::CALL,
            Some(serde_json::json!({ "name": name, "arguments": {} })),
        )
    }

    /// Hiding the name from the listing is not enough on its own: a caller
    /// holding it from anywhere else would otherwise reach the tool with none
    /// of the headers its declaration asked for.
    #[test]
    fn a_rejected_tool_cannot_be_called_by_name() {
        let mut client = Client::new();

        let mut listed = listing(serde_json::json!([
            annotated("search"),
            {
                "name": "broken",
                "inputSchema": {
                    "type": "object",
                    "properties": { "p": { "type": "array", "items": { "x-mcp-header": "P" } } }
                }
            }
        ]));
        client.register_param_headers(&mut listed, true);

        let err = client
            .blocked_tool_error(&call("broken"))
            .expect("a rejected tool is refused");
        assert_eq!(err.code, ErrorCode::InvalidParams);
        assert!(client.blocked_tool_error(&call("search")).is_none());
        // Only `tools/call` names a tool.
        assert!(
            client
                .blocked_tool_error(&Request::new(
                    Some(RequestId::Number(1)),
                    crate::types::tool::commands::LIST,
                    Some(serde_json::json!({ "name": "broken" })),
                ))
                .is_none()
        );
    }

    /// The block follows the listing: a definition the server fixed -- or
    /// withdrew altogether -- is no longer the one being refused.
    #[test]
    fn a_fresh_listing_lifts_the_block() {
        let mut client = Client::new();

        let mut first = listing(serde_json::json!([{
            "name": "broken",
            "inputSchema": {
                "type": "object",
                "properties": { "p": { "type": "array", "items": { "x-mcp-header": "P" } } }
            }
        }]));
        client.register_param_headers(&mut first, true);
        assert!(client.blocked_tool_error(&call("broken")).is_some());

        let mut fixed = listing(serde_json::json!([annotated("broken")]));
        client.register_param_headers(&mut fixed, true);
        assert!(client.blocked_tool_error(&call("broken")).is_none());

        client.register_param_headers(&mut first, true);
        let mut gone = listing(serde_json::json!([plain("other")]));
        client.register_param_headers(&mut gone, true);
        assert!(client.blocked_tool_error(&call("broken")).is_none());
    }
}

/// Task support in a 2026-07-28 build means one thing: the peer advertised the
/// extension *and* stayed on the 2026-07-28 protocol. Generations do not mix
/// for tasks -- run a `legacy-spec` build against a legacy server.
#[cfg(all(test, feature = "tasks", not(feature = "legacy-spec")))]
mod fallback_tasks_capability_tests {
    use super::*;
    use crate::types::ServerCapabilities;
    use serde_json::json;

    fn client_with_capabilities(caps: serde_json::Value) -> Client {
        let mut client = Client::new();
        client.server_capabilities =
            Some(serde_json::from_value::<ServerCapabilities>(caps).expect("valid capabilities"));
        client
    }

    /// The legacy top-level `tasks` field can only reach this build from a
    /// fallback peer, whose task protocol it does not speak. Reading it would
    /// promise support that ends in 2026-07-28 messages the peer cannot read.
    #[test]
    fn a_legacy_top_level_tasks_capability_is_not_support() {
        let client = client_with_capabilities(json!({
            "tools": {},
            "tasks": { "requests": { "tools": { "call": {} } } }
        }));
        assert!(!client.is_server_supports_tasks());
        assert!(!client.is_server_support_call_tool_with_tasks());
    }

    /// And a peer that advertised the 2026-07-28 extension but then negotiated
    /// the legacy protocol is no different.
    #[test]
    fn a_fallback_peer_reports_no_task_support() {
        let client = client_with_capabilities(json!({
            "tools": {},
            "extensions": {
                "io.modelcontextprotocol/tasks": { "requests": { "tools": { "call": {} } } }
            }
        }));
        assert!(client.is_server_supports_tasks());

        client.options.peer_mode.set_legacy();
        assert!(!client.is_server_supports_tasks());
        assert!(!client.is_server_support_call_tool_with_tasks());
    }

    #[test]
    fn the_extension_tasks_capability_resolves() {
        let client = client_with_capabilities(json!({
            "tools": {},
            "extensions": {
                "io.modelcontextprotocol/tasks": { "requests": { "tools": { "call": {} } } }
            }
        }));
        assert!(client.is_server_supports_tasks());
    }

    #[test]
    fn no_tasks_capability_resolves_to_none() {
        let client = client_with_capabilities(json!({ "tools": {} }));
        assert!(!client.is_server_supports_tasks());
    }
}

/// Establishing a subscription against a peer that misbehaves: answering
/// instead of acknowledging, or acknowledging more than was asked for. Driven
/// by a raw-HTTP mock, since a real neva server produces neither.
#[cfg(all(test, feature = "http-client", not(feature = "legacy-spec")))]
mod listen_rejection_tests {
    use super::*;
    use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::{TcpListener, TcpStream};

    const REASON: &str = "subscriptions are disabled here";

    async fn read_request(stream: &mut TcpStream) -> Option<(String, String)> {
        let mut buf = Vec::new();
        let mut tmp = [0u8; 2048];
        let header_end = loop {
            let n = stream.read(&mut tmp).await.ok()?;
            if n == 0 {
                return None;
            }
            buf.extend_from_slice(&tmp[..n]);
            if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
                break pos + 4;
            }
            if buf.len() > 65536 {
                return None;
            }
        };
        let head = String::from_utf8_lossy(&buf[..header_end]).to_string();
        let content_length = head
            .lines()
            .find_map(|l| {
                l.to_ascii_lowercase()
                    .strip_prefix("content-length:")
                    .map(|v| v.trim().parse::<usize>().ok())
            })
            .flatten()
            .unwrap_or(0);
        while buf.len() < header_end + content_length {
            let n = stream.read(&mut tmp).await.ok()?;
            if n == 0 {
                return None;
            }
            buf.extend_from_slice(&tmp[..n]);
        }
        let body =
            String::from_utf8_lossy(&buf[header_end..header_end + content_length]).to_string();
        Some((head, body))
    }

    async fn write_json(stream: &mut TcpStream, body: &str) {
        let resp = format!(
            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: keep-alive\r\n\r\n{body}",
            body.len()
        );
        let _ = stream.write_all(resp.as_bytes()).await;
    }

    /// Answers `server/discover` normally, then rejects `subscriptions/listen`
    /// with a JSON-RPC error and never sends an acknowledgment.
    async fn serve_rejecting(listener: TcpListener) {
        loop {
            let Ok((mut stream, _)) = listener.accept().await else {
                return;
            };
            tokio::spawn(async move {
                loop {
                    let Some((_head, body)) = read_request(&mut stream).await else {
                        return;
                    };
                    let msg: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
                    let id = msg.get("id").cloned().unwrap_or(serde_json::Value::Null);
                    let method = msg
                        .get("method")
                        .and_then(|m| m.as_str())
                        .unwrap_or_default();

                    let reply = if method == crate::commands::DISCOVER {
                        serde_json::json!({
                            "jsonrpc": "2.0", "id": id,
                            "result": {
                                "supportedVersions": [crate::LATEST_PROTOCOL_VERSION],
                                "capabilities": { "tools": { "listChanged": true } }
                            }
                        })
                    } else {
                        serde_json::json!({
                            "jsonrpc": "2.0", "id": id,
                            "error": { "code": -32600, "message": REASON }
                        })
                    };
                    write_json(&mut stream, &reply.to_string()).await;
                }
            });
        }
    }

    /// A cancelled subscription is never answered, so nothing completes its
    /// request slot -- and those slots carry no TTL, because a subscription may
    /// legitimately stay open for hours. Whoever gives up on one has to release
    /// it, or a client that opens and cancels subscriptions in a loop grows the
    /// pending queue by one entry per cycle.
    #[tokio::test(flavor = "multi_thread")]
    async fn cancelling_releases_the_request_slot() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(serve_offside_notification(listener));

        let mut client = Client::new().with_options(|opt| {
            opt.with_http(|http| http.bind(addr.to_string()))
                .with_timeout(std::time::Duration::from_secs(5))
        });
        client.connect().await.expect("connect");

        let queued = |client: &Client| client.handler.as_ref().expect("connected").pending().len();

        let idle = queued(&client);

        let mut subscription = client
            .listen(crate::types::SubscriptionFilter::new().with_tools_changed())
            .await
            .expect("listen");
        assert_eq!(
            queued(&client),
            idle + 1,
            "the live subscription holds one slot"
        );

        subscription.cancel().await.expect("cancel");
        assert_eq!(
            queued(&client),
            idle,
            "cancelling must release the subscription's slot"
        );
    }

    /// A cancel written immediately behind a listen -- which is exactly what a
    /// dropped establishment writes -- has to find the stream it names. The
    /// abort handle is registered by the connection loop rather than by the
    /// task it spawns, so the two are ordered by the wire, not by the
    /// scheduler.
    ///
    /// A single worker on purpose: it pins the interleaving this is about.
    /// Both messages are queued before the connection loop runs, so it reads
    /// the cancel on the turn right after spawning the listen, while that task
    /// has had no chance to run. (One worker rather than `current_thread`
    /// because connecting uses `block_in_place`, which the current-thread
    /// runtime refuses.)
    #[tokio::test(flavor = "multi_thread")]
    async fn a_cancel_queued_behind_a_listen_still_closes_the_stream() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let opened = Arc::new(AtomicBool::new(false));
        let hung_up = Arc::new(AtomicBool::new(false));
        tokio::spawn(serve_orphan_watch(
            listener,
            opened.clone(),
            hung_up.clone(),
        ));

        let mut client = Client::new().with_options(|opt| {
            opt.with_http(|http| http.bind(addr.to_string()))
                .with_timeout(std::time::Duration::from_secs(30))
        });
        client.connect().await.expect("connect");

        use crate::transport::Sender as _;

        let id = RequestId::Number(99);
        let mut sender = client.handler.as_ref().expect("connected").sender();

        let listen = Request::new(
            Some(id.clone()),
            crate::types::subscription::commands::LISTEN,
            Some(SubscriptionsListenRequestParams::new(
                crate::types::SubscriptionFilter::new().with_tools_changed(),
            )),
        );
        sender.send(listen.into()).await.expect("send listen");
        sender
            .send(subscription::cancelled(&id).into())
            .await
            .expect("send cancel");

        // The abort may land before the POST is even written, so what is
        // asserted is the outcome rather than one particular mechanism: the
        // peer must not be left holding this listen open. Without the fix the
        // cancel finds no handle, the request goes out, and the stream drains
        // for as long as the connection lives.
        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(3);
        while !hung_up.load(AtomicOrdering::SeqCst) && tokio::time::Instant::now() < deadline {
            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        }

        assert!(
            !opened.load(AtomicOrdering::SeqCst) || hung_up.load(AtomicOrdering::SeqCst),
            "a cancel arriving right behind its listen left the peer holding an orphaned stream"
        );
    }

    /// Answers `server/discover`, then holds any other request open and reports
    /// both that it saw one and whether the client ever hung up on it.
    async fn serve_orphan_watch(
        listener: TcpListener,
        opened: Arc<AtomicBool>,
        hung_up: Arc<AtomicBool>,
    ) {
        loop {
            let Ok((mut stream, _)) = listener.accept().await else {
                return;
            };
            let (opened, hung_up) = (opened.clone(), hung_up.clone());
            tokio::spawn(async move {
                loop {
                    let Some((_head, body)) = read_request(&mut stream).await else {
                        return;
                    };

                    let msg: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
                    let id = msg.get("id").cloned().unwrap_or(serde_json::Value::Null);
                    let method = msg
                        .get("method")
                        .and_then(|m| m.as_str())
                        .unwrap_or_default();

                    if method == crate::commands::DISCOVER {
                        let reply = serde_json::json!({
                            "jsonrpc": "2.0", "id": id,
                            "result": {
                                "supportedVersions": [crate::LATEST_PROTOCOL_VERSION],
                                "capabilities": { "tools": { "listChanged": true } }
                            }
                        });
                        write_json(&mut stream, &reply.to_string()).await;
                        continue;
                    }

                    // Anything else -- the cancel notification travels on its
                    // own `POST` -- is answered and forgotten; only the listen
                    // is the stream this test is about.
                    if method != crate::types::subscription::commands::LISTEN {
                        let _ = stream
                            .write_all(
                                b"HTTP/1.1 202 Accepted\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n",
                            )
                            .await;
                        continue;
                    }

                    opened.store(true, AtomicOrdering::SeqCst);

                    let mut probe = [0u8; 1];
                    if let Ok(Ok(0)) = tokio::time::timeout(
                        std::time::Duration::from_secs(3),
                        stream.read(&mut probe),
                    )
                    .await
                    {
                        hung_up.store(true, AtomicOrdering::SeqCst);
                    }

                    return;
                }
            });
        }
    }

    /// A caller who drops the `listen` future -- an outer `timeout`, a lost
    /// `select!` branch -- runs none of the error paths inside it, so the
    /// bookkeeping and the peer's stream would be left behind by an
    /// establishment that never returned anything to end them with.
    #[tokio::test(flavor = "multi_thread")]
    async fn dropping_the_listen_future_abandons_the_subscription() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let closed = Arc::new(AtomicBool::new(false));
        tokio::spawn(serve_stalled_listen(listener, closed.clone()));

        let mut client = Client::new().with_options(|opt| {
            opt.with_http(|http| http.bind(addr.to_string()))
                // Far longer than this test waits: the establishment must be
                // ended by the dropped future, not by `listen`'s own timeout.
                .with_timeout(std::time::Duration::from_secs(30))
        });
        client.connect().await.expect("connect");

        let queued = |client: &Client| client.handler.as_ref().expect("connected").pending().len();
        let idle = queued(&client);

        // The caller gives up on its own schedule and never sees a result.
        assert!(
            tokio::time::timeout(
                std::time::Duration::from_millis(300),
                client.listen(crate::types::SubscriptionFilter::new().with_tools_changed()),
            )
            .await
            .is_err(),
            "the peer never acknowledges, so the outer timeout must fire"
        );

        assert_eq!(
            queued(&client),
            idle,
            "a dropped establishment must release its request slot"
        );

        // And it has to reach the wire too: the peer is still holding the
        // listen request open, waiting for someone who is no longer there.
        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
        while !closed.load(AtomicOrdering::SeqCst) && tokio::time::Instant::now() < deadline {
            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        }
        assert!(
            closed.load(AtomicOrdering::SeqCst),
            "a dropped establishment must close the stream it opened"
        );
    }

    /// A cancel that never reached the wire ended nothing -- the connection
    /// did. Reporting `Cancelled` for it would tell the caller a deliberate
    /// stop happened where a connection loss did, and reconnect logic keys on
    /// exactly that difference.
    #[tokio::test(flavor = "multi_thread")]
    async fn cancelling_after_a_disconnect_reports_abrupt() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(serve_offside_notification(listener));

        let mut client = Client::new().with_options(|opt| {
            opt.with_http(|http| http.bind(addr.to_string()))
                .with_timeout(std::time::Duration::from_secs(5))
        });
        client.connect().await.expect("connect");

        let mut subscription = client
            .listen(crate::types::SubscriptionFilter::new().with_tools_changed())
            .await
            .expect("listen");

        client.disconnect().await.expect("disconnect");

        assert!(
            subscription.cancel().await.is_err(),
            "a cancel has nowhere to go once the transport is gone"
        );

        let ended = tokio::time::timeout(std::time::Duration::from_secs(2), subscription.closed())
            .await
            .expect("closed() must not hang after a failed cancel");
        assert!(
            matches!(ended, crate::client::SubscriptionEnd::Abrupt),
            "got {ended:?}"
        );
    }

    /// The same slot must come back when the handle is simply dropped.
    #[tokio::test(flavor = "multi_thread")]
    async fn dropping_the_handle_releases_the_request_slot() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(serve_offside_notification(listener));

        let mut client = Client::new().with_options(|opt| {
            opt.with_http(|http| http.bind(addr.to_string()))
                .with_timeout(std::time::Duration::from_secs(5))
        });
        client.connect().await.expect("connect");

        let queued = |client: &Client| client.handler.as_ref().expect("connected").pending().len();

        let idle = queued(&client);
        {
            let _subscription = client
                .listen(crate::types::SubscriptionFilter::new().with_tools_changed())
                .await
                .expect("listen");
            assert_eq!(queued(&client), idle + 1);
        }

        assert_eq!(
            queued(&client),
            idle,
            "dropping the handle must release the subscription's slot"
        );
    }

    /// Acknowledges exactly what was asked for, then sends a tagged
    /// notification of a category outside it.
    async fn serve_offside_notification(listener: TcpListener) {
        loop {
            let Ok((mut stream, _)) = listener.accept().await else {
                return;
            };
            tokio::spawn(async move {
                loop {
                    let Some((_head, body)) = read_request(&mut stream).await else {
                        return;
                    };
                    let msg: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
                    let id = msg.get("id").cloned().unwrap_or(serde_json::Value::Null);
                    let method = msg
                        .get("method")
                        .and_then(|m| m.as_str())
                        .unwrap_or_default();

                    if method == crate::commands::DISCOVER {
                        let reply = serde_json::json!({
                            "jsonrpc": "2.0", "id": id,
                            "result": {
                                "supportedVersions": [crate::LATEST_PROTOCOL_VERSION],
                                "capabilities": {
                                    "tools": { "listChanged": true },
                                    "prompts": { "listChanged": true }
                                }
                            }
                        });
                        write_json(&mut stream, &reply.to_string()).await;
                        continue;
                    }

                    let head = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\n\r\n";
                    let _ = stream.write_all(head.as_bytes()).await;

                    // A correct acknowledgment: tools only, exactly as asked.
                    let ack = serde_json::json!({
                        "jsonrpc": "2.0",
                        "method": "notifications/subscriptions/acknowledged",
                        "params": {
                            "notifications": { "toolsListChanged": true },
                            "_meta": { crate::types::SUBSCRIPTION_ID_KEY: id }
                        }
                    });
                    let _ = stream
                        .write_all(format!("data: {ack}\n\n").as_bytes())
                        .await;

                    // ...then a category the filter never selected.
                    let offside = serde_json::json!({
                        "jsonrpc": "2.0",
                        "method": crate::types::prompt::commands::LIST_CHANGED,
                        "params": { "_meta": { crate::types::SUBSCRIPTION_ID_KEY: id } }
                    });
                    let _ = stream
                        .write_all(format!("data: {offside}\n\n").as_bytes())
                        .await;

                    tokio::time::sleep(std::time::Duration::from_secs(30)).await;
                    return;
                }
            });
        }
    }

    /// A valid acknowledgment is a promise about the whole stream, not just its
    /// first message. A peer that keeps it and then sends an off-filter
    /// notification anyway must not reach the client's handlers -- they are
    /// global and know nothing about which subscription a message came from.
    #[tokio::test(flavor = "multi_thread")]
    async fn notifications_outside_the_acknowledged_filter_are_dropped() {
        use std::sync::atomic::AtomicUsize;

        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(serve_offside_notification(listener));

        let tools = Arc::new(AtomicUsize::new(0));
        let prompts = Arc::new(AtomicUsize::new(0));
        let (tools_seen, prompts_seen) = (tools.clone(), prompts.clone());

        let mut client = Client::new().with_options(|opt| {
            opt.with_http(|http| http.bind(addr.to_string()))
                .with_timeout(std::time::Duration::from_secs(5))
        });
        client.connect().await.expect("connect");
        client.subscribe(crate::types::tool::commands::LIST_CHANGED, move |_| {
            let seen = tools_seen.clone();
            async move {
                seen.fetch_add(1, AtomicOrdering::SeqCst);
            }
        });
        client.subscribe(crate::types::prompt::commands::LIST_CHANGED, move |_| {
            let seen = prompts_seen.clone();
            async move {
                seen.fetch_add(1, AtomicOrdering::SeqCst);
            }
        });

        let _subscription = client
            .listen(crate::types::SubscriptionFilter::new().with_tools_changed())
            .await
            .expect("listen");

        tokio::time::sleep(std::time::Duration::from_millis(300)).await;

        assert_eq!(
            prompts.load(AtomicOrdering::SeqCst),
            0,
            "a notification outside the acknowledged filter must be dropped"
        );
        assert_eq!(
            tools.load(AtomicOrdering::SeqCst),
            0,
            "and the in-filter categories are unaffected (none were sent)"
        );
    }

    /// Answers `server/discover` normally, then puts a correctly tagged,
    /// in-filter notification on the stream *ahead* of the acknowledgment.
    async fn serve_notification_before_ack(listener: TcpListener) {
        loop {
            let Ok((mut stream, _)) = listener.accept().await else {
                return;
            };
            tokio::spawn(async move {
                loop {
                    let Some((_head, body)) = read_request(&mut stream).await else {
                        return;
                    };
                    let msg: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
                    let id = msg.get("id").cloned().unwrap_or(serde_json::Value::Null);
                    let method = msg
                        .get("method")
                        .and_then(|m| m.as_str())
                        .unwrap_or_default();

                    if method == crate::commands::DISCOVER {
                        let reply = serde_json::json!({
                            "jsonrpc": "2.0", "id": id,
                            "result": {
                                "supportedVersions": [crate::LATEST_PROTOCOL_VERSION],
                                "capabilities": { "tools": { "listChanged": true } }
                            }
                        });
                        write_json(&mut stream, &reply.to_string()).await;
                        continue;
                    }

                    let head = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\n\r\n";
                    let _ = stream.write_all(head.as_bytes()).await;

                    // Correctly tagged, squarely inside what was requested --
                    // and out of order.
                    let early = serde_json::json!({
                        "jsonrpc": "2.0",
                        "method": crate::types::tool::commands::LIST_CHANGED,
                        "params": { "_meta": { crate::types::SUBSCRIPTION_ID_KEY: id } }
                    });
                    let _ = stream
                        .write_all(format!("data: {early}\n\n").as_bytes())
                        .await;

                    tokio::time::sleep(std::time::Duration::from_secs(30)).await;
                    return;
                }
            });
        }
    }

    /// The acknowledgment comes first or the subscription is not established.
    /// A peer that streams before acknowledging is streaming from a
    /// subscription `listen` goes on to report as failed -- its events must not
    /// have reached the handlers in the meantime.
    #[tokio::test(flavor = "multi_thread")]
    async fn notifications_before_the_acknowledgment_are_dropped() {
        use std::sync::atomic::AtomicUsize;

        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(serve_notification_before_ack(listener));

        let tools = Arc::new(AtomicUsize::new(0));
        let seen = tools.clone();

        let mut client = Client::new().with_options(|opt| {
            opt.with_http(|http| http.bind(addr.to_string()))
                // Bounded, because the peer never acknowledges and
                // establishment has to end by timing out -- but not tight: the
                // same budget covers the `connect` above, which shares this
                // client, and a loaded machine makes a short one flake.
                .with_timeout(std::time::Duration::from_secs(5))
        });
        client.connect().await.expect("connect");
        client.subscribe(crate::types::tool::commands::LIST_CHANGED, move |_| {
            let seen = seen.clone();
            async move {
                seen.fetch_add(1, AtomicOrdering::SeqCst);
            }
        });

        client
            .listen(crate::types::SubscriptionFilter::new().with_tools_changed())
            .await
            .expect_err("a peer that never acknowledges must not establish");

        assert_eq!(
            tools.load(AtomicOrdering::SeqCst),
            0,
            "a notification sent before the acknowledgment must be dropped"
        );
    }

    /// Answers `server/discover` normally, acknowledges the subscription, then
    /// pushes a subscribable notification with no subscription id on it.
    async fn serve_untagged_notification(listener: TcpListener) {
        loop {
            let Ok((mut stream, _)) = listener.accept().await else {
                return;
            };
            tokio::spawn(async move {
                loop {
                    let Some((_head, body)) = read_request(&mut stream).await else {
                        return;
                    };
                    let msg: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
                    let id = msg.get("id").cloned().unwrap_or(serde_json::Value::Null);
                    let method = msg
                        .get("method")
                        .and_then(|m| m.as_str())
                        .unwrap_or_default();

                    if method == crate::commands::DISCOVER {
                        let reply = serde_json::json!({
                            "jsonrpc": "2.0", "id": id,
                            "result": {
                                "supportedVersions": [crate::LATEST_PROTOCOL_VERSION],
                                "capabilities": { "tools": { "listChanged": true } }
                            }
                        });
                        write_json(&mut stream, &reply.to_string()).await;
                        continue;
                    }

                    let head = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\n\r\n";
                    let _ = stream.write_all(head.as_bytes()).await;

                    let ack = serde_json::json!({
                        "jsonrpc": "2.0",
                        "method": "notifications/subscriptions/acknowledged",
                        "params": {
                            "notifications": { "toolsListChanged": true },
                            "_meta": { crate::types::SUBSCRIPTION_ID_KEY: id }
                        }
                    });
                    let _ = stream
                        .write_all(format!("data: {ack}\n\n").as_bytes())
                        .await;

                    // In the accepted filter, but with nothing tying it to the
                    // subscription that accepted it.
                    let untagged = serde_json::json!({
                        "jsonrpc": "2.0",
                        "method": crate::types::tool::commands::LIST_CHANGED
                    });
                    let _ = stream
                        .write_all(format!("data: {untagged}\n\n").as_bytes())
                        .await;

                    tokio::time::sleep(std::time::Duration::from_secs(30)).await;
                    return;
                }
            });
        }
    }

    /// Under MCP 2026-07-28 a subscribable notification travels on a
    /// subscription and nowhere else. One that arrives without a subscription
    /// id has nothing to check it against, so it cannot be admitted just
    /// because the client happens to have asked for that category somewhere.
    #[tokio::test(flavor = "multi_thread")]
    async fn untagged_subscribable_notifications_are_dropped() {
        use std::sync::atomic::AtomicUsize;

        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(serve_untagged_notification(listener));

        let tools = Arc::new(AtomicUsize::new(0));
        let seen = tools.clone();

        let mut client = Client::new().with_options(|opt| {
            opt.with_http(|http| http.bind(addr.to_string()))
                .with_timeout(std::time::Duration::from_secs(5))
        });
        client.connect().await.expect("connect");
        client.subscribe(crate::types::tool::commands::LIST_CHANGED, move |_| {
            let seen = seen.clone();
            async move {
                seen.fetch_add(1, AtomicOrdering::SeqCst);
            }
        });

        let _subscription = client
            .listen(crate::types::SubscriptionFilter::new().with_tools_changed())
            .await
            .expect("listen");

        tokio::time::sleep(std::time::Duration::from_millis(300)).await;

        assert_eq!(
            tools.load(AtomicOrdering::SeqCst),
            0,
            "a subscription-only notification with no subscription id must be dropped"
        );
    }

    /// A transport that dies while `listen` is still waiting for its
    /// acknowledgment is a lost connection, not a peer that would not
    /// acknowledge -- and callers act on those differently.
    #[tokio::test(flavor = "multi_thread")]
    async fn listen_reports_a_lost_transport_as_a_connection_error() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(serve_stalled_listen(
            listener,
            Arc::new(AtomicBool::new(false)),
        ));

        let mut client = Client::new().with_options(|opt| {
            opt.with_http(|http| http.bind(addr.to_string()))
                // Long enough that a timeout cannot be what ends the wait.
                .with_timeout(std::time::Duration::from_secs(30))
        });
        client.connect().await.expect("connect");

        let token = client.handler.as_ref().expect("connected").cancellation();
        tokio::spawn(async move {
            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
            token.cancel();
        });

        let err = tokio::time::timeout(
            std::time::Duration::from_secs(5),
            client.listen(crate::types::SubscriptionFilter::new().with_tools_changed()),
        )
        .await
        .expect("a dead transport must not be waited out")
        .expect_err("a dead transport cannot establish a subscription");

        assert_eq!(err.code, ErrorCode::InternalError, "got {err:?}");
    }

    /// Answers `server/discover` normally, then delivers the whole
    /// subscription -- acknowledgment, an in-filter notification and an
    /// off-filter one -- inside a single JSON-RPC batch.
    async fn serve_batched_frames(listener: TcpListener) {
        loop {
            let Ok((mut stream, _)) = listener.accept().await else {
                return;
            };

            tokio::spawn(async move {
                loop {
                    let Some((_head, body)) = read_request(&mut stream).await else {
                        return;
                    };

                    let msg: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
                    let id = msg.get("id").cloned().unwrap_or(serde_json::Value::Null);
                    let method = msg
                        .get("method")
                        .and_then(|m| m.as_str())
                        .unwrap_or_default();

                    if method == crate::commands::DISCOVER {
                        let reply = serde_json::json!({
                            "jsonrpc": "2.0", "id": id,
                            "result": {
                                "supportedVersions": [crate::LATEST_PROTOCOL_VERSION],
                                "capabilities": {
                                    "tools": { "listChanged": true },
                                    "prompts": { "listChanged": true }
                                }
                            }
                        });

                        write_json(&mut stream, &reply.to_string()).await;
                        continue;
                    }

                    let head = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\n\r\n";
                    let _ = stream.write_all(head.as_bytes()).await;

                    let batch = serde_json::json!([
                        {
                            "jsonrpc": "2.0",
                            "method": "notifications/subscriptions/acknowledged",
                            "params": {
                                "notifications": { "toolsListChanged": true },
                                "_meta": { crate::types::SUBSCRIPTION_ID_KEY: id }
                            }
                        },
                        {
                            "jsonrpc": "2.0",
                            "method": crate::types::tool::commands::LIST_CHANGED,
                            "params": { "_meta": { crate::types::SUBSCRIPTION_ID_KEY: id } }
                        },
                        {
                            "jsonrpc": "2.0",
                            "method": crate::types::prompt::commands::LIST_CHANGED,
                            "params": { "_meta": { crate::types::SUBSCRIPTION_ID_KEY: id } }
                        }
                    ]);
                    let _ = stream
                        .write_all(format!("data: {batch}\n\n").as_bytes())
                        .await;

                    tokio::time::sleep(std::time::Duration::from_secs(30)).await;
                    return;
                }
            });
        }
    }

    /// Batching is a framing choice of the peer's. An acknowledgment sent that
    /// way still has to establish the subscription, and a tagged notification
    /// sent that way still has to face the filter it was accepted under.
    #[tokio::test(flavor = "multi_thread")]
    async fn batched_subscription_frames_go_through_the_same_gate() {
        use std::sync::atomic::AtomicUsize;

        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(serve_batched_frames(listener));

        let tools = Arc::new(AtomicUsize::new(0));
        let prompts = Arc::new(AtomicUsize::new(0));
        let (tools_seen, prompts_seen) = (tools.clone(), prompts.clone());

        let mut client = Client::new().with_options(|opt| {
            opt.with_http(|http| http.bind(addr.to_string()))
                .with_timeout(std::time::Duration::from_secs(30))
        });
        client.connect().await.expect("connect");
        client.subscribe(crate::types::tool::commands::LIST_CHANGED, move |_| {
            let seen = tools_seen.clone();
            async move {
                seen.fetch_add(1, AtomicOrdering::SeqCst);
            }
        });
        client.subscribe(crate::types::prompt::commands::LIST_CHANGED, move |_| {
            let seen = prompts_seen.clone();
            async move {
                seen.fetch_add(1, AtomicOrdering::SeqCst);
            }
        });

        // A batched acknowledgment has to resolve `listen`, not leave it
        // waiting out the establishment timeout.
        let _subscription = client
            .listen(crate::types::SubscriptionFilter::new().with_tools_changed())
            .await
            .expect("a batched acknowledgment must establish the subscription");

        tokio::time::sleep(std::time::Duration::from_millis(300)).await;

        assert_eq!(
            tools.load(AtomicOrdering::SeqCst),
            1,
            "an in-filter batched notification must be delivered"
        );
        assert_eq!(
            prompts.load(AtomicOrdering::SeqCst),
            0,
            "an off-filter batched notification must be dropped"
        );
    }

    /// Answers `server/discover` normally, then acknowledges the subscription
    /// with a *broader* filter than the client asked for.
    async fn serve_overbroad_ack(listener: TcpListener) {
        loop {
            let Ok((mut stream, _)) = listener.accept().await else {
                return;
            };
            tokio::spawn(async move {
                loop {
                    let Some((_head, body)) = read_request(&mut stream).await else {
                        return;
                    };
                    let msg: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
                    let id = msg.get("id").cloned().unwrap_or(serde_json::Value::Null);
                    let method = msg
                        .get("method")
                        .and_then(|m| m.as_str())
                        .unwrap_or_default();

                    if method == crate::commands::DISCOVER {
                        let reply = serde_json::json!({
                            "jsonrpc": "2.0", "id": id,
                            "result": {
                                "supportedVersions": [crate::LATEST_PROTOCOL_VERSION],
                                "capabilities": {
                                    "tools": { "listChanged": true },
                                    "prompts": { "listChanged": true }
                                }
                            }
                        });
                        write_json(&mut stream, &reply.to_string()).await;
                        continue;
                    }

                    // The client asked for tools only; claim prompts as well.
                    let ack = serde_json::json!({
                        "jsonrpc": "2.0",
                        "method": "notifications/subscriptions/acknowledged",
                        "params": {
                            "notifications": {
                                "toolsListChanged": true,
                                "promptsListChanged": true
                            },
                            "_meta": { crate::types::SUBSCRIPTION_ID_KEY: id }
                        }
                    });
                    let head = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\n\r\n";
                    let _ = stream.write_all(head.as_bytes()).await;
                    let _ = stream
                        .write_all(format!("data: {ack}\n\n").as_bytes())
                        .await;

                    // Straight behind it, a notification squarely inside what
                    // the client *did* ask for. The acknowledgment is on its way
                    // to being rejected, so this must not reach the handlers
                    // either -- intersecting the filter alone would let it.
                    let in_filter = serde_json::json!({
                        "jsonrpc": "2.0",
                        "method": crate::types::tool::commands::LIST_CHANGED,
                        "params": { "_meta": { crate::types::SUBSCRIPTION_ID_KEY: id } }
                    });
                    let _ = stream
                        .write_all(format!("data: {in_filter}\n\n").as_bytes())
                        .await;

                    // Hold the stream open, the way a real subscription would.
                    tokio::time::sleep(std::time::Duration::from_secs(30)).await;
                    return;
                }
            });
        }
    }

    /// An acknowledgment may narrow the requested filter -- that is what it is
    /// for -- but never widen it. Notifications reach the client's global
    /// handlers with no per-subscription filtering, so accepting an overbroad
    /// acknowledgment would deliver events this call never asked for.
    #[tokio::test(flavor = "multi_thread")]
    async fn listen_rejects_an_overbroad_acknowledgment() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(serve_overbroad_ack(listener));

        let mut client = Client::new().with_options(|opt| {
            opt.with_http(|http| http.bind(addr.to_string()))
                .with_timeout(std::time::Duration::from_secs(5))
        });
        client.connect().await.expect("connect");

        let tools = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let seen = tools.clone();
        client.subscribe(crate::types::tool::commands::LIST_CHANGED, move |_| {
            let seen = seen.clone();
            async move {
                seen.fetch_add(1, AtomicOrdering::SeqCst);
            }
        });

        let err = client
            .listen(crate::types::SubscriptionFilter::new().with_tools_changed())
            .await
            .expect_err("an overbroad acknowledgment must be rejected");

        let reported = format!("{err:?}");
        assert!(
            reported.contains("broader"),
            "the rejection must name the cause, got: {reported}"
        );

        // Nothing may have been delivered on the strength of an acknowledgment
        // this call refuses -- not even a category it did ask for.
        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
        assert_eq!(
            tools.load(AtomicOrdering::SeqCst),
            0,
            "a subscription `listen` rejects must deliver nothing"
        );
    }

    /// Answers `server/discover` normally, then accepts the listen `POST` and
    /// never replies at all -- headers included. Records whether that
    /// connection was closed by the peer.
    async fn serve_stalled_listen(listener: TcpListener, closed: Arc<AtomicBool>) {
        loop {
            let Ok((mut stream, _)) = listener.accept().await else {
                return;
            };
            let closed = closed.clone();
            tokio::spawn(async move {
                loop {
                    let Some((_head, body)) = read_request(&mut stream).await else {
                        return;
                    };
                    let msg: serde_json::Value = serde_json::from_str(&body).unwrap_or_default();
                    let id = msg.get("id").cloned().unwrap_or(serde_json::Value::Null);
                    let method = msg
                        .get("method")
                        .and_then(|m| m.as_str())
                        .unwrap_or_default();

                    if method == crate::commands::DISCOVER {
                        let reply = serde_json::json!({
                            "jsonrpc": "2.0", "id": id,
                            "result": {
                                "supportedVersions": [crate::LATEST_PROTOCOL_VERSION],
                                "capabilities": { "tools": { "listChanged": true } }
                            }
                        });
                        write_json(&mut stream, &reply.to_string()).await;
                        continue;
                    }

                    // Sit on the request without sending so much as a status
                    // line, and watch for the client hanging up.
                    let mut probe = [0u8; 1];
                    let hung_up = tokio::time::timeout(
                        std::time::Duration::from_secs(10),
                        stream.read(&mut probe),
                    )
                    .await
                    .is_ok_and(|read| matches!(read, Ok(0)));
                    if hung_up {
                        closed.store(true, AtomicOrdering::SeqCst);
                    }
                    return;
                }
            });
        }
    }

    /// A subscription can be cancelled while the peer is still sitting on the
    /// response headers -- establishment timing out is exactly that. The abort
    /// handle has to exist by then, or the cancel finds nothing to close and the
    /// task starts draining an orphaned stream once the headers finally arrive.
    #[tokio::test(flavor = "multi_thread")]
    async fn listen_closes_a_stalled_request_on_timeout() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let closed = Arc::new(AtomicBool::new(false));
        tokio::spawn(serve_stalled_listen(listener, closed.clone()));

        let mut client = Client::new().with_options(|opt| {
            opt.with_http(|http| http.bind(addr.to_string()))
                // Bounded, because establishment has to give up on its own --
                // but not tight: this budget covers the `connect` before the
                // subscription as well, and a loaded machine makes a short one
                // flake. The assertion below waits longer still.
                .with_timeout(std::time::Duration::from_secs(5))
        });
        client.connect().await.expect("connect");

        client
            .listen(crate::types::SubscriptionFilter::new().with_tools_changed())
            .await
            .expect_err("a stalled subscription must not establish");

        // Giving up has to reach the wire: the peer sees the connection go away
        // instead of holding a request nobody is waiting for.
        let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);
        while !closed.load(AtomicOrdering::SeqCst) && tokio::time::Instant::now() < deadline {
            tokio::time::sleep(std::time::Duration::from_millis(25)).await;
        }
        assert!(
            closed.load(AtomicOrdering::SeqCst),
            "abandoning an unacknowledged subscription must close its request"
        );
    }

    /// A rejected `subscriptions/listen` must surface the server's own error
    /// immediately. Waiting only on the acknowledgment would sit out the full
    /// request timeout and report *that* instead -- the peer's reason lost, and
    /// the caller blocked for no reason.
    #[tokio::test(flavor = "multi_thread")]
    async fn listen_surfaces_an_immediate_rejection() {
        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(serve_rejecting(listener));

        let mut client = Client::new().with_options(|opt| {
            opt.with_http(|http| http.bind(addr.to_string()))
                // Generous on purpose: a timeout would be unmistakable below.
                .with_timeout(std::time::Duration::from_secs(30))
        });
        client.connect().await.expect("connect");

        let started = tokio::time::Instant::now();
        let err = client
            .listen(crate::types::SubscriptionFilter::new().with_tools_changed())
            .await
            .expect_err("a rejected subscription must fail");

        let reported = format!("{err:?}");
        assert!(
            reported.contains(REASON),
            "the server's own error must survive, got: {reported}"
        );
        assert!(
            started.elapsed() < std::time::Duration::from_secs(5),
            "the rejection must not wait out the request timeout"
        );
    }
}