fastmcp-rust 0.7.0

Asupersync-based MCP framework for Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
//! E2E Client-Server Protocol Integration Tests (bd-22q)
//!
//! Comprehensive tests for full client-server protocol flows using
//! MemoryTransport with real handler implementations. No mocks.
//!
//! Coverage:
//! - Initialize handshake
//! - Tool listing and invocation
//! - Resource listing and reading
//! - Prompt listing and retrieval
//! - Error handling (unknown tool, invalid params, method not found)
//! - JSON-RPC 2.0 compliance

use std::collections::HashMap;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
use std::thread::JoinHandle;
#[cfg(unix)]
use std::time::{Duration, Instant};

use fastmcp_protocol::{LegacyContent, LegacyResourceContent};
use fastmcp_rust::testing::prelude::*;
use fastmcp_rust::{
    AuthContext, CacheScope, CacheTtl, ContentBlock, EmbeddedResourceContents, McpContext,
    McpErrorCode, McpResult, PromptMessage, Role, StaticTokenVerifier, TokenAuthProvider,
};
#[cfg(unix)]
use fastmcp_rust::{
    Client, ClientCapabilities, Cx, ListPromptsParams, ListResourceTemplatesParams,
    ListResourcesParams, ListToolsParams, ProtocolEra, ProtocolPolicy, RequestTimeoutPolicy, auto,
    legacy_2024, modern,
};
use serde_json::json;

// ============================================================================
// Test handler implementations
// ============================================================================

/// A simple greeting tool handler.
#[fastmcp_rust::tool(
    name = "greeting",
    description = "Returns a greeting for the given name",
    version = "1.0.0",
    tags = ["greeting"],
    annotations(read_only)
)]
fn greeting_tool_handler(name: String) -> String {
    format!("Hello, {name}!")
}

/// A calculator tool handler.
#[fastmcp_rust::tool(name = "calculator", description = "Performs arithmetic operations")]
fn calculator_tool_handler(a: f64, b: f64, operation: String) -> McpResult<String> {
    let result = match operation.as_str() {
        "add" => a + b,
        "subtract" => a - b,
        "multiply" => a * b,
        "divide" => {
            if b == 0.0 {
                return Err(McpError::tool_error("Division by zero"));
            }
            a / b
        }
        _ => {
            return Err(McpError::tool_error(format!(
                "Unknown operation: {operation}"
            )));
        }
    };

    Ok(result.to_string())
}

/// An error-producing tool handler.
#[fastmcp_rust::tool(name = "error_tool", description = "Always returns an error")]
fn error_tool_handler() -> McpResult<String> {
    Err(McpError::tool_error("Intentional error for testing"))
}

/// A tool that returns the current request authentication context as JSON text.
#[fastmcp_rust::tool(
    name = "auth_info",
    description = "Returns auth context for E2E verification",
    tags = ["auth", "testing"],
    annotations(read_only)
)]
fn auth_info_tool_handler(ctx: &McpContext) -> String {
    let auth = ctx.auth().unwrap_or_else(AuthContext::anonymous);

    let payload = json!({
        "subject": auth.subject,
        "scopes": auth.scopes,
    });

    payload.to_string()
}

/// A text file resource handler.
#[fastmcp_rust::resource(
    uri = "file:///test/sample.txt",
    name = "sample.txt",
    description = "A sample text file",
    mime_type = "text/plain",
    version = "1.0.0",
    tags = ["text"]
)]
fn text_file_resource_handler() -> String {
    "Hello, World!\nThis is sample text content.".to_string()
}

/// A JSON config resource handler.
#[fastmcp_rust::resource(
    uri = "file:///config/settings.json",
    name = "settings.json",
    description = "Application configuration",
    mime_type = "application/json"
)]
fn json_config_resource_handler() -> String {
    json!({
        "version": "1.0.0",
        "debug": false,
        "max_connections": 100
    })
    .to_string()
}

/// A greeting prompt handler.
#[fastmcp_rust::prompt(
    name = "greeting",
    description = "Generate a greeting",
    version = "1.0.0",
    tags = ["greeting"]
)]
fn greeting_prompt_handler(name: String) -> Vec<PromptMessage> {
    vec![PromptMessage {
        role: Role::User,
        content: Content::Text {
            text: format!("Please greet {name} warmly."),
        },
    }]
}

/// A code review prompt handler with multiple arguments.
#[fastmcp_rust::prompt(name = "code_review", description = "Review code for quality")]
fn code_review_prompt_handler(code: String, language: String) -> Vec<PromptMessage> {
    vec![
        PromptMessage {
            role: Role::User,
            content: Content::Text {
                text: format!("Review this {language} code:\n```{language}\n{code}\n```"),
            },
        },
        PromptMessage {
            role: Role::Assistant,
            content: Content::Text {
                text: "I'll review this code for quality, bugs, and improvements.".to_string(),
            },
        },
    ]
}

// ============================================================================
// Helper: build server + client pair
// ============================================================================

struct TestHarness {
    client: Option<TestClient>,
    server_thread: Option<JoinHandle<()>>,
}

impl TestHarness {
    fn new(client: TestClient, server_thread: JoinHandle<()>) -> Self {
        Self {
            client: Some(client),
            server_thread: Some(server_thread),
        }
    }
}

impl Deref for TestHarness {
    type Target = TestClient;

    fn deref(&self) -> &Self::Target {
        self.client.as_ref().expect("client missing")
    }
}

impl DerefMut for TestHarness {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.client.as_mut().expect("client missing")
    }
}

impl Drop for TestHarness {
    fn drop(&mut self) {
        // Drop the client first so the transport closes and the server thread can exit.
        self.client.take();

        if let Some(handle) = self.server_thread.take() {
            // If the server thread panicked, fail the test (assert! is acceptable in test-only Drop).
            assert!(handle.join().is_ok(), "server thread panicked");
        }
    }
}

fn spawn_thread(f: impl FnOnce() + Send + 'static) -> JoinHandle<()> {
    std::thread::spawn(f)
}

/// Spawns a server with all test handlers and returns a connected TestClient.
///
/// The server runs in a background thread and is cleaned up when the
/// transport is closed.
fn setup_test_server_and_client() -> TestHarness {
    let (builder, client_transport, server_transport) = TestServer::builder()
        .with_name("e2e-test-server")
        .with_version("1.0.0")
        .build_server_builder();

    let server = builder
        .tool(GreetingToolHandler)
        .tool(CalculatorToolHandler)
        .tool(ErrorToolHandler)
        .resource(TextFileResourceHandlerResource)
        .resource(JsonConfigResourceHandlerResource)
        .prompt(GreetingPromptHandlerPrompt)
        .prompt(CodeReviewPromptHandlerPrompt)
        .build();

    // Run server in background thread
    let handle = spawn_thread(move || {
        server.run_transport(server_transport);
    });

    TestHarness::new(TestClient::new(client_transport), handle)
}

fn setup_auth_server_and_client<P: fastmcp_rust::AuthProvider + 'static>(
    provider: P,
    server_name: &str,
) -> TestHarness {
    let (builder, client_transport, server_transport) = TestServer::builder()
        .with_name(server_name)
        .with_version("1.0.0")
        .build_server_builder();

    let server = builder
        .tool(GreetingToolHandler)
        .tool(AuthInfoToolHandler)
        .auth_provider(provider)
        .build();

    let handle = spawn_thread(move || server.run_transport(server_transport));

    TestHarness::new(TestClient::new(client_transport), handle)
}

// ============================================================================
// Initialize handshake tests
// ============================================================================

#[test]
fn e2e_initialize_handshake() {
    let mut client = setup_test_server_and_client();
    let result = client.initialize();
    assert!(result.is_ok(), "Initialization failed: {result:?}");

    let init_result = result.unwrap();
    assert_eq!(init_result.server_info.name, "e2e-test-server");
    assert_eq!(init_result.server_info.version, "1.0.0");
    assert_eq!(init_result.protocol_version, fastmcp_rust::PROTOCOL_VERSION);
}

#[test]
fn e2e_initialize_reports_capabilities() {
    let mut client = setup_test_server_and_client();
    let init_result = client.initialize().unwrap();

    // Server registered tools, resources, and prompts, so all should be Some
    assert!(
        init_result.capabilities.tools.is_some(),
        "Server should advertise tool capabilities"
    );
    assert!(
        init_result.capabilities.resources.is_some(),
        "Server should advertise resource capabilities"
    );
    assert!(
        init_result.capabilities.prompts.is_some(),
        "Server should advertise prompt capabilities"
    );
}

#[test]
fn e2e_initialize_stores_server_info() {
    let mut client = setup_test_server_and_client();
    assert!(!client.is_initialized());
    assert!(client.server_info().is_none());

    client.initialize().unwrap();

    assert!(client.is_initialized());
    assert_eq!(client.server_info().unwrap().name, "e2e-test-server");
    assert!(client.server_capabilities().is_some());
    assert_eq!(
        client.protocol_version().unwrap(),
        fastmcp_rust::PROTOCOL_VERSION
    );
}

// ============================================================================
// Authentication flow tests (bd-21q)
// ============================================================================

#[test]
fn e2e_auth_static_token_flow_allows_and_denies() {
    let verifier = StaticTokenVerifier::new([("good-token", AuthContext::with_subject("user-1"))])
        .expect("valid verifier configuration")
        .with_allowed_schemes(["Bearer"])
        .expect("valid scheme configuration");
    let provider = TokenAuthProvider::new(verifier);

    let mut client = setup_auth_server_and_client(provider, "e2e-auth-static");
    client.initialize().unwrap();

    let mut trace = TestTrace::new("e2e-auth-static-token");

    // Unauthorized tools/list.
    let params = json!({ "cursor": null });
    let corr = trace.log_request("tools/list", Some(&params));
    let err = client.send_request_json("tools/list", params).unwrap_err();
    trace.log_response(
        &corr,
        None::<&serde_json::Value>,
        Some(&json!({"error": err.message})),
    );
    assert_eq!(err.code, McpErrorCode::ResourceForbidden);

    // Invalid token should be rejected.
    let params = json!({ "cursor": null, "auth": "Bearer bad-token" });
    let corr = trace.log_request("tools/list", Some(&params));
    let err = client.send_request_json("tools/list", params).unwrap_err();
    trace.log_response(
        &corr,
        None::<&serde_json::Value>,
        Some(&json!({"error": err.message})),
    );
    assert_eq!(err.code, McpErrorCode::ResourceForbidden);

    // Authorized tools/list.
    let params = json!({ "cursor": null, "auth": "Bearer good-token" });
    let corr = trace.log_request("tools/list", Some(&params));
    let value = client.send_request_json("tools/list", params).unwrap();
    trace.log_response(&corr, Some(&value), None::<&serde_json::Value>);

    let tools: fastmcp_protocol::ListToolsResult = serde_json::from_value(value).unwrap();
    assert!(
        tools.tools.iter().any(|t| t.name == "greeting"),
        "expected greeting tool to be listed"
    );

    // Authorized tools/call.
    let params = json!({
        "name": "greeting",
        "arguments": { "name": "Ada" },
        "auth": "Bearer good-token",
    });
    let corr = trace.log_request("tools/call", Some(&params));
    let value = client.send_request_json("tools/call", params).unwrap();
    trace.log_response(&corr, Some(&value), None::<&serde_json::Value>);

    let call: fastmcp_protocol::CallToolResult = serde_json::from_value(value).unwrap();
    assert!(!call.is_error);
    assert!(
        matches!(call.content.first(), Some(LegacyContent::Text { .. })),
        "expected text content"
    );
    let Some(LegacyContent::Text { text, .. }) = call.content.first() else {
        return;
    };
    assert_eq!(text, "Hello, Ada!");

    // Verify handlers receive verified identity facts, never the raw token.
    let params = json!({
        "name": "auth_info",
        "arguments": {},
        "auth": "Bearer good-token",
    });
    let corr = trace.log_request("tools/call(auth_info)", Some(&params));
    let value = client.send_request_json("tools/call", params).unwrap();
    trace.log_response(&corr, Some(&value), None::<&serde_json::Value>);

    let call: fastmcp_protocol::CallToolResult = serde_json::from_value(value).unwrap();
    assert!(
        matches!(call.content.first(), Some(LegacyContent::Text { .. })),
        "expected text content"
    );
    let Some(LegacyContent::Text { text, .. }) = call.content.first() else {
        return;
    };
    let auth_json: serde_json::Value = serde_json::from_str(text).unwrap();
    assert_eq!(
        auth_json.get("subject").and_then(|v| v.as_str()),
        Some("user-1")
    );
    assert!(auth_json.get("token").is_none());
    assert!(!text.contains("good-token"));
}

// FND-01: JWT e2e removed — undeclared cfg(feature="jwt") is fatal under -D warnings,
// and production JWT is not a facade/server feature (FACADE-NO-JSONWEBTOKEN).

#[test]
fn e2e_auth_oauth_token_verifier_revocation_and_refresh() {
    use fastmcp_rust::oauth::{
        AuthorizationApprovalBackend, AuthorizationApprovalDisposition,
        AuthorizationApprovalGeneration, AuthorizationApprovalRequest, AuthorizationRequest,
        CodeChallengeMethod, OAuthClient, OAuthServer, OAuthServerConfig, TokenRequest,
    };

    const CLIENT_SECRET: &str = "e2e-approval-client-secret-canary";
    struct E2eApprovalBackend(std::sync::Mutex<Option<String>>);
    impl AuthorizationApprovalBackend for E2eApprovalBackend {
        fn generation(&self) -> AuthorizationApprovalGeneration {
            AuthorizationApprovalGeneration::from_bytes([0xE2; 32])
        }

        fn approve(
            &self,
            request: &AuthorizationApprovalRequest,
        ) -> AuthorizationApprovalDisposition {
            *self.0.lock().expect("approval observation") = Some(format!("{request:?}"));
            AuthorizationApprovalDisposition::Approved(
                request
                    .approve(
                        "user123".to_string(),
                        request.scopes().to_vec(),
                        request.resource().map(str::to_string),
                        self.generation(),
                    )
                    .expect("validated approval request"),
            )
        }
    }

    let approval = Arc::new(E2eApprovalBackend(std::sync::Mutex::new(None)));
    let approval_backend: Arc<dyn AuthorizationApprovalBackend> = approval.clone();
    let oauth = Arc::new(OAuthServer::with_approval_backend(
        OAuthServerConfig::default(),
        approval_backend,
    ));
    let client_def = OAuthClient::builder("test-client")
        .secret(CLIENT_SECRET)
        .redirect_uri("http://127.0.0.1:3000/callback")
        .scope("read")
        .build()
        .unwrap();
    oauth.register_client(client_def).unwrap();

    // RFC 7636 Appendix B verifier/challenge pair.
    let code_verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
    let auth_request = AuthorizationRequest {
        response_type: "code".to_string(),
        client_id: "test-client".to_string(),
        redirect_uri: "http://127.0.0.1:3000/callback".to_string(),
        scopes: vec!["read".to_string()],
        resource: None,
        state: None,
        code_challenge: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM".to_string(),
        code_challenge_method: CodeChallengeMethod::S256,
    };
    let (code, _redirect) = oauth.authorize(&auth_request).unwrap();
    let approval_debug = approval
        .0
        .lock()
        .expect("approval observation")
        .clone()
        .expect("approval backend called");
    assert!(!approval_debug.contains(CLIENT_SECRET));
    assert!(!approval_debug.contains(&code));

    let token_response = oauth
        .token(&TokenRequest {
            grant_type: "authorization_code".to_string(),
            code: Some(code),
            redirect_uri: Some("http://127.0.0.1:3000/callback".to_string()),
            client_id: "test-client".to_string(),
            client_secret: Some(CLIENT_SECRET.to_string()),
            code_verifier: Some(code_verifier.to_string()),
            refresh_token: None,
            scopes: None,
            resource: None,
        })
        .unwrap();

    assert!(!approval_debug.contains(&token_response.access_token));
    assert!(
        !approval_debug.contains(
            token_response
                .refresh_token
                .as_deref()
                .expect("refresh token")
        )
    );

    let access = token_response.access_token.clone();
    let refresh = token_response.refresh_token.clone().expect("refresh token");

    let provider = TokenAuthProvider::new(oauth.token_verifier());
    let mut mcp_client = setup_auth_server_and_client(provider, "e2e-auth-oauth");
    mcp_client.initialize().unwrap();

    let mut trace = TestTrace::new("e2e-auth-oauth");

    // Access token allows request.
    let params = json!({
        "name": "greeting",
        "arguments": { "name": "Grace" },
        "auth": format!("Bearer {access}"),
    });
    let corr = trace.log_request("tools/call", Some(&params));
    let value = mcp_client.send_request_json("tools/call", params).unwrap();
    trace.log_response(&corr, Some(&value), None::<&serde_json::Value>);
    let call: fastmcp_protocol::CallToolResult = serde_json::from_value(value).unwrap();
    assert!(!call.is_error);

    // Verify auth context propagated from OAuth subject/scopes.
    let params = json!({
        "name": "auth_info",
        "arguments": {},
        "auth": format!("Bearer {access}"),
    });
    let corr = trace.log_request("tools/call(auth_info)", Some(&params));
    let value = mcp_client.send_request_json("tools/call", params).unwrap();
    trace.log_response(&corr, Some(&value), None::<&serde_json::Value>);
    let call: fastmcp_protocol::CallToolResult = serde_json::from_value(value).unwrap();
    assert!(
        matches!(call.content.first(), Some(LegacyContent::Text { .. })),
        "expected text content"
    );
    let Some(LegacyContent::Text { text, .. }) = call.content.first() else {
        return;
    };
    let auth_json: serde_json::Value = serde_json::from_str(text).unwrap();
    assert_eq!(
        auth_json.get("subject").and_then(|v| v.as_str()),
        Some("user123")
    );

    // Revoke access token: request should now be forbidden.
    oauth.revoke(&access, "test-client", None).unwrap();
    let params = json!({ "cursor": null, "auth": format!("Bearer {access}") });
    let corr = trace.log_request("tools/list(revoked)", Some(&params));
    let err = mcp_client
        .send_request_json("tools/list", params)
        .unwrap_err();
    trace.log_response(
        &corr,
        None::<&serde_json::Value>,
        Some(&json!({"error": err.message})),
    );
    assert_eq!(err.code, McpErrorCode::ResourceForbidden);

    // Refresh: new access token should be accepted.
    let refreshed = oauth
        .token(&TokenRequest {
            grant_type: "refresh_token".to_string(),
            code: None,
            redirect_uri: None,
            client_id: "test-client".to_string(),
            client_secret: None,
            code_verifier: None,
            refresh_token: Some(refresh),
            scopes: None,
            resource: None,
        })
        .unwrap();

    let new_access = refreshed.access_token;
    let params = json!({
        "name": "greeting",
        "arguments": { "name": "Grace" },
        "auth": format!("Bearer {new_access}"),
    });
    let corr = trace.log_request("tools/call(refreshed)", Some(&params));
    let value = mcp_client.send_request_json("tools/call", params).unwrap();
    trace.log_response(&corr, Some(&value), None::<&serde_json::Value>);
    let call: fastmcp_protocol::CallToolResult = serde_json::from_value(value).unwrap();
    assert!(!call.is_error);
}

// ============================================================================
// Tool listing tests
// ============================================================================

#[test]
fn e2e_list_tools() {
    let mut client = setup_test_server_and_client();
    client.initialize().unwrap();

    let tools = client.list_tools().unwrap();
    assert_eq!(tools.len(), 3, "Expected 3 tools, got {}", tools.len());

    let names: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect();
    assert!(names.contains(&"greeting"), "Missing greeting tool");
    assert!(names.contains(&"calculator"), "Missing calculator tool");
    assert!(names.contains(&"error_tool"), "Missing error_tool");
}

#[test]
fn e2e_list_tools_returns_definitions() {
    let mut client = setup_test_server_and_client();
    client.initialize().unwrap();

    let tools = client.list_tools().unwrap();
    let greeting = tools.iter().find(|t| t.name == "greeting").unwrap();

    assert_eq!(
        greeting.description.as_deref(),
        Some("Returns a greeting for the given name")
    );
    assert!(greeting.input_schema.get("properties").is_some());
    assert_eq!(greeting.version.as_deref(), Some("1.0.0"));
}

// ============================================================================
// Tool invocation tests
// ============================================================================

#[test]
fn e2e_call_tool_greeting() {
    let mut client = setup_test_server_and_client();
    client.initialize().unwrap();

    let result = client
        .call_tool("greeting", json!({"name": "Alice"}))
        .unwrap();
    assert_eq!(result.len(), 1);

    assert!(
        matches!(result.first(), Some(LegacyContent::Text { .. })),
        "expected text content"
    );
    let Some(LegacyContent::Text { text, .. }) = result.first() else {
        return;
    };
    assert_eq!(text, "Hello, Alice!");
}

#[test]
fn e2e_call_tool_calculator_add() {
    let mut client = setup_test_server_and_client();
    client.initialize().unwrap();

    let result = client
        .call_tool("calculator", json!({"a": 10, "b": 20, "operation": "add"}))
        .unwrap();
    assert_eq!(result.len(), 1);

    assert!(
        matches!(result.first(), Some(LegacyContent::Text { .. })),
        "expected text content"
    );
    let Some(LegacyContent::Text { text, .. }) = result.first() else {
        return;
    };
    assert_eq!(text, "30");
}

#[test]
fn e2e_call_tool_calculator_multiply() {
    let mut client = setup_test_server_and_client();
    client.initialize().unwrap();

    let result = client
        .call_tool(
            "calculator",
            json!({"a": 7, "b": 6, "operation": "multiply"}),
        )
        .unwrap();

    assert!(
        matches!(result.first(), Some(LegacyContent::Text { .. })),
        "expected text content"
    );
    let Some(LegacyContent::Text { text, .. }) = result.first() else {
        return;
    };
    assert_eq!(text, "42");
}

#[test]
fn e2e_call_tool_calculator_divide() {
    let mut client = setup_test_server_and_client();
    client.initialize().unwrap();

    let result = client
        .call_tool(
            "calculator",
            json!({"a": 100, "b": 4, "operation": "divide"}),
        )
        .unwrap();

    assert!(
        matches!(result.first(), Some(LegacyContent::Text { .. })),
        "expected text content"
    );
    let Some(LegacyContent::Text { text, .. }) = result.first() else {
        return;
    };
    assert_eq!(text, "25");
}

#[test]
fn e2e_call_tool_error_handler() {
    let mut client = setup_test_server_and_client();
    client.initialize().unwrap();

    let result = client.call_tool("error_tool", json!({}));
    assert!(result.is_err(), "Error tool should return an error");
}

#[test]
fn e2e_call_tool_division_by_zero() {
    let mut client = setup_test_server_and_client();
    client.initialize().unwrap();

    let result = client.call_tool(
        "calculator",
        json!({"a": 10, "b": 0, "operation": "divide"}),
    );
    assert!(result.is_err(), "Division by zero should return an error");
}

#[test]
fn e2e_call_unknown_tool() {
    let mut client = setup_test_server_and_client();
    client.initialize().unwrap();

    let result = client.call_tool("nonexistent_tool", json!({}));
    assert!(result.is_err(), "Unknown tool should return an error");
}

// ============================================================================
// Resource listing and reading tests
// ============================================================================

#[test]
fn e2e_list_resources() {
    let mut client = setup_test_server_and_client();
    client.initialize().unwrap();

    let resources = client.list_resources().unwrap();
    assert_eq!(
        resources.len(),
        2,
        "Expected 2 resources, got {}",
        resources.len()
    );

    let uris: Vec<&str> = resources.iter().map(|r| r.uri.as_str()).collect();
    assert!(
        uris.contains(&"file:///test/sample.txt"),
        "Missing text file resource"
    );
    assert!(
        uris.contains(&"file:///config/settings.json"),
        "Missing config resource"
    );
}

#[test]
fn e2e_list_resources_returns_metadata() {
    let mut client = setup_test_server_and_client();
    client.initialize().unwrap();

    let resources = client.list_resources().unwrap();
    let text_file = resources.iter().find(|r| r.name == "sample.txt").unwrap();

    assert_eq!(text_file.mime_type.as_deref(), Some("text/plain"));
    assert_eq!(text_file.description.as_deref(), Some("A sample text file"));
}

#[test]
fn e2e_read_text_resource() {
    let mut client = setup_test_server_and_client();
    client.initialize().unwrap();

    let contents = client.read_resource("file:///test/sample.txt").unwrap();
    assert_eq!(contents.len(), 1);
    let LegacyResourceContent::Text {
        uri,
        mime_type,
        text,
        ..
    } = &contents[0]
    else {
        panic!("text resource must use exact legacy text resource content");
    };
    assert_eq!(uri, "file:///test/sample.txt");
    assert_eq!(mime_type.as_deref(), Some("text/plain"));
    assert!(
        text.contains("Hello, World!"),
        "Text content should contain greeting"
    );
}

#[test]
fn e2e_read_json_resource() {
    let mut client = setup_test_server_and_client();
    client.initialize().unwrap();

    let contents = client
        .read_resource("file:///config/settings.json")
        .unwrap();
    assert_eq!(contents.len(), 1);
    let LegacyResourceContent::Text {
        mime_type, text, ..
    } = &contents[0]
    else {
        panic!("JSON resource must use exact legacy text resource content");
    };
    assert_eq!(mime_type.as_deref(), Some("application/json"));

    // Parse the JSON content to verify structure
    let config: serde_json::Value = serde_json::from_str(text).unwrap();
    assert_eq!(config.get("version").unwrap(), "1.0.0");
    assert_eq!(config.get("max_connections").unwrap(), 100);
}

#[test]
fn e2e_read_unknown_resource() {
    let mut client = setup_test_server_and_client();
    client.initialize().unwrap();

    let result = client.read_resource("file:///nonexistent");
    assert!(
        result.is_err(),
        "Reading unknown resource should return an error"
    );
}

// ============================================================================
// Prompt listing and retrieval tests
// ============================================================================

#[test]
fn e2e_list_prompts() {
    let mut client = setup_test_server_and_client();
    client.initialize().unwrap();

    let prompts = client.list_prompts().unwrap();
    assert_eq!(
        prompts.len(),
        2,
        "Expected 2 prompts, got {}",
        prompts.len()
    );

    let names: Vec<&str> = prompts.iter().map(|p| p.name.as_str()).collect();
    assert!(names.contains(&"greeting"), "Missing greeting prompt");
    assert!(names.contains(&"code_review"), "Missing code_review prompt");
}

#[test]
fn e2e_list_prompts_returns_arguments() {
    let mut client = setup_test_server_and_client();
    client.initialize().unwrap();

    let prompts = client.list_prompts().unwrap();
    let greeting = prompts.iter().find(|p| p.name == "greeting").unwrap();

    assert_eq!(greeting.arguments.len(), 1);
    assert_eq!(greeting.arguments[0].name, "name");
    assert!(greeting.arguments[0].required);
}

#[test]
fn e2e_get_prompt_greeting() {
    let mut client = setup_test_server_and_client();
    client.initialize().unwrap();

    let mut args = HashMap::new();
    args.insert("name".to_string(), "Bob".to_string());

    let messages = client.get_prompt("greeting", args).unwrap();
    assert_eq!(messages.len(), 1);

    let Some(first) = messages.first() else {
        return;
    };
    assert!(
        matches!(&first.content, LegacyContent::Text { .. }),
        "expected text content"
    );
    let LegacyContent::Text { text, .. } = &first.content else {
        return;
    };
    assert!(
        text.contains("Bob"),
        "Greeting should contain the name, got: {text}"
    );
}

#[test]
fn e2e_get_prompt_code_review() {
    let mut client = setup_test_server_and_client();
    client.initialize().unwrap();

    let mut args = HashMap::new();
    args.insert("code".to_string(), "fn main() {}".to_string());
    args.insert("language".to_string(), "rust".to_string());

    let messages = client.get_prompt("code_review", args).unwrap();
    assert_eq!(messages.len(), 2, "Expected 2 messages (user + assistant)");

    // First message should be user with the code
    assert!(matches!(messages[0].role, Role::User));
    let Some(first) = messages.first() else {
        return;
    };
    assert!(
        matches!(&first.content, LegacyContent::Text { .. }),
        "expected text content"
    );
    let LegacyContent::Text { text, .. } = &first.content else {
        return;
    };
    assert!(text.contains("rust"), "Should mention language");
    assert!(text.contains("fn main()"), "Should contain the code");

    // Second message should be assistant
    assert!(matches!(messages[1].role, Role::Assistant));
}

#[test]
fn e2e_get_unknown_prompt() {
    let mut client = setup_test_server_and_client();
    client.initialize().unwrap();

    let result = client.get_prompt("nonexistent_prompt", HashMap::new());
    assert!(
        result.is_err(),
        "Getting unknown prompt should return an error"
    );
}

// ============================================================================
// Pre-initialization error tests
// ============================================================================

#[test]
fn e2e_call_before_initialize() {
    let mut client = setup_test_server_and_client();
    // Don't call initialize()

    let result = client.list_tools();
    assert!(
        result.is_err(),
        "Operations before initialization should fail"
    );
}

// ============================================================================
// Raw request tests (JSON-RPC compliance)
// ============================================================================

#[test]
fn e2e_raw_request_unknown_method() {
    let mut client = setup_test_server_and_client();
    client.initialize().unwrap();

    let result = client.send_raw_request("nonexistent/method", json!({}));
    assert!(result.is_err(), "Unknown method should return an error");
}

// ============================================================================
// Multiple sequential operations
// ============================================================================

#[test]
fn e2e_full_workflow() {
    let mut client = setup_test_server_and_client();

    // Step 1: Initialize
    let init = client.initialize().unwrap();
    assert_eq!(init.server_info.name, "e2e-test-server");

    // Step 2: List tools
    let tools = client.list_tools().unwrap();
    assert_eq!(tools.len(), 3);

    // Step 3: Call a tool
    let greeting = client
        .call_tool("greeting", json!({"name": "E2E"}))
        .unwrap();
    assert!(
        matches!(greeting.first(), Some(LegacyContent::Text { .. })),
        "expected text content"
    );
    let Some(LegacyContent::Text { text, .. }) = greeting.first() else {
        return;
    };
    assert_eq!(text, "Hello, E2E!");

    // Step 4: List resources
    let resources = client.list_resources().unwrap();
    assert_eq!(resources.len(), 2);

    // Step 5: Read a resource
    let content = client.read_resource("file:///test/sample.txt").unwrap();
    assert!(matches!(
        content.first(),
        Some(LegacyResourceContent::Text { text, .. }) if text.contains("Hello")
    ));

    // Step 6: List prompts
    let prompts = client.list_prompts().unwrap();
    assert_eq!(prompts.len(), 2);

    // Step 7: Get a prompt
    let mut args = HashMap::new();
    args.insert("name".to_string(), "Test".to_string());
    let messages = client.get_prompt("greeting", args).unwrap();
    assert!(!messages.is_empty());
}

#[test]
fn e2e_multiple_tool_calls() {
    let mut client = setup_test_server_and_client();
    client.initialize().unwrap();

    // Make several tool calls in sequence
    for i in 0..5 {
        let name = format!("User{i}");
        let result = client.call_tool("greeting", json!({"name": name})).unwrap();
        assert!(
            matches!(result.first(), Some(LegacyContent::Text { .. })),
            "expected text content"
        );
        let Some(LegacyContent::Text { text, .. }) = result.first() else {
            return;
        };
        assert_eq!(text, &format!("Hello, {name}!"));
    }
}

#[test]
fn e2e_mixed_operations() {
    let mut client = setup_test_server_and_client();
    client.initialize().unwrap();

    // Interleave tool calls, resource reads, and prompt gets
    let tools = client.list_tools().unwrap();
    assert!(!tools.is_empty());

    let result = client
        .call_tool("calculator", json!({"a": 2, "b": 3, "operation": "add"}))
        .unwrap();
    assert!(
        matches!(result.first(), Some(LegacyContent::Text { .. })),
        "expected text content"
    );
    let Some(LegacyContent::Text { text, .. }) = result.first() else {
        return;
    };
    assert_eq!(text, "5");

    let resources = client.list_resources().unwrap();
    assert!(!resources.is_empty());

    let content = client
        .read_resource("file:///config/settings.json")
        .unwrap();
    assert!(!content.is_empty());

    let prompts = client.list_prompts().unwrap();
    assert!(!prompts.is_empty());

    let mut args = HashMap::new();
    args.insert("name".to_string(), "Mixed".to_string());
    let messages = client.get_prompt("greeting", args).unwrap();
    assert!(!messages.is_empty());

    // Another tool call after all the interleaving
    let result = client
        .call_tool(
            "calculator",
            json!({"a": 10, "b": 5, "operation": "subtract"}),
        )
        .unwrap();
    assert!(
        matches!(result.first(), Some(LegacyContent::Text { .. })),
        "expected text content"
    );
    let Some(LegacyContent::Text { text, .. }) = result.first() else {
        return;
    };
    assert_eq!(text, "5");
}

// ============================================================================
// Server with minimal configuration
// ============================================================================

#[test]
fn e2e_server_with_tools_only() {
    let (builder, client_transport, server_transport) = TestServer::builder()
        .with_name("tools-only")
        .build_server_builder();

    let server = builder.tool(GreetingToolHandler).build();

    let handle = spawn_thread(move || {
        server.run_transport(server_transport);
    });

    let mut client = TestHarness::new(TestClient::new(client_transport), handle);
    let init = client.initialize().unwrap();

    // Should have tools but not resources or prompts
    assert!(init.capabilities.tools.is_some());
    assert!(init.capabilities.resources.is_none());
    assert!(init.capabilities.prompts.is_none());

    let tools = client.list_tools().unwrap();
    assert_eq!(tools.len(), 1);
    assert_eq!(tools[0].name, "greeting");
}

#[test]
fn e2e_server_with_resources_only() {
    let (builder, client_transport, server_transport) = TestServer::builder()
        .with_name("resources-only")
        .build_server_builder();

    let server = builder.resource(TextFileResourceHandlerResource).build();

    let handle = spawn_thread(move || {
        server.run_transport(server_transport);
    });

    let mut client = TestHarness::new(TestClient::new(client_transport), handle);
    let init = client.initialize().unwrap();

    assert!(init.capabilities.tools.is_none());
    assert!(init.capabilities.resources.is_some());
    assert!(init.capabilities.prompts.is_none());

    let resources = client.list_resources().unwrap();
    assert_eq!(resources.len(), 1);
}

#[test]
fn e2e_server_with_prompts_only() {
    let (builder, client_transport, server_transport) = TestServer::builder()
        .with_name("prompts-only")
        .build_server_builder();

    let server = builder.prompt(GreetingPromptHandlerPrompt).build();

    let handle = spawn_thread(move || {
        server.run_transport(server_transport);
    });

    let mut client = TestHarness::new(TestClient::new(client_transport), handle);
    let init = client.initialize().unwrap();

    assert!(init.capabilities.tools.is_none());
    assert!(init.capabilities.resources.is_none());
    assert!(init.capabilities.prompts.is_some());

    let prompts = client.list_prompts().unwrap();
    assert_eq!(prompts.len(), 1);
}

#[test]
fn e2e_empty_server() {
    let (builder, client_transport, server_transport) = TestServer::builder()
        .with_name("empty-server")
        .build_server_builder();

    let server = builder.build();

    let handle = spawn_thread(move || {
        server.run_transport(server_transport);
    });

    let mut client = TestHarness::new(TestClient::new(client_transport), handle);
    let init = client.initialize().unwrap();

    // Empty server should not advertise any capabilities
    assert!(init.capabilities.tools.is_none());
    assert!(init.capabilities.resources.is_none());
    assert!(init.capabilities.prompts.is_none());
}

// ============================================================================
// Custom client info
// ============================================================================

#[test]
fn e2e_custom_client_info() {
    let (builder, client_transport, server_transport) =
        TestServer::builder().build_server_builder();

    let server = builder.tool(GreetingToolHandler).build();

    let handle = spawn_thread(move || {
        server.run_transport(server_transport);
    });

    let client = TestClient::new(client_transport).with_client_info("custom-client", "3.0.0");
    let mut client = TestHarness::new(client, handle);

    let init = client.initialize().unwrap();
    // Initialization should succeed with custom client info
    assert!(init.capabilities.tools.is_some());
}

// ============================================================================
// Public facade dual-era stdio negotiation
// ============================================================================

#[cfg(unix)]
fn shipped_echo_server_executable() -> &'static str {
    env!("CARGO_BIN_EXE_echo_server")
}

#[cfg(unix)]
fn connect_auto_stdio_to_shipped_echo_server(server_policy: &str) -> Client {
    let command = shipped_echo_server_executable();
    let builder = auto::client_builder().env("FASTMCP_PROTOCOL_POLICY", server_policy);
    assert_eq!(
        builder.selected_protocol_plan().policy(),
        ProtocolPolicy::Auto
    );

    let cx = Cx::for_request();
    builder
        .connect_stdio_with_cx(command, &[], &cx)
        .expect("the public Auto facade client connects to the shipped stdio example")
}

#[cfg(unix)]
fn connect_modern_stdio_to_shipped_echo_server(server_policy: &str) -> McpResult<modern::Client> {
    connect_modern_stdio_to_shipped_echo_server_with_env(server_policy, &[])
}

#[cfg(unix)]
fn connect_modern_stdio_to_shipped_echo_server_with_env(
    server_policy: &str,
    extra_env: &[(&str, &str)],
) -> McpResult<modern::Client> {
    let command = shipped_echo_server_executable();
    let mut builder = modern::client_builder().env("FASTMCP_PROTOCOL_POLICY", server_policy);
    for (key, value) in extra_env {
        builder = builder.env(*key, *value);
    }
    builder.connect_stdio_with_cx(command, &[], &Cx::for_request())
}

#[cfg(unix)]
const STDIO_COMPLETION_IDLE_TIMEOUT: Duration = Duration::from_secs(2);
#[cfg(unix)]
const STDIO_COMPLETION_ABSOLUTE_TIMEOUT: Duration = Duration::from_secs(4);
#[cfg(unix)]
const STDIO_COMPLETION_CLEANUP_BOUND: Duration = Duration::from_secs(4);

#[cfg(unix)]
const ECHO_SERVER_INSTRUCTIONS: &str =
    "A simple echo server for testing FastMCP. Try calling the 'echo' tool with a message!";

#[cfg(unix)]
fn connect_bounded_modern_stdio_to_shipped_echo_server(
    server_policy: &str,
) -> McpResult<modern::Client> {
    connect_bounded_modern_stdio_to_shipped_echo_server_with_env(server_policy, &[])
}

#[cfg(unix)]
fn connect_bounded_modern_stdio_to_shipped_echo_server_with_env(
    server_policy: &str,
    extra_env: &[(&str, &str)],
) -> McpResult<modern::Client> {
    let command = shipped_echo_server_executable();
    let mut builder = modern::client_builder()
        .env("FASTMCP_PROTOCOL_POLICY", server_policy)
        .request_timeout_policy(
            RequestTimeoutPolicy::new(
                STDIO_COMPLETION_IDLE_TIMEOUT,
                STDIO_COMPLETION_ABSOLUTE_TIMEOUT,
            )
            .expect("the public completion timeout policy is valid"),
        );
    for (key, value) in extra_env {
        builder = builder.env(*key, *value);
    }
    builder.connect_stdio_with_cx(command, &[], &Cx::for_request())
}

#[cfg(unix)]
fn stdio_mrtr_capabilities(
    sampling: bool,
    roots: bool,
    form: bool,
    url: bool,
) -> modern::ClientCapabilities {
    let mut capabilities = modern::ClientCapabilities::default();
    if sampling {
        capabilities.sampling = Some(Default::default());
    }
    if roots {
        capabilities.roots = serde_json::from_value(json!({})).expect("roots capability is valid");
    }
    if form || url {
        let mut elicitation = json!({});
        if form {
            elicitation["form"] = json!({});
        }
        if url {
            elicitation["url"] = json!({});
        }
        capabilities.elicitation =
            serde_json::from_value(elicitation).expect("elicitation capability is valid");
    }
    capabilities
}

#[cfg(unix)]
fn connect_bounded_modern_stdio_with_mrtr(
    server_policy: &str,
    capabilities: modern::ClientCapabilities,
    handlers: modern::ReverseRequestHandlers,
) -> McpResult<modern::Client> {
    let command = shipped_echo_server_executable();
    modern::client_builder()
        .env("FASTMCP_PROTOCOL_POLICY", server_policy)
        .request_timeout_policy(
            RequestTimeoutPolicy::new(
                STDIO_COMPLETION_IDLE_TIMEOUT,
                STDIO_COMPLETION_ABSOLUTE_TIMEOUT,
            )
            .expect("the public completion timeout policy is valid"),
        )
        .capabilities(capabilities)
        .modern_reverse_request_handlers(handlers)
        .connect_stdio_with_cx(command, &[], &Cx::for_request())
}

#[cfg(unix)]
fn assert_stdio_input_required(result: &modern::InputRequiredResult, key: &str, kind: &str) {
    assert!(
        result.request_state().is_some(),
        "{kind} must return framework-issued requestState"
    );
    assert!(
        result
            .input_requests()
            .is_some_and(|requests| requests.get(key).is_some()),
        "{kind} must retain its {key} input request"
    );
}

#[cfg(unix)]
fn assert_stdio_capability_gate(result: &modern::FinalCoreResult, kind: &str) {
    let modern::FinalCoreResult::ToolsCall { result, .. } = result else {
        panic!("{kind} missing capability must fail closed as a tool error: {result:?}");
    };
    assert!(
        result.payload.is_error,
        "{kind} missing capability must fail closed: {result:?}"
    );
    assert!(
        result.payload.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => text.contains("not advertised by the client"),
            _ => false,
        }),
        "{kind} missing capability must name the capability gate: {result:?}"
    );
}

#[cfg(unix)]
fn connect_legacy_stdio_to_shipped_echo_server(
    server_policy: &str,
) -> McpResult<legacy_2024::Client> {
    connect_legacy_stdio_to_shipped_echo_server_with_env(server_policy, &[])
}

#[cfg(unix)]
fn connect_legacy_stdio_to_shipped_echo_server_with_env(
    server_policy: &str,
    extra_env: &[(&str, &str)],
) -> McpResult<legacy_2024::Client> {
    connect_legacy_stdio_to_shipped_echo_server_with_reverse_handlers_and_env(
        server_policy,
        legacy_2024::LegacyReverseRequestHandlers::new(),
        extra_env,
    )
}

#[cfg(unix)]
fn connect_legacy_stdio_to_shipped_echo_server_with_reverse_handlers(
    server_policy: &str,
    handlers: legacy_2024::LegacyReverseRequestHandlers,
) -> McpResult<legacy_2024::Client> {
    connect_legacy_stdio_to_shipped_echo_server_with_reverse_handlers_and_env(
        server_policy,
        handlers,
        &[],
    )
}

#[cfg(unix)]
fn connect_legacy_stdio_to_shipped_echo_server_with_reverse_handlers_and_env(
    server_policy: &str,
    handlers: legacy_2024::LegacyReverseRequestHandlers,
    extra_env: &[(&str, &str)],
) -> McpResult<legacy_2024::Client> {
    let command = shipped_echo_server_executable();
    let mut builder = legacy_2024::client_builder()
        .env("FASTMCP_PROTOCOL_POLICY", server_policy)
        .reverse_request_handlers(handlers);
    for (key, value) in extra_env {
        builder = builder.env(*key, *value);
    }
    assert_eq!(
        builder.protocol_policy(),
        legacy_2024::ProtocolPolicy::LegacyOnly
    );

    builder.connect_stdio_with_cx(command, &[], &Cx::for_request())
}

#[cfg(unix)]
fn selected_modern_stdio_raw_result(
    client: &mut Client,
    method: &str,
    parameters: serde_json::Value,
) -> serde_json::Value {
    let cx = Cx::for_request();
    let mut request = client
        .start_multiplexed_request(&cx, method, Some(parameters))
        .expect("the selected modern public facade commits the raw MRTR request");
    let response = client
        .wait_multiplexed_request(&cx, &mut request)
        .expect("the selected modern public facade receives the raw MRTR response");
    assert!(response.error.is_none(), "the raw MRTR request succeeds");
    response
        .result
        .expect("a successful raw MRTR response carries its exact result")
}

#[cfg(unix)]
fn selected_modern_stdio_raw_error(
    client: &mut Client,
    method: &str,
    parameters: serde_json::Value,
) -> String {
    let cx = Cx::for_request();
    let mut request = client
        .start_multiplexed_request(&cx, method, Some(parameters))
        .expect("the selected modern public facade commits the negative MRTR request");
    client
        .wait_multiplexed_request(&cx, &mut request)
        .expect_err("the rejected MRTR retry surfaces as the public wait error")
        .message
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_auto_selects_modern_on_the_shipped_facade_server() {
    let mut client = connect_auto_stdio_to_shipped_echo_server("auto");

    assert_eq!(client.protocol_policy(), ProtocolPolicy::Auto);
    assert_eq!(
        client.selected_protocol_era(),
        Some(ProtocolEra::Modern2026),
        "the real Auto server must retain the successful modern discovery selection"
    );
    assert_eq!(
        client.protocol_version(),
        fastmcp_rust::modern::PROTOCOL_VERSION
    );
    assert_eq!(client.server_info().name, "echo-server");
    assert!(
        client.server_discovery().is_some(),
        "a modern selection retains its public discovery observable"
    );
    let tools = client
        .list_tools()
        .expect("the selected modern stdio client accepts tools/list");
    assert!(
        tools.iter().any(|tool| tool.name == "echo"),
        "the modern tools/list result must expose the shipped echo tool"
    );
    client.close().expect("modern stdio client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_auto_falls_back_to_exact_legacy_on_the_shipped_facade_server() {
    let mut client = connect_auto_stdio_to_shipped_echo_server("legacy-only");

    assert_eq!(client.protocol_policy(), ProtocolPolicy::Auto);
    assert_eq!(
        client.selected_protocol_era(),
        Some(ProtocolEra::Legacy2024),
        "the real legacy-only server must make Auto reopen its fresh exact-legacy stdio session"
    );
    assert_eq!(
        client.protocol_version(),
        fastmcp_rust::legacy_2024::PROTOCOL_VERSION
    );
    assert_eq!(client.server_info().name, "echo-server");
    assert!(
        client.server_discovery().is_none(),
        "an exact legacy session cannot inherit modern discovery state"
    );
    client
        .ping()
        .expect("the selected exact-legacy stdio client remains usable");
    client.close().expect("legacy stdio client cleanup");
}

#[cfg(unix)]
fn assert_public_auto_stdio_multiplexes(server_policy: &str, expected_era: ProtocolEra) {
    let mut client = connect_auto_stdio_to_shipped_echo_server(server_policy);
    assert_eq!(client.protocol_policy(), ProtocolPolicy::Auto);
    assert_eq!(client.selected_protocol_era(), Some(expected_era));

    let executor = client
        .multiplexed_stdio_executor()
        .expect("the selected public stdio session installs its shared executor");
    assert_eq!(executor.selected_protocol_era(), expected_era);
    let cx = Cx::for_request();
    // Both sends occur before either wait. The real subprocess therefore sees
    // two committed request owners on the selected final child, rather than a
    // tautological sequence of one request followed by one response.
    let mut first = client
        .start_multiplexed_request(&cx, "ping", Some(json!({})))
        .expect("first selected-era ping commits");
    let mut second = client
        .start_multiplexed_request(&cx, "ping", Some(json!({})))
        .expect("second selected-era ping commits before the first wait");
    assert_ne!(first.request_id(), second.request_id());

    // The sequential adapter must drive this same ingress/correlation path.
    // Its response wait sees and preserves both earlier multiplexed owners
    // before consuming its own real subprocess response.
    client
        .ping()
        .expect("the sequential adapter cannot consume either multiplexed response");

    let first_response = client
        .wait_multiplexed_request(&cx, &mut first)
        .expect("first committed request receives its own final response");
    let second_response = client
        .wait_multiplexed_request(&cx, &mut second)
        .expect("second committed request receives its own final response");
    assert_eq!(first_response.id.as_ref(), Some(first.request_id()));
    assert_eq!(second_response.id.as_ref(), Some(second.request_id()));
    assert!(first_response.error.is_none());
    assert!(second_response.error.is_none());
    drop(executor);
    client.close().expect("multiplexed stdio client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_auto_modern_selection_multiplexes_two_committed_requests() {
    assert_public_auto_stdio_multiplexes("auto", ProtocolEra::Modern2026);
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_auto_legacy_fallback_multiplexes_two_committed_requests() {
    // The paired positive differs only in the real child's era policy. Auto
    // must tear down its modern probe, establish a fresh exact-2024 child,
    // then install the same shared executor on that final connection.
    assert_public_auto_stdio_multiplexes("legacy-only", ProtocolEra::Legacy2024);
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_only_round_trips_with_the_shipped_facade_server() {
    let mut client = connect_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client completes live modern discovery");

    assert_eq!(
        client.protocol_version(),
        fastmcp_rust::modern::PROTOCOL_VERSION
    );
    let tools = client
        .list_tools(None)
        .expect("the explicit ModernOnly connection accepts tools/list");
    assert!(
        tools.tools.iter().any(|tool| tool.name == "echo"),
        "the modern tools/list result must expose the shipped echo tool"
    );
    client.close().expect("modern-only stdio client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_discovery_retains_instructions() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client completes live modern discovery");
    assert_eq!(
        client
            .instructions()
            .expect("modern discovery exposes handshake instructions"),
        Some(ECHO_SERVER_INSTRUCTIONS),
        "live stdio modern discovery must retain the shipped echo instructions"
    );
    client
        .close()
        .expect("instructed modern stdio client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_discovery_retains_instructions_peer_stays_bare() {
    let mut bare = connect_bounded_modern_stdio_to_shipped_echo_server_with_env(
        "modern-only",
        &[("FASTMCP_NO_INSTRUCTIONS", "1")],
    )
    .expect("a ModernOnly facade client connects to the bare echo peer");
    assert_eq!(
        bare.instructions()
            .expect("modern discovery exposes the missing-instructions observable"),
        None,
        "changing only the missing instructions must keep the peer bare"
    );
    bare.close().expect("bare modern stdio client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_discovery_retains_implementation_identity() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client completes live modern discovery");
    let discovery = client
        .server_discovery()
        .expect("modern discovery exposes handshake identity");
    let identified = discovery
        .implementation()
        .expect("configured modern discovery must retain Implementation identity");
    assert_eq!(identified.name, "echo-server");
    assert_eq!(identified.version, "1.0.0");
    assert_eq!(identified.title.as_deref(), Some("FastMCP Echo"));
    assert_eq!(
        identified.description.as_deref(),
        Some("A simple echo server for testing FastMCP.")
    );
    assert_eq!(
        identified.website_url.as_ref().map(|uri| uri.as_str()),
        Some("https://example.test/fastmcp")
    );
    assert_eq!(
        identified.icons.first().map(|icon| icon.src.as_str()),
        Some("https://example.test/echo-icon.png"),
        "live stdio discovery must retain the shipped echo icon: {identified:?}"
    );
    client
        .close()
        .expect("identified modern stdio client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_discovery_retains_implementation_identity_peer_stays_bare() {
    let mut bare = connect_bounded_modern_stdio_to_shipped_echo_server_with_env(
        "modern-only",
        &[("FASTMCP_NO_IDENTITY", "1")],
    )
    .expect("a ModernOnly facade client connects to the bare-identity echo peer");
    let discovery = bare
        .server_discovery()
        .expect("modern discovery exposes the missing-identity observable");
    assert!(
        discovery.implementation().is_none(),
        "changing only the missing identity extras must keep discovery name/version-only: {:?}",
        discovery.implementation()
    );
    assert_eq!(
        discovery
            .server_info()
            .map(|info| (info.name.as_str(), info.version.as_str())),
        Some(("echo-server", "1.0.0")),
        "the bare peer must still advertise name and version"
    );
    bare.close()
        .expect("bare-identity modern stdio client cleanup");
}

#[cfg(unix)]
fn connect_bounded_modern_stdio_with_client_title(
    server_policy: &str,
    client_name: &str,
    title: Option<&str>,
) -> McpResult<modern::Client> {
    let command = shipped_echo_server_executable();
    let mut builder = modern::client_builder()
        .client_info(client_name, "1.0.0")
        .env("FASTMCP_PROTOCOL_POLICY", server_policy)
        .request_timeout_policy(
            RequestTimeoutPolicy::new(
                STDIO_COMPLETION_IDLE_TIMEOUT,
                STDIO_COMPLETION_ABSOLUTE_TIMEOUT,
            )
            .expect("the public completion timeout policy is valid"),
        );
    if let Some(title) = title {
        builder = builder.title(title);
    }
    builder.connect_stdio_with_cx(command, &[], &Cx::for_request())
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_client_implementation_is_visible_to_handler() {
    let mut client = connect_bounded_modern_stdio_with_client_title(
        "modern-only",
        "e2e-stdio-client-identity",
        Some("Client Title"),
    )
    .expect("a titled ModernOnly facade client completes live modern discovery");
    let reported = client
        .call_tool("client_identity", json!({}))
        .expect("live modern stdio client_identity must reach the shipped handler");
    assert!(
        reported.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => {
                text == "name=e2e-stdio-client-identity|title=Client Title"
            }
            _ => false,
        }),
        "live stdio must attach ClientBuilder title onto McpContext: {reported:?}"
    );
    client
        .close()
        .expect("identified modern stdio client-identity cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_client_implementation_peer_stays_bare() {
    let mut bare = connect_bounded_modern_stdio_with_client_title(
        "modern-only",
        "e2e-stdio-client-identity-bare",
        None,
    )
    .expect("a name/version-only ModernOnly facade client connects to the echo peer");
    let reported = bare
        .call_tool("client_identity", json!({}))
        .expect("bare modern stdio client_identity must still reach the shipped handler");
    assert!(
        reported.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => {
                text == "name=e2e-stdio-client-identity-bare|title=none"
            }
            _ => false,
        }),
        "changing only the missing client title must keep handler-visible extras bare: {reported:?}"
    );
    bare.close()
        .expect("bare modern stdio client-identity cleanup");
}

#[cfg(unix)]
fn connect_legacy_stdio_with_client_name(
    server_policy: &str,
    client_name: &str,
) -> McpResult<legacy_2024::Client> {
    let command = shipped_echo_server_executable();
    legacy_2024::client_builder()
        .client_info(client_name, "1.0.0")
        .env("FASTMCP_PROTOCOL_POLICY", server_policy)
        .request_timeout_policy(
            RequestTimeoutPolicy::new(
                STDIO_COMPLETION_IDLE_TIMEOUT,
                STDIO_COMPLETION_ABSOLUTE_TIMEOUT,
            )
            .expect("the public completion timeout policy is valid"),
        )
        .connect_stdio_with_cx(command, &[], &Cx::for_request())
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_client_info_is_visible_to_handler() {
    let mut client =
        connect_legacy_stdio_with_client_name("legacy-only", "e2e-stdio-legacy-client-identity")
            .expect("a named LegacyOnly facade client completes live exact-2024 initialize");
    let reported = client
        .call_tool("client_identity", json!({}))
        .expect("live exact-2024 stdio client_identity must reach the shipped handler");
    assert_eq!(
        stdio_legacy_tool_text(&reported),
        Some("name=e2e-stdio-legacy-client-identity|title=none"),
        "live exact-2024 stdio must attach initialize clientInfo onto McpContext: {reported:?}"
    );
    client
        .close()
        .expect("named exact-2024 stdio client-identity cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_client_info_peer_changes_only_the_name() {
    let mut other = connect_legacy_stdio_with_client_name(
        "legacy-only",
        "e2e-stdio-legacy-client-identity-other",
    )
    .expect("a differently named LegacyOnly facade client connects to the echo peer");
    let reported = other
        .call_tool("client_identity", json!({}))
        .expect("the other exact-2024 stdio client_identity must still reach the shipped handler");
    assert_eq!(
        stdio_legacy_tool_text(&reported),
        Some("name=e2e-stdio-legacy-client-identity-other|title=none"),
        "changing only the initialize client name must change the handler-visible identity: {reported:?}"
    );
    other
        .close()
        .expect("other exact-2024 stdio client-identity cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_composes_nested_tool_and_resource() {
    let mut client = connect_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client completes live modern discovery");

    let composed = client
        .call_tool("compose_echo", json!({"message": "alpha"}))
        .expect("live modern stdio compose_echo must nest echo and info://server");
    assert!(
        composed.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => {
                text.starts_with("compose:alpha|") && text.contains("echo-server")
            }
            _ => false,
        }),
        "compose_echo must retain the nested echo text and server-info resource: {composed:?}"
    );

    let missing_tool = client.call_tool(
        "compose_echo",
        json!({
            "message": "alpha",
            "tool": "stdio-e2e-missing",
        }),
    );
    let missing_tool = match missing_tool {
        Ok(result) if result.is_error => format!("{result:?}"),
        Err(error) => format!("{error:?}"),
        Ok(result) => panic!(
            "changing only the nested tool name must refuse before the peer resource: {result:?}"
        ),
    };
    assert!(
        missing_tool.contains("stdio-e2e-missing")
            || missing_tool.contains("compose-nested-tool")
            || missing_tool.contains("Unknown tool"),
        "the nested unknown tool must stay a handler-visible refusal: {missing_tool}"
    );

    let missing_resource = client.call_tool(
        "compose_echo",
        json!({
            "message": "beta",
            "resource": "info://stdio-e2e-missing",
        }),
    );
    let missing_resource = match missing_resource {
        Ok(result) if result.is_error => format!("{result:?}"),
        Err(error) => format!("{error:?}"),
        Ok(result) => panic!(
            "changing only the nested resource URI must refuse after the peer tool: {result:?}"
        ),
    };
    assert!(
        missing_resource.contains("info://stdio-e2e-missing")
            || missing_resource.contains("compose-nested-resource")
            || missing_resource.contains("not found"),
        "the nested unknown resource must stay a handler-visible refusal: {missing_resource}"
    );

    client
        .close()
        .expect("modern-only stdio compose client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_composes_nested_prompt() {
    let mut client = connect_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client completes live modern discovery");

    let composed = client
        .call_tool("compose_prompt", json!({"name": "alpha"}))
        .expect("live modern stdio compose_prompt must nest the greeting prompt");
    assert!(
        composed.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => {
                text == "compose-prompt:Please greet alpha in a friendly way."
            }
            _ => false,
        }),
        "compose_prompt must retain the nested greeting text: {composed:?}"
    );

    let missing = client.call_tool(
        "compose_prompt",
        json!({
            "name": "alpha",
            "prompt": "stdio-e2e-missing",
        }),
    );
    let missing = match missing {
        Ok(result) if result.is_error => format!("{result:?}"),
        Err(error) => format!("{error:?}"),
        Ok(result) => panic!("changing only the nested prompt name must refuse: {result:?}"),
    };
    assert!(
        missing.contains("stdio-e2e-missing")
            || missing.contains("compose-nested-prompt")
            || missing.contains("not found"),
        "the nested unknown prompt must stay a handler-visible refusal: {missing}"
    );

    client
        .close()
        .expect("modern-only stdio compose-prompt client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_resource_and_prompt_compose_nested_prompt() {
    let mut client = connect_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client completes live modern discovery");

    let resource = client
        .read_resource("info://compose-prompt")
        .expect("live modern stdio info://compose-prompt must nest greeting");
    assert!(
        resource.contents.iter().any(|content| match content {
            EmbeddedResourceContents::Text { text, .. } => {
                text == "compose-prompt:Please greet alpha in a friendly way."
            }
            _ => false,
        }),
        "info://compose-prompt must retain the nested greeting text: {resource:?}"
    );
    let missing_resource = client
        .read_resource("info://compose-prompt-missing")
        .expect_err("changing only the nested prompt name must refuse the resource compose");
    let missing_resource = format!("{missing_resource:?}");
    assert!(
        missing_resource.contains("stdio-e2e-missing")
            || missing_resource.contains("compose-nested-prompt")
            || missing_resource.contains("not found"),
        "the nested unknown prompt must stay a handler-visible refusal: {missing_resource}"
    );

    let prompt = client
        .get_prompt(
            "compose_from_prompt",
            HashMap::from([("name".to_owned(), "alpha".to_owned())]),
        )
        .expect("live modern stdio compose_from_prompt must nest greeting");
    assert!(
        prompt
            .messages
            .iter()
            .any(|message| match &message.content {
                ContentBlock::Text { text, .. } => {
                    text == "compose-prompt:Please greet alpha in a friendly way."
                }
                _ => false,
            }),
        "compose_from_prompt must retain the nested greeting text: {prompt:?}"
    );
    let missing_prompt = client
        .get_prompt(
            "compose_from_prompt",
            HashMap::from([
                ("name".to_owned(), "alpha".to_owned()),
                ("prompt".to_owned(), "stdio-e2e-missing".to_owned()),
            ]),
        )
        .expect_err("changing only the nested prompt name must refuse the prompt compose");
    let missing_prompt = format!("{missing_prompt:?}");
    assert!(
        missing_prompt.contains("stdio-e2e-missing")
            || missing_prompt.contains("compose-nested-prompt")
            || missing_prompt.contains("not found"),
        "the nested unknown prompt must stay a handler-visible refusal: {missing_prompt}"
    );

    client
        .close()
        .expect("modern-only stdio resource/prompt compose-prompt client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_prompt_composes_nested_tool_and_resource() {
    let mut client = connect_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client completes live modern discovery");

    let composed = client
        .get_prompt(
            "compose_greeting",
            HashMap::from([
                ("name".to_owned(), "alpha".to_owned()),
                ("tool".to_owned(), "echo".to_owned()),
                ("resource".to_owned(), "info://server".to_owned()),
            ]),
        )
        .expect("live modern stdio compose_greeting must nest echo and info://server");
    assert!(
        composed
            .messages
            .iter()
            .any(|message| match &message.content {
                ContentBlock::Text { text, .. } => {
                    text.starts_with("compose:alpha|") && text.contains("echo-server")
                }
                _ => false,
            }),
        "compose_greeting must retain the nested echo text and server-info resource: {composed:?}"
    );

    let missing_tool = client
        .get_prompt(
            "compose_greeting",
            HashMap::from([
                ("name".to_owned(), "alpha".to_owned()),
                ("tool".to_owned(), "stdio-e2e-missing".to_owned()),
                ("resource".to_owned(), "info://server".to_owned()),
            ]),
        )
        .expect_err("changing only the nested tool name must refuse before the peer resource");
    let missing_tool = format!("{missing_tool:?}");
    assert!(
        missing_tool.contains("stdio-e2e-missing")
            || missing_tool.contains("compose-nested-tool")
            || missing_tool.contains("Unknown tool"),
        "the nested unknown tool must stay a handler-visible refusal: {missing_tool}"
    );

    client
        .close()
        .expect("modern-only stdio prompt compose client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_resource_composes_nested_tool_and_resource() {
    let mut client = connect_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client completes live modern discovery");

    let composed = client
        .read_resource("info://compose")
        .expect("live modern stdio info://compose must nest echo and info://server");
    assert!(
        composed.contents.iter().any(|content| match content {
            EmbeddedResourceContents::Text { text, .. } => {
                text.starts_with("compose:alpha|") && text.contains("echo-server")
            }
            _ => false,
        }),
        "info://compose must retain the nested echo text and server-info resource: {composed:?}"
    );

    let missing_tool = client
        .read_resource("info://compose-missing-tool")
        .expect_err("changing only the nested tool name must refuse before the peer resource");
    let missing_tool = format!("{missing_tool:?}");
    assert!(
        missing_tool.contains("stdio-e2e-missing")
            || missing_tool.contains("compose-nested-tool")
            || missing_tool.contains("Unknown tool"),
        "the nested unknown tool must stay a handler-visible refusal: {missing_tool}"
    );

    let missing_resource = client
        .read_resource("info://compose-missing-resource")
        .expect_err("changing only the nested resource URI must refuse after the peer tool");
    let missing_resource = format!("{missing_resource:?}");
    assert!(
        missing_resource.contains("info://stdio-e2e-missing")
            || missing_resource.contains("compose-nested-resource")
            || missing_resource.contains("not found"),
        "the nested unknown resource must stay a handler-visible refusal: {missing_resource}"
    );

    client
        .close()
        .expect("modern-only stdio resource compose client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_handler_timeout_refuses_late_tool_and_admits_fast_peer() {
    let mut client = connect_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client completes live modern discovery");

    let timed_out = client
        .call_tool("slow_echo", json!({}))
        .expect_err("a handler that outlives its timeout must be refused");
    let timed_out = format!("{timed_out:?}");
    assert!(
        timed_out.contains("Request timeout exceeded") || timed_out.contains("RequestCancelled"),
        "the refused late tools/call must keep the handler-timeout error: {timed_out}"
    );

    let fast = client
        .call_tool("fast_echo", json!({}))
        .expect("changing only the tool must still be admitted after a handler timeout");
    assert!(
        fast.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => text == "fast",
            _ => false,
        }),
        "the fast peer tool must still complete: {fast:?}"
    );

    client
        .close()
        .expect("modern-only stdio handler-timeout client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_default_parameter_is_injected_and_overridable() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client completes live modern discovery");

    let injected = client
        .call_tool("greet", json!({"name": "World"}))
        .expect("omitting the defaulted argument must still be admitted");
    assert!(
        injected.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => text == "greet:World!",
            _ => false,
        }),
        "the generated default must be injected at call time: {injected:?}"
    );

    let overridden = client
        .call_tool("greet", json!({"name": "World", "suffix": "?"}))
        .expect("supplying the defaulted argument must override the generated default");
    assert!(
        overridden.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => text == "greet:World?",
            _ => false,
        }),
        "changing only the suffix must override the generated default: {overridden:?}"
    );

    let missing_name = client.call_tool("greet", json!({"suffix": "!"}));
    let missing_name = match missing_name {
        Ok(result) if result.is_error => format!("{result:?}"),
        Err(error) => format!("{error:?}"),
        Ok(result) => {
            panic!("a missing required generated argument must stay an error: {result:?}")
        }
    };
    assert!(
        missing_name.contains("name")
            || missing_name.contains("required")
            || missing_name.contains("Invalid")
            || missing_name.contains("input schema")
            || missing_name.contains("inputSchema"),
        "omitting only the required sibling must stay a handler-visible refusal: {missing_name}"
    );

    let listed_prompts = client
        .list_prompts(None)
        .expect("live modern stdio must list the default-parameter prompt");
    let compose = listed_prompts
        .prompts
        .iter()
        .find(|prompt| prompt.name == "compose_greeting")
        .expect("compose_greeting must remain on the live catalog");
    let arguments = compose.arguments.as_deref().unwrap_or(&[]);
    assert!(
        arguments
            .iter()
            .any(|argument| { argument.name == "name" && argument.required == Some(true) }),
        "compose_greeting must still require name: {compose:?}"
    );
    assert!(
        arguments
            .iter()
            .any(|argument| { argument.name == "tool" && argument.required != Some(true) }),
        "the defaulted tool argument must not stay required: {compose:?}"
    );

    let injected_prompt = client
        .get_prompt(
            "compose_greeting",
            HashMap::from([("name".to_owned(), "alpha".to_owned())]),
        )
        .expect("omitting defaulted prompt arguments must still compose echo and info://server");
    assert!(
        injected_prompt
            .messages
            .iter()
            .any(|message| match &message.content {
                ContentBlock::Text { text, .. } => {
                    text.starts_with("compose:alpha|") && text.contains("echo-server")
                }
                _ => false,
            }),
        "prompt defaults must inject echo and info://server: {injected_prompt:?}"
    );

    client
        .close()
        .expect("modern-only stdio default-parameter client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_output_schema_retains_structured_content_and_peer_stays_bare() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client completes live modern discovery");

    let listed = client
        .list_tools(None)
        .expect("live modern stdio must list the output-schema tools");
    let structured = listed
        .tools
        .iter()
        .find(|tool| tool.name == "structured_echo")
        .expect("structured_echo must remain on the live catalog");
    let echo = listed
        .tools
        .iter()
        .find(|tool| tool.name == "echo")
        .expect("the bare echo peer must remain on the live catalog");
    assert_eq!(
        structured
            .output_schema
            .as_ref()
            .and_then(|schema| schema.get("required")),
        Some(&json!(["value"])),
        "tools/list must retain the advertised output schema: {structured:?}"
    );
    assert_eq!(
        echo.output_schema, None,
        "changing only the missing output schema must keep the echo peer bare: {echo:?}"
    );

    let called = client
        .call_tool("structured_echo", json!({"value": "alpha"}))
        .expect("live modern stdio must admit the structured output tool");
    assert!(
        called.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => text == "tool:alpha",
            _ => false,
        }),
        "the structured tool must still author text content: {called:?}"
    );
    assert_eq!(
        called.structured_content,
        Some(json!({"value": "alpha"})),
        "tools/call must retain structuredContent matching the advertised schema: {called:?}"
    );

    let peer = client
        .call_tool("echo", json!({"message": "alpha"}))
        .expect("the bare echo peer must still be callable");
    assert_eq!(
        peer.structured_content, None,
        "changing only the missing output schema must not invent structuredContent: {peer:?}"
    );

    client
        .close()
        .expect("modern-only stdio output-schema client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_rich_content_retains_image_and_audio_blocks() {
    let mut client = connect_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client completes live modern discovery");

    let rich = client
        .call_tool("rich_echo", json!({}))
        .expect("live modern stdio must retain image and audio content blocks");
    assert!(
        rich.content.iter().any(|content| match content {
            ContentBlock::Image {
                data, mime_type, ..
            } => data == "e2eimage" && mime_type == "image/png",
            _ => false,
        }),
        "tools/call must retain the authored image block: {rich:?}"
    );
    assert!(
        rich.content.iter().any(|content| match content {
            ContentBlock::Audio {
                data, mime_type, ..
            } => data == "e2eaudio" && mime_type == "audio/wav",
            _ => false,
        }),
        "tools/call must retain the authored audio block: {rich:?}"
    );

    let peer = client
        .call_tool("echo", json!({"message": "alpha"}))
        .expect("the text-only echo peer must still be callable");
    assert!(
        peer.content
            .iter()
            .all(|content| matches!(content, ContentBlock::Text { .. })),
        "changing only the missing rich content must keep the echo peer text-only: {peer:?}"
    );

    client
        .close()
        .expect("modern-only stdio rich-content client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_progress_marker_is_retained_from_live_echo() {
    let mut client = connect_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client completes live modern discovery");

    client
        .call_tool("echo", json!({"message": "no-token"}))
        .expect("echo still completes without a progress token");
    assert!(
        client.take_progress_notifications().is_empty(),
        "without a progressToken the shipped echo tool must not emit request-scoped progress"
    );

    let marker = modern::ProgressMarker::from("stdio-progress");
    client
        .call_tool_with_progress_marker("echo", json!({"message": "token"}), marker.clone())
        .expect("a progressToken must not prevent the shipped echo tool from completing");
    let progress = client.take_progress_notifications();
    assert!(
        progress.iter().any(|notification| {
            notification.progress_token == marker
                && notification.message.as_deref() == Some("echoed")
        }),
        "live stdio must retain notifications/progress after a progressToken: {progress:?}"
    );
    assert!(
        client.take_progress_notifications().is_empty(),
        "take_progress_notifications must drain the retained queue"
    );

    client
        .read_resource("info://server")
        .expect("a resources/read without a progress token still completes");
    assert!(
        client.take_progress_notifications().is_empty(),
        "without a progressToken the shipped server_info resource must not emit request-scoped progress"
    );

    let resource_marker = modern::ProgressMarker::from("stdio-resource-progress");
    client
        .read_resource_with_progress_marker("info://server", resource_marker.clone())
        .expect(
            "a progressToken must not prevent the shipped server_info resource from completing",
        );
    let resource_progress = client.take_progress_notifications();
    assert!(
        resource_progress.iter().any(|notification| {
            notification.progress_token == resource_marker
                && notification.message.as_deref() == Some("info")
        }),
        "live stdio must retain resource notifications/progress after a progressToken: {resource_progress:?}"
    );

    let mut greeting_arguments = std::collections::HashMap::new();
    greeting_arguments.insert("name".to_owned(), "no-token".to_owned());
    client
        .get_prompt("greeting", greeting_arguments)
        .expect("a prompts/get without a progress token still completes");
    assert!(
        client.take_progress_notifications().is_empty(),
        "without a progressToken the shipped greeting prompt must not emit request-scoped progress"
    );

    let prompt_marker = modern::ProgressMarker::from("stdio-prompt-progress");
    let mut greeting_with_token = std::collections::HashMap::new();
    greeting_with_token.insert("name".to_owned(), "token".to_owned());
    client
        .get_prompt_with_progress_marker("greeting", greeting_with_token, prompt_marker.clone())
        .expect("a progressToken must not prevent the shipped greeting prompt from completing");
    let prompt_progress = client.take_progress_notifications();
    assert!(
        prompt_progress.iter().any(|notification| {
            notification.progress_token == prompt_marker
                && notification.message.as_deref() == Some("greeted")
        }),
        "live stdio must retain prompt notifications/progress after a progressToken: {prompt_progress:?}"
    );
    assert!(
        client.take_progress_notifications().is_empty(),
        "take_progress_notifications must drain the retained resource and prompt queues"
    );
    client
        .close()
        .expect("modern-only stdio progress client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_resource_updated_is_retained_on_incremental_listen() {
    let mut client = connect_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client completes live modern discovery");

    client
        .open_subscriptions_listener(modern::SubscriptionFilter {
            resource_subscriptions: Some(vec!["info://server".to_owned()]),
            ..modern::SubscriptionFilter::default()
        })
        .expect("live stdio must admit an incremental subscriptions/listen");

    let cx = Cx::for_request();
    let cancellation = modern::McpRequestCancellation::new();
    let acknowledgement = client
        .next_subscription_event(&cx, &cancellation)
        .expect("subscriptions/listen must emit its acknowledgement");
    assert!(
        matches!(
            acknowledgement,
            modern::StdioSubscriptionEvent::Acknowledged(ref filter)
                if filter.resource_subscriptions.as_deref() == Some(&["info://server".to_owned()][..])
        ),
        "the first incremental listen record must be the accepted filter: {acknowledgement:?}"
    );

    let touched = client
        .call_tool("touch_server_info", json!({}))
        .expect("touching the watched resource must complete");
    assert!(
        touched.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => text == "notified",
            _ => false,
        }),
        "a matching incremental listener must count as notify_resource_updated delivery: {touched:?}"
    );

    let updated = client
        .next_subscription_event(&cx, &cancellation)
        .expect("subscriptions/listen must retain resources/updated after the handler publish");
    assert!(
        matches!(
            updated,
            modern::StdioSubscriptionEvent::Notification(
                modern::ServerNotification::ResourceUpdated(ref params)
            ) if params.uri.as_str() == "info://server"
        ),
        "live stdio must retain notifications/resources/updated on the incremental listener: {updated:?}"
    );
    client
        .close()
        .expect("modern-only stdio subscription client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_tools_list_changed_is_retained_on_incremental_listen() {
    let mut client = connect_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client completes live modern discovery");

    client
        .open_subscriptions_listener(modern::SubscriptionFilter {
            tools_list_changed: Some(true),
            ..modern::SubscriptionFilter::default()
        })
        .expect("live stdio must admit an incremental subscriptions/listen");

    let cx = Cx::for_request();
    let cancellation = modern::McpRequestCancellation::new();
    let acknowledgement = client
        .next_subscription_event(&cx, &cancellation)
        .expect("subscriptions/listen must emit its acknowledgement");
    assert!(
        matches!(
            acknowledgement,
            modern::StdioSubscriptionEvent::Acknowledged(ref filter)
                if filter.tools_list_changed == Some(true)
        ),
        "the first incremental listen record must be the accepted filter: {acknowledgement:?}"
    );

    let hidden = client
        .call_tool("hide_echo", json!({}))
        .expect("disabling the shipped echo tool must complete");
    assert!(
        hidden.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => text == "hidden",
            _ => false,
        }),
        "stdio session state must let disable_tool publish list_changed: {hidden:?}"
    );

    let changed = client
        .next_subscription_event(&cx, &cancellation)
        .expect("subscriptions/listen must retain tools/list_changed after the handler mutation");
    assert!(
        matches!(
            changed,
            modern::StdioSubscriptionEvent::Notification(
                modern::ServerNotification::ToolsListChanged(_)
            )
        ),
        "live stdio must retain notifications/tools/list_changed on the incremental listener: {changed:?}"
    );
    client
        .close()
        .expect("modern-only stdio list_changed client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_hide_echo_refuses_later_call_and_show_restores() {
    let mut client = connect_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client connects to the shipped echo server");

    let before = client
        .call_tool("echo", json!({"message": "alpha"}))
        .expect("the shipped echo tool must be callable before hide_echo");
    assert!(
        before.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => text.contains("alpha"),
            _ => false,
        }),
        "the live modern stdio echo must retain the handler text: {before:?}"
    );

    let hidden = client
        .call_tool("hide_echo", json!({}))
        .expect("disabling the shipped echo tool must complete");
    assert!(
        hidden.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => text == "hidden",
            _ => false,
        }),
        "modern stdio session state must retain disable_tool: {hidden:?}"
    );

    let disabled = client.call_tool("echo", json!({"message": "beta"}));
    let disabled = match disabled {
        Ok(result) => {
            assert!(
                result.is_error,
                "hide_echo must turn a later echo call into a tool-level error: {result:?}"
            );
            format!("{result:?}")
        }
        Err(error) => format!("{error:?}"),
    };
    assert!(
        disabled.contains("disabled")
            || disabled.contains("echo")
            || disabled.contains("Method not found")
            || disabled.contains("MethodNotFound"),
        "the refused echo call must name the session-disabled tool: {disabled}"
    );

    let peer = client
        .call_tool("add", json!({"a": 2, "b": 3}))
        .expect("changing only the missing hide must keep an undisabled tool callable");
    assert!(
        peer.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => text.contains('5'),
            _ => false,
        }),
        "an undisabled peer tool must still complete after hide_echo: {peer:?}"
    );

    let shown = client
        .call_tool("show_echo", json!({}))
        .expect("re-enabling the shipped echo tool must complete");
    assert!(
        shown.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => text == "shown",
            _ => false,
        }),
        "modern stdio session state must retain enable_tool: {shown:?}"
    );
    let restored = client
        .call_tool("echo", json!({"message": "gamma"}))
        .expect("show_echo must restore a later echo call on the same modern session");
    assert!(
        restored.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => text.contains("gamma"),
            _ => false,
        }),
        "the restored modern stdio echo must retain the handler text: {restored:?}"
    );

    client
        .close()
        .expect("modern-only stdio hide_echo client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_resource_and_prompt_list_changed_are_retained_on_incremental_listen() {
    let mut client = connect_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client completes live modern discovery");

    client
        .open_subscriptions_listener(modern::SubscriptionFilter {
            resources_list_changed: Some(true),
            prompts_list_changed: Some(true),
            ..modern::SubscriptionFilter::default()
        })
        .expect("live stdio must admit an incremental subscriptions/listen");

    let cx = Cx::for_request();
    let cancellation = modern::McpRequestCancellation::new();
    let acknowledgement = client
        .next_subscription_event(&cx, &cancellation)
        .expect("subscriptions/listen must emit its acknowledgement");
    assert!(
        matches!(
            acknowledgement,
            modern::StdioSubscriptionEvent::Acknowledged(ref filter)
                if filter.resources_list_changed == Some(true)
                    && filter.prompts_list_changed == Some(true)
        ),
        "the first incremental listen record must be the accepted filter: {acknowledgement:?}"
    );

    let hidden = client
        .call_tool("hide_catalog", json!({}))
        .expect("disabling a shipped resource and prompt must complete");
    assert!(
        hidden.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => text == "hidden",
            _ => false,
        }),
        "stdio session state must let disable_resource and disable_prompt publish: {hidden:?}"
    );

    let first = client
        .next_subscription_event(&cx, &cancellation)
        .expect("subscriptions/listen must retain the first catalog mutation");
    let second = client
        .next_subscription_event(&cx, &cancellation)
        .expect("subscriptions/listen must retain the second catalog mutation");
    let kinds = [first, second];
    assert!(
        kinds.iter().any(|event| matches!(
            event,
            modern::StdioSubscriptionEvent::Notification(
                modern::ServerNotification::ResourcesListChanged(_)
            )
        )),
        "live stdio must retain notifications/resources/list_changed: {kinds:?}"
    );
    assert!(
        kinds.iter().any(|event| matches!(
            event,
            modern::StdioSubscriptionEvent::Notification(
                modern::ServerNotification::PromptsListChanged(_)
            )
        )),
        "live stdio must retain notifications/prompts/list_changed: {kinds:?}"
    );
    client
        .close()
        .expect("modern-only stdio catalog list_changed client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_ctx_info_is_retained_after_set_log_level() {
    let mut client = connect_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client completes live modern discovery");

    client
        .set_log_level(modern::LoggingLevel::Info)
        .expect("info logLevel is stored as request metadata");
    client
        .call_tool("echo", json!({"message": "log"}))
        .expect("ctx.info must not prevent the shipped echo tool from completing");
    let info_notifications = client.take_server_notifications();
    assert!(
        info_notifications.iter().any(|notification| matches!(
            notification,
            modern::ServerNotification::Message(message)
                if message.level == modern::LoggingLevel::Info
                    && message.data == json!("echo-handler-info")
        )),
        "live stdio must retain ctx.info after set_log_level(Info): {info_notifications:?}"
    );

    client
        .set_log_level(modern::LoggingLevel::Emergency)
        .expect("emergency logLevel still stores request metadata locally");
    client
        .call_tool("echo", json!({"message": "quiet"}))
        .expect("raising only the logLevel floor cannot break the shipped echo tool");
    let emergency_notifications = client.take_server_notifications();
    assert!(
        !emergency_notifications.iter().any(|notification| matches!(
            notification,
            modern::ServerNotification::Message(message)
                if message.data == json!("echo-handler-info")
        )),
        "raising only the logLevel floor must suppress ctx.info: {emergency_notifications:?}"
    );
    client
        .close()
        .expect("modern-only stdio log client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_completion_returns_typed_result_and_rejects_undeclared_argument() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client completes live modern discovery");
    let params = modern::CompletionParams {
        reference: modern::CompletionReference::PromptWithTitle {
            name: "greeting".to_owned(),
            title: "Greeting".to_owned(),
        },
        argument: modern::FinalCompletionArgument {
            name: "name".to_owned(),
            value: "co".to_owned(),
        },
        context: Some(modern::FinalCompletionContext {
            arguments: Some(std::collections::BTreeMap::from([(
                "locale".to_owned(),
                "en-US".to_owned(),
            )])),
        }),
    };

    let completion_started = Instant::now();
    client
        .complete(params.clone())
        .expect("a completion/complete without a progress token still completes");
    assert!(
        client.take_progress_notifications().is_empty(),
        "without a progressToken the shipped completion handler must not emit request-scoped progress"
    );
    let marker = modern::ProgressMarker::from("stdio-completion-progress");
    let result = client
        .complete_with_progress_marker(params.clone(), marker.clone())
        .expect("the typed ModernOnly client reaches the shipped completion provider");
    assert!(
        completion_started.elapsed() <= STDIO_COMPLETION_ABSOLUTE_TIMEOUT,
        "the positive completion finishes within its explicit public-client absolute bound"
    );
    assert_eq!(
        result.completion.values,
        vec!["stdio-completion-2".to_owned()],
        "the exact FinalCompletionResult retains the provider value and count"
    );
    let progress = client.take_progress_notifications();
    assert!(
        progress.iter().any(|notification| {
            notification.progress_token == marker
                && notification.message.as_deref() == Some("stdio-completion-halfway")
        }),
        "live shipped-echo stdio must retain completion notifications/progress: {progress:?}"
    );
    assert_eq!(
        result.completion.total,
        Some(modern::JsonInteger::from(2_i64)),
        "the exact FinalCompletionResult retains its JSON-integer count"
    );
    assert_eq!(
        result.completion.has_more,
        Some(false),
        "the exact FinalCompletionResult retains the terminal pagination flag"
    );

    // RH-5 near-negative: retain the target, title, prefix, and context,
    // changing only the completion argument name. Router validation must
    // reject before the shipped provider can increment its process-local count.
    let mut undeclared_argument = params.clone();
    undeclared_argument.argument.name = "undeclared".to_owned();
    let error = client
        .complete(undeclared_argument)
        .expect_err("only an undeclared completion argument is rejected");
    assert_eq!(error.code, McpErrorCode::InvalidParams);

    let resumed = client
        .complete(params)
        .expect("the rejected request leaves the live modern client and provider usable");
    assert_eq!(
        resumed.completion.values,
        vec!["stdio-completion-3".to_owned()],
        "the next accepted completion proves the rejected argument did not invoke the provider"
    );
    assert_eq!(
        resumed.completion.total,
        Some(modern::JsonInteger::from(3_i64)),
        "the provider count advances only for the three accepted completions"
    );
    assert_eq!(resumed.completion.has_more, Some(false));
    let cleanup_started = Instant::now();
    client
        .close()
        .expect("modern completion stdio client cleanup and child reap");
    assert!(
        cleanup_started.elapsed() <= STDIO_COMPLETION_CLEANUP_BOUND,
        "the public close confirms bounded stdio child cleanup and reap"
    );
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_resource_template_completion_is_retained_and_unregistered_template_is_refused()
 {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client completes live modern discovery");
    let params = modern::CompletionParams {
        reference: modern::CompletionReference::Resource {
            uri: "note://{name}".to_owned(),
        },
        argument: modern::FinalCompletionArgument {
            name: "name".to_owned(),
            value: "al".to_owned(),
        },
        context: None,
    };

    let result = client
        .complete(params.clone())
        .expect("the typed ModernOnly client reaches the shipped note template provider");
    assert_eq!(
        result.completion.values,
        vec!["alice".to_owned()],
        "the exact FinalCompletionResult retains the note template provider value: {result:?}"
    );
    assert_eq!(
        result.completion.total,
        Some(modern::JsonInteger::from(1_i64))
    );
    assert_eq!(result.completion.has_more, Some(false));

    let mut undeclared_argument = params.clone();
    undeclared_argument.argument.name = "undeclared".to_owned();
    let undeclared = client
        .complete(undeclared_argument)
        .expect_err("only an undeclared template variable is rejected");
    assert_eq!(undeclared.code, McpErrorCode::InvalidParams);

    let mut other_template = params;
    other_template.reference = modern::CompletionReference::Resource {
        uri: "memo://{name}".to_owned(),
    };
    let missing_provider = client
        .complete(other_template)
        .expect_err("changing only the template URI must refuse a missing provider");
    assert_eq!(missing_provider.code, McpErrorCode::InvalidParams);

    let greeting = client
        .complete(modern::CompletionParams {
            reference: modern::CompletionReference::PromptWithTitle {
                name: "greeting".to_owned(),
                title: "Greeting".to_owned(),
            },
            argument: modern::FinalCompletionArgument {
                name: "name".to_owned(),
                value: "co".to_owned(),
            },
            context: Some(modern::FinalCompletionContext {
                arguments: Some(std::collections::BTreeMap::from([(
                    "locale".to_owned(),
                    "en-US".to_owned(),
                )])),
            }),
        })
        .expect("the note provider must leave the greeting prompt provider usable");
    assert!(
        greeting
            .completion
            .values
            .first()
            .is_some_and(|value| value.starts_with("stdio-completion-")),
        "the greeting provider must still complete after note template completion: {greeting:?}"
    );

    client
        .close()
        .expect("modern note-completion stdio client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_result_verbs_keep_live_input_required() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client observes live stdio input_required");
    let pending_resource = client
        .read_resource_result("info://mrtr-resource")
        .expect("live stdio resources/read must keep a typed result");
    let modern::FinalCoreResult::ResourcesReadInputRequired { result, .. } = pending_resource
    else {
        panic!("live stdio resources/read must keep input_required: {pending_resource:?}");
    };
    assert!(
        result.request_state().is_some(),
        "stdio resource MRTR must return framework-issued requestState"
    );
    assert!(
        result
            .input_requests()
            .is_some_and(|requests| requests.get("roots").is_some()),
        "stdio resource MRTR must retain its roots input request"
    );
    let pending_prompt = client
        .get_prompt_result(
            "mrtr_prompt",
            HashMap::from([("mode".to_owned(), "terminal".to_owned())]),
        )
        .expect("live stdio prompts/get must keep a typed result");
    let modern::FinalCoreResult::PromptsGetInputRequired { result, .. } = pending_prompt else {
        panic!("live stdio prompts/get must keep input_required: {pending_prompt:?}");
    };
    assert!(
        result.request_state().is_some(),
        "stdio prompt MRTR must return framework-issued requestState"
    );
    assert!(
        result
            .input_requests()
            .is_some_and(|requests| requests.get("roots").is_some()),
        "stdio prompt MRTR must retain its roots input request"
    );
    client
        .close()
        .expect("stdio result-verb client cleanup reaps the live subprocess");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_read_resource_and_get_prompt_follow_installed_roots_handler() {
    let mut client = modern::client_builder()
        .env("FASTMCP_PROTOCOL_POLICY", "modern-only")
        .request_timeout_policy(
            RequestTimeoutPolicy::new(
                STDIO_COMPLETION_IDLE_TIMEOUT,
                STDIO_COMPLETION_ABSOLUTE_TIMEOUT,
            )
            .expect("the public follow timeout policy is valid"),
        )
        .modern_reverse_request_handlers(
            modern::ReverseRequestHandlers::new().with_modern_roots_list(
                |_cx, _cancellation, _params| {
                    Box::pin(async { Ok(modern::FinalEmbeddedRootsListResult { roots: vec![] }) })
                },
            ),
        )
        .connect_stdio_with_cx(shipped_echo_server_executable(), &[], &Cx::for_request())
        .expect("a ModernOnly facade client installs a roots handler before discovery");

    let resource = client
        .read_resource("info://mrtr-resource")
        .expect("public stdio read_resource follows the installed roots handler");
    assert_eq!(resource.ttl_ms, CacheTtl::milliseconds(7));
    assert_eq!(resource.cache_scope, CacheScope::Private);

    let prompt = client
        .get_prompt(
            "mrtr_prompt",
            HashMap::from([("mode".to_owned(), "terminal".to_owned())]),
        )
        .expect("public stdio get_prompt follows the installed roots handler");
    assert_eq!(
        prompt.description.as_deref(),
        Some("typed MRTR prompt result")
    );
    client
        .close()
        .expect("stdio follow-handler client cleanup reaps the live subprocess");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_sampling_elicitation_keep_input_required() {
    let mut client = connect_bounded_modern_stdio_with_mrtr(
        "modern-only",
        stdio_mrtr_capabilities(true, true, true, true),
        modern::ReverseRequestHandlers::new(),
    )
    .expect("a ModernOnly facade client advertises sampling, roots, and elicitation");

    let sampling = client
        .call_tool_result("sample_echo", json!({}))
        .expect("live stdio ctx.final_sampling must return a typed tools/call result");
    let modern::FinalCoreResult::ToolsCallInputRequired { result, .. } = sampling else {
        panic!("live stdio final sampling must keep input_required: {sampling:?}");
    };
    assert_stdio_input_required(&result, "sample", "tools/call sampling");

    let roots = client
        .call_tool_result("roots_echo", json!({}))
        .expect("live stdio ctx.final_roots must return a typed tools/call result");
    let modern::FinalCoreResult::ToolsCallInputRequired { result, .. } = roots else {
        panic!("live stdio final roots must keep input_required: {roots:?}");
    };
    assert_stdio_input_required(&result, "roots", "tools/call roots");

    let url = client
        .call_tool_result("url_elicit_echo", json!({}))
        .expect("live stdio ctx.final_elicitation_url must return a typed tools/call result");
    let modern::FinalCoreResult::ToolsCallInputRequired { result, .. } = url else {
        panic!("live stdio final URL elicitation must keep input_required: {url:?}");
    };
    assert_stdio_input_required(&result, "approval", "tools/call URL elicitation");

    let resource = client
        .read_resource_result("info://elicit-form")
        .expect("live stdio form elicitation resource must return a typed result");
    let modern::FinalCoreResult::ResourcesReadInputRequired { result, .. } = resource else {
        panic!("live stdio resource form elicitation must keep input_required: {resource:?}");
    };
    assert_stdio_input_required(&result, "approval", "resources/read form elicitation");

    let prompt = client
        .get_prompt_result("elicit_form_greeting", HashMap::new())
        .expect("live stdio form elicitation prompt must return a typed result");
    let modern::FinalCoreResult::PromptsGetInputRequired { result, .. } = prompt else {
        panic!("live stdio prompt form elicitation must keep input_required: {prompt:?}");
    };
    assert_stdio_input_required(&result, "approval", "prompts/get form elicitation");
    client
        .close()
        .expect("stdio input_required MRTR client cleanup reaps the live subprocess");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_sampling_elicitation_fail_closed_without_capability() {
    let mut no_sampling = connect_bounded_modern_stdio_with_mrtr(
        "modern-only",
        stdio_mrtr_capabilities(false, true, true, true),
        modern::ReverseRequestHandlers::new(),
    )
    .expect("a ModernOnly facade client connects without advertising sampling");
    let missing_sampling = no_sampling
        .call_tool_result("sample_echo", json!({}))
        .expect("missing sampling capability must still return a typed tools/call result");
    assert_stdio_capability_gate(&missing_sampling, "sampling");
    no_sampling
        .close()
        .expect("stdio no-sampling client cleanup reaps the live subprocess");

    let mut no_url = connect_bounded_modern_stdio_with_mrtr(
        "modern-only",
        stdio_mrtr_capabilities(true, true, true, false),
        modern::ReverseRequestHandlers::new(),
    )
    .expect("a ModernOnly facade client connects without advertising URL elicitation");
    let missing_url = no_url
        .call_tool_result("url_elicit_echo", json!({}))
        .expect("missing URL elicitation capability must still return a typed tools/call result");
    assert_stdio_capability_gate(&missing_url, "URL elicitation");
    no_url
        .close()
        .expect("stdio no-url-elicitation client cleanup reaps the live subprocess");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_sampling_elicitation_follow_installed_handlers() {
    let handlers = modern::ReverseRequestHandlers::new()
        .with_modern_sampling_create_message(|_cx, _cancellation, _params| {
            Box::pin(async {
                Ok(modern::FinalCreateMessageResult {
                    content: modern::FinalSamplingMessageContent::Block(
                        modern::FinalSamplingMessageContentBlock::Text {
                            text: "sampled".to_owned(),
                            annotations: None,
                            meta: None,
                            additional: std::collections::BTreeMap::new(),
                        },
                    ),
                    model: "stdio-sample-model".to_owned(),
                    role: Role::Assistant,
                    stop_reason: None,
                    meta: None,
                })
            })
        })
        .with_modern_roots_list(|_cx, _cancellation, _params| {
            Box::pin(async { Ok(modern::FinalEmbeddedRootsListResult { roots: vec![] }) })
        })
        .with_modern_elicitation_create(|_cx, _cancellation, params| {
            Box::pin(async move {
                Ok(match params {
                    fastmcp_protocol::ElicitRequestParams::Url(_) => {
                        fastmcp_protocol::ElicitResult::accept_url()
                    }
                    fastmcp_protocol::ElicitRequestParams::Form(_) => {
                        fastmcp_protocol::ElicitResult::accept(HashMap::from([(
                            "approved".to_owned(),
                            fastmcp_protocol::ElicitContentValue::Bool(true),
                        )]))
                    }
                })
            })
        });
    let mut client = connect_bounded_modern_stdio_with_mrtr(
        "modern-only",
        stdio_mrtr_capabilities(true, true, true, true),
        handlers,
    )
    .expect("a ModernOnly facade client installs sampling, roots, and elicitation handlers");

    let sampled = client
        .call_tool("sample_echo", json!({}))
        .expect("public stdio call_tool follows the installed sampling handler");
    assert!(
        sampled.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => text == "sampled:stdio-sample-model",
            _ => false,
        }),
        "the sampling retry must complete from the installed handler: {sampled:?}"
    );

    let roots = client
        .call_tool("roots_echo", json!({}))
        .expect("public stdio call_tool follows the installed roots handler");
    assert!(
        roots.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => text == "roots:0",
            _ => false,
        }),
        "the roots retry must complete from the installed handler: {roots:?}"
    );

    let url = client
        .call_tool("url_elicit_echo", json!({}))
        .expect("public stdio call_tool follows the installed URL elicitation handler");
    assert!(
        url.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => text == "url-elicit:accept",
            _ => false,
        }),
        "the URL elicitation retry must complete from the installed handler: {url:?}"
    );

    let resource = client
        .read_resource("info://elicit-form")
        .expect("public stdio read_resource follows the installed form elicitation handler");
    assert!(
        resource.contents.iter().any(|content| match content {
            EmbeddedResourceContents::Text { text, .. } => text == "form-elicit:true",
            _ => false,
        }),
        "the form elicitation resource retry must complete from the installed handler: {resource:?}"
    );

    let prompt = client
        .get_prompt("elicit_form_greeting", HashMap::new())
        .expect("public stdio get_prompt follows the installed form elicitation handler");
    assert!(
        prompt
            .messages
            .iter()
            .any(|message| match &message.content {
                ContentBlock::Text { text, .. } => text == "form-elicit:true",
                _ => false,
            }),
        "the form elicitation prompt retry must complete from the installed handler: {prompt:?}"
    );

    client
        .close()
        .expect("stdio follow-handler MRTR client cleanup reaps the live subprocess");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_typed_verbs_honor_pre_send_cancellation() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client connects before pre-send cancellation");
    let cx = Cx::for_request();
    let cancellation = fastmcp_rust::McpRequestCancellation::new();
    cancellation.cancel();
    let list = client
        .list_tools_with_cancellation(&cx, &cancellation, None)
        .expect_err("pre-send list_tools cancellation must reject locally");
    assert_eq!(list.code, McpErrorCode::RequestCancelled);
    let resources = client
        .list_resources_with_cancellation(&cx, &cancellation, None)
        .expect_err("pre-send list_resources cancellation must reject locally");
    assert_eq!(resources.code, McpErrorCode::RequestCancelled);
    let templates = client
        .list_resource_templates_with_cancellation(&cx, &cancellation, None)
        .expect_err("pre-send list_resource_templates cancellation must reject locally");
    assert_eq!(templates.code, McpErrorCode::RequestCancelled);
    let prompts = client
        .list_prompts_with_cancellation(&cx, &cancellation, None)
        .expect_err("pre-send list_prompts cancellation must reject locally");
    assert_eq!(prompts.code, McpErrorCode::RequestCancelled);
    let call = client
        .call_tool_with_cancellation(&cx, &cancellation, "echo", json!({"message": "hi"}))
        .expect_err("pre-send call_tool cancellation must reject locally");
    assert_eq!(call.code, McpErrorCode::RequestCancelled);
    let resource = client
        .read_resource_with_cancellation(&cx, &cancellation, "info://mrtr-resource")
        .expect_err("pre-send read_resource cancellation must reject locally");
    assert_eq!(resource.code, McpErrorCode::RequestCancelled);
    let prompt = client
        .get_prompt_with_cancellation(
            &cx,
            &cancellation,
            "mrtr_prompt",
            HashMap::from([("mode".to_owned(), "terminal".to_owned())]),
        )
        .expect_err("pre-send get_prompt cancellation must reject locally");
    assert_eq!(prompt.code, McpErrorCode::RequestCancelled);
    let completion = client
        .complete_with_cancellation(
            &cx,
            &cancellation,
            modern::CompletionParams {
                reference: modern::CompletionReference::PromptWithTitle {
                    name: "greeting".to_owned(),
                    title: "Greeting".to_owned(),
                },
                argument: modern::FinalCompletionArgument {
                    name: "name".to_owned(),
                    value: "co".to_owned(),
                },
                context: None,
            },
        )
        .expect_err("pre-send complete cancellation must reject locally");
    assert_eq!(completion.code, McpErrorCode::RequestCancelled);
    let ping = client
        .ping_with_cancellation(&cx, &cancellation)
        .expect_err("pre-send ping cancellation must reject locally");
    assert_eq!(ping.code, McpErrorCode::RequestCancelled);
    client
        .ping()
        .expect("modern stdio ping remains usable after local cancellation");
    client
        .list_tools(None)
        .expect("the same stdio session remains usable after local cancellation");
    client
        .close()
        .expect("stdio pre-send cancellation client cleanup reaps the live subprocess");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_typed_verbs_honor_pre_send_cancellation() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client connects before pre-send cancellation");
    let cx = Cx::for_request();
    let cancellation = fastmcp_rust::McpRequestCancellation::new();
    cancellation.cancel();
    let list = client
        .list_tools_with_cancellation(&cx, &cancellation, None)
        .expect_err("pre-send list_tools cancellation must reject locally");
    assert_eq!(list.code, McpErrorCode::RequestCancelled);
    let tagged = client
        .list_tools_with_params_and_cancellation(
            &cx,
            &cancellation,
            ListToolsParams {
                include_tags: Some(vec!["demo".to_owned()]),
                ..ListToolsParams::default()
            },
        )
        .expect_err("pre-send tagged list_tools cancellation must reject locally");
    assert_eq!(tagged.code, McpErrorCode::RequestCancelled);
    let resources = client
        .list_resources_with_cancellation(&cx, &cancellation, None)
        .expect_err("pre-send list_resources cancellation must reject locally");
    assert_eq!(resources.code, McpErrorCode::RequestCancelled);
    let templates = client
        .list_resource_templates_with_cancellation(&cx, &cancellation, None)
        .expect_err("pre-send list_resource_templates cancellation must reject locally");
    assert_eq!(templates.code, McpErrorCode::RequestCancelled);
    let prompts = client
        .list_prompts_with_cancellation(&cx, &cancellation, None)
        .expect_err("pre-send list_prompts cancellation must reject locally");
    assert_eq!(prompts.code, McpErrorCode::RequestCancelled);
    let call = client
        .call_tool_with_cancellation(&cx, &cancellation, "echo", json!({"message": "hi"}))
        .expect_err("pre-send call_tool cancellation must reject locally");
    assert_eq!(call.code, McpErrorCode::RequestCancelled);
    let resource = client
        .read_resource_with_cancellation(&cx, &cancellation, "info://server")
        .expect_err("pre-send read_resource cancellation must reject locally");
    assert_eq!(resource.code, McpErrorCode::RequestCancelled);
    let prompt = client
        .get_prompt_with_cancellation(&cx, &cancellation, "greeting", HashMap::new())
        .expect_err("pre-send get_prompt cancellation must reject locally");
    assert_eq!(prompt.code, McpErrorCode::RequestCancelled);
    let completion = client
        .complete_with_cancellation(
            &cx,
            &cancellation,
            legacy_2024::LegacyCompletionParams {
                reference: legacy_2024::LegacyCompletionReference::Prompt {
                    name: "greeting".to_owned(),
                },
                argument: legacy_2024::LegacyCompletionArgument {
                    name: "name".to_owned(),
                    value: "co".to_owned(),
                },
                meta: None,
            },
        )
        .expect_err("pre-send complete cancellation must reject locally");
    assert_eq!(completion.code, McpErrorCode::RequestCancelled);
    let ping = client
        .ping_with_cancellation(&cx, &cancellation)
        .expect_err("pre-send ping cancellation must reject locally");
    assert_eq!(ping.code, McpErrorCode::RequestCancelled);

    let admitted = fastmcp_rust::McpRequestCancellation::new();
    let echoed = client
        .call_tool_with_cancellation(&cx, &admitted, "echo", json!({"message": "hi"}))
        .expect("an uncancelled exact-2024 tools/call still reaches the handler");
    assert!(matches!(
        echoed.content.first(),
        Some(LegacyContent::Text { text, .. }) if text == "hi"
    ));
    client
        .ping()
        .expect("exact-2024 stdio ping remains usable after local cancellation");
    client
        .list_tools()
        .expect("the same exact-2024 stdio session remains usable after local cancellation");
    client
        .close()
        .expect("exact-2024 stdio pre-send cancellation client cleanup reaps the live subprocess");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_executor_execute_stamps_modern_meta() {
    let mut client = connect_auto_stdio_to_shipped_echo_server("modern-only");
    assert_eq!(
        client.selected_protocol_era(),
        Some(ProtocolEra::Modern2026)
    );
    let cx = Cx::for_request();
    let executor = client
        .multiplexed_stdio_executor()
        .expect("a negotiated modern stdio session exposes the shared executor");
    let mut listed = executor
        .execute(&cx, "tools/list", Some(json!({})))
        .expect("a cloned executor stamps modern _meta before tools/list");
    let listed = client
        .wait_multiplexed_request(&cx, &mut listed)
        .expect("undecorated tools/list params are admitted after executor stamping");
    assert!(
        listed.error.is_none(),
        "executor-stamped tools/list must not be an era refusal: {listed:?}"
    );
    assert_eq!(
        listed
            .result
            .as_ref()
            .and_then(|result| result.get("resultType")),
        Some(&json!("complete"))
    );

    let refused = executor
        .execute(&cx, "tools/list", Some(json!("not-an-object")))
        .expect_err("modern execute rejects a non-object body before send");
    assert_eq!(refused.code, McpErrorCode::InvalidParams);
    assert!(
        refused.message.contains("object parameters"),
        "only the parameter shape is refused: {refused:?}"
    );
    client
        .list_tools_typed(None)
        .expect("the same stdio session remains usable after the local parameter refusal");
    client
        .close()
        .expect("stdio executor-stamp client cleanup reaps the live subprocess");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_final_resource_keeps_authored_cache_ttl() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client completes live modern discovery");
    let resource = client
        .read_resource_with_mrtr_retry("info://mrtr-resource", |_| {
            Ok(std::collections::BTreeMap::from([(
                "roots".to_owned(),
                json!({"roots": []}),
            )]))
        })
        .expect("the public modern facade resumes the shipped resource with typed roots");
    let modern::FinalCoreResult::ResourcesRead { result, .. } = resource else {
        panic!("the resumed resource returns the exact FinalReadResourceResult branch");
    };
    assert_eq!(result.payload.ttl_ms, CacheTtl::milliseconds(7));
    assert_eq!(result.payload.cache_scope, CacheScope::Private);
    client
        .close()
        .expect("stdio cache-ttl client cleanup reaps the live subprocess");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_resource_and_prompt_mrtr_are_typed_and_bounded() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client completes live modern discovery");

    let operation_started = Instant::now();
    let resource = client
        .read_resource_with_mrtr_retry("info://mrtr-resource", |_| {
            Ok(std::collections::BTreeMap::from([(
                "roots".to_owned(),
                json!({"roots": []}),
            )]))
        })
        .expect("the public modern facade resumes the shipped resource with typed roots");
    let modern::FinalCoreResult::ResourcesRead { result, .. } = resource else {
        panic!("the resumed resource returns the exact FinalReadResourceResult branch");
    };
    assert_eq!(result.payload.ttl_ms, CacheTtl::milliseconds(7));
    assert_eq!(result.payload.cache_scope, CacheScope::Private);
    let [
        EmbeddedResourceContents::Text {
            uri,
            text,
            mime_type,
            meta,
            additional,
        },
    ] = result.payload.contents.as_slice()
    else {
        panic!("the final resource result contains one exact text resource");
    };
    assert_eq!(uri.as_str(), "info://mrtr-resource/result");
    assert_eq!(text, "typed resource roots=0");
    assert_eq!(mime_type.as_deref(), Some("text/plain"));
    assert!(meta.is_none());
    assert!(additional.is_empty());

    let prompt = client
        .get_prompt_with_mrtr_retry(
            "mrtr_prompt",
            HashMap::from([("mode".to_owned(), "terminal".to_owned())]),
            |_| {
                Ok(std::collections::BTreeMap::from([(
                    "roots".to_owned(),
                    json!({"roots": []}),
                )]))
            },
        )
        .expect("the public modern facade resumes the shipped prompt with typed roots");
    let modern::FinalCoreResult::PromptsGet { result, .. } = prompt else {
        panic!("the resumed prompt returns the exact FinalGetPromptResult branch");
    };
    assert_eq!(
        result.payload.description.as_deref(),
        Some("typed MRTR prompt result")
    );
    let [message] = result.payload.messages.as_slice() else {
        panic!("the final prompt result contains one exact final message");
    };
    assert_eq!(message.role, Role::Assistant);
    assert!(matches!(
        &message.content,
        ContentBlock::Text {
            text,
            annotations: None,
            meta: None,
            additional,
        } if text == "typed prompt roots=0" && additional.is_empty()
    ));
    assert!(
        operation_started.elapsed() <= STDIO_COMPLETION_ABSOLUTE_TIMEOUT,
        "both typed public MRTR completions finish within the explicit absolute bound"
    );

    // RH-5: keep the method, URI, issued state, and typed roots response;
    // changing only requestState must reject without consuming the registry
    // entry, so the originally issued state still completes below.
    let mut raw = connect_auto_stdio_to_shipped_echo_server("modern-only");
    assert_eq!(raw.selected_protocol_era(), Some(ProtocolEra::Modern2026));
    let initial = selected_modern_stdio_raw_result(
        &mut raw,
        "resources/read",
        json!({"uri": "info://mrtr-resource"}),
    );
    assert_eq!(initial["resultType"], "input_required");
    assert_eq!(
        initial["inputRequests"],
        json!({"roots": {"method": "roots/list"}})
    );
    let request_state = initial["requestState"]
        .as_str()
        .expect("the router mints an opaque resource MRTR state")
        .to_owned();
    let bad_request_state = selected_modern_stdio_raw_error(
        &mut raw,
        "resources/read",
        json!({
            "uri": "info://mrtr-resource",
            "inputResponses": {"roots": {"roots": []}},
            "requestState": format!("{request_state}-mutated"),
        }),
    );
    assert_eq!(bad_request_state, "Invalid or expired MRTR request state");

    // RH-5: retain every accepted field and change only the typed response
    // discriminator from roots to elicitation.
    // A subsequent accepted retry with the original state proves neither
    // rejection consumed the server-owned registry entry or reached the handler.
    let bad_input_responses = selected_modern_stdio_raw_error(
        &mut raw,
        "resources/read",
        json!({
            "uri": "info://mrtr-resource",
            "inputResponses": {
                "roots": {"action": "accept", "content": {}},
            },
            "requestState": request_state,
        }),
    );
    assert_eq!(
        bad_input_responses,
        "MRTR input response does not match its request"
    );
    let completed = selected_modern_stdio_raw_result(
        &mut raw,
        "resources/read",
        json!({
            "uri": "info://mrtr-resource",
            "inputResponses": {"roots": {"roots": []}},
            "requestState": initial["requestState"],
        }),
    );
    assert_eq!(completed["resultType"], "complete");
    assert_eq!(completed["ttlMs"], 7);
    assert_eq!(completed["cacheScope"], "private");
    assert_eq!(completed["contents"][0]["text"], "typed resource roots=0");
    let raw_cleanup_started = Instant::now();
    raw.close()
        .expect("the selected-modern raw MRTR public facade cleans up");
    assert!(
        raw_cleanup_started.elapsed() <= STDIO_COMPLETION_CLEANUP_BOUND,
        "the selected-modern raw MRTR facade also bounds child cleanup"
    );

    let cancellation = client
        .get_prompt_with_mrtr_retry(
            "mrtr_prompt",
            HashMap::from([("mode".to_owned(), "terminal".to_owned())]),
            |_| Err(fastmcp_rust::McpError::request_cancelled()),
        )
        .expect_err("a caller cancellation rejects before the MRTR retry is sent");
    assert_eq!(cancellation.code, McpErrorCode::RequestCancelled);

    let mut round_callbacks = 0;
    let round_error = client
        .get_prompt_with_mrtr_retry(
            "mrtr_prompt",
            HashMap::from([("mode".to_owned(), "round-bound".to_owned())]),
            |_| {
                round_callbacks += 1;
                Ok(std::collections::BTreeMap::from([(
                    "roots".to_owned(),
                    json!({"roots": [{"uri": "file:///mrtr/retry"}]}),
                )]))
            },
        )
        .expect_err("one continuation beyond the public round bound is rejected locally");
    assert_eq!(round_error.code, McpErrorCode::InvalidParams);
    assert_eq!(
        round_error.message,
        "MRTR continuation-round limit exceeded"
    );
    assert_eq!(round_callbacks, 4);

    let input_error = client
        .get_prompt_with_mrtr_retry(
            "mrtr_prompt",
            HashMap::from([("mode".to_owned(), "terminal".to_owned())]),
            |_| {
                Ok((0..=128)
                    .map(|index| (format!("oversized-{index}"), json!({"roots": []})))
                    .collect())
            },
        )
        .expect_err("a 129th response differs only by crossing the public input bound");
    assert_eq!(input_error.code, McpErrorCode::InvalidParams);
    assert_eq!(
        input_error.message,
        "MRTR inputResponses must not exceed 128 entries"
    );
    assert!(
        client.list_tools(None).is_ok(),
        "cancellation and local bounds leave the public modern connection usable"
    );

    let cleanup_started = Instant::now();
    client
        .close()
        .expect("modern MRTR stdio client cleanup reaps the shipped server");
    assert!(
        cleanup_started.elapsed() <= STDIO_COMPLETION_CLEANUP_BOUND,
        "the public client bounds the shipped server lifecycle by closing stdio"
    );
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_tasks_create_resume_cancel_and_reject_missing_capability() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client starts the shipped caller-owned Task service");

    // RH-5 near-negative: preserve the modern session, method, tool, and
    // arguments. `call_tool` differs from `call_tool_outcome` only by omitting
    // the official Tasks client capability. The bounded one-task store makes
    // the following successful creation a public proof that this refusal did
    // not persist a Task.
    let missing_capability = client
        .call_tool("durable_task", json!({}))
        .expect_err("a task-capable tool requires the declared Tasks capability");
    assert_eq!(i32::from(missing_capability.code), -32_021);

    let created = client
        .call_tool_outcome("durable_task", json!({}))
        .expect("the typed ModernOnly facade client creates one durable Task");
    let modern::FinalToolCallOutcome::Task(created) = created else {
        panic!("the task-capable tool returns the exact final Task result branch");
    };
    assert!(matches!(created.task, modern::FinalTask::Working(_)));
    assert_eq!(
        created.task.base().status_message.as_deref(),
        Some("durable stdio task call 1"),
        "the created Task proves the missing-capability call reached no durable Task state"
    );
    let task_id = created.task.base().task_id.clone();

    let input_required_deadline = Instant::now() + STDIO_COMPLETION_ABSOLUTE_TIMEOUT;
    let input_required = loop {
        let observed = client
            .get_task(task_id.clone())
            .expect("typed tasks/get observes the live shipped Task");
        if matches!(&observed.task, modern::FinalTask::InputRequired { .. }) {
            break observed;
        }
        assert!(
            Instant::now() < input_required_deadline,
            "the caller-owned supervisor reaches input_required within the public bound"
        );
        std::thread::sleep(Duration::from_millis(1));
    };
    assert_eq!(
        input_required.task.base().status_message.as_deref(),
        Some("awaiting roots from the caller-owned stdio service")
    );

    let responses: modern::FinalTaskInputResponses =
        serde_json::from_value(json!({"roots": {"roots": []}}))
            .expect("the exact public Tasks input response is typed");
    let updated = client
        .update_task(&input_required.task, responses)
        .expect("typed tasks/update accepts the declared input request");
    assert!(
        updated.additional.is_empty(),
        "tasks/update returns the exact empty final acknowledgement"
    );
    let cancelled = client
        .cancel_task(task_id.clone())
        .expect("typed tasks/cancel acknowledges the durable cancellation request");
    assert!(
        cancelled.additional.is_empty(),
        "tasks/cancel returns the exact empty final acknowledgement"
    );

    let cancellation_deadline = Instant::now() + STDIO_COMPLETION_ABSOLUTE_TIMEOUT;
    loop {
        let observed = client
            .get_task(task_id.clone())
            .expect("typed tasks/get remains usable after cancellation");
        if matches!(&observed.task, modern::FinalTask::Cancelled(_)) {
            break;
        }
        assert!(
            Instant::now() < cancellation_deadline,
            "the live caller-owned supervisor honors cancellation within the public bound"
        );
        std::thread::sleep(Duration::from_millis(1));
    }

    let cleanup_started = Instant::now();
    client
        .close()
        .expect("modern Tasks stdio client cleanup reaps the live subprocess");
    assert!(
        cleanup_started.elapsed() <= STDIO_COMPLETION_CLEANUP_BOUND,
        "the caller-owned stdio Task service settles when the client closes"
    );

    let mut legacy = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("the exact-2024 facade retains its separate shipped stdio lifecycle");
    let legacy_result = legacy
        .call_tool("durable_task", json!({}))
        .expect("exact-2024 treats the task-capable tool as an ordinary legacy tool");
    assert!(matches!(
        legacy_result.content.first(),
        Some(LegacyContent::Text { text, .. }) if text == "exact-2024 Tasks are unavailable"
    ));
    let legacy_cleanup_started = Instant::now();
    legacy
        .close()
        .expect("exact-2024 stdio client cleanup reaps its separate subprocess");
    assert!(
        legacy_cleanup_started.elapsed() <= STDIO_COMPLETION_CLEANUP_BOUND,
        "the exact-2024 subprocess also performs bounded cleanup without a Task service"
    );
}

#[cfg(unix)]
#[cfg(feature = "tasks")]
#[test]
fn e2e_public_stdio_modern_tasks_listen_retains_status_and_catalog_listen_refuses_task_ids() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client starts the shipped caller-owned Task service");

    let created = client
        .call_tool_outcome("durable_task", json!({}))
        .expect("the typed ModernOnly facade client creates one durable Task");
    let modern::FinalToolCallOutcome::Task(created) = created else {
        panic!("the task-capable tool returns the exact final Task result branch");
    };
    let task_id = created.task.base().task_id.clone();

    let mut catalog_with_tasks = modern::SubscriptionFilter {
        tools_list_changed: Some(true),
        ..modern::SubscriptionFilter::default()
    };
    modern::set_task_subscription_ids(&mut catalog_with_tasks, vec![task_id.clone()])
        .expect("the public Tasks filter composes beside a catalog filter");
    let catalog_refusal = client
        .open_subscriptions_listener(catalog_with_tasks)
        .expect_err("catalog listen must refuse taskIds");
    assert!(
        catalog_refusal
            .to_string()
            .contains("open_final_task_subscription_listener")
            || catalog_refusal.to_string().contains("taskIds"),
        "changing only the added taskIds must keep catalog listen refused: {catalog_refusal:?}"
    );

    let mut filter = modern::SubscriptionFilter::default();
    modern::set_task_subscription_ids(&mut filter, vec![task_id.clone()])
        .expect("the public Tasks filter is valid");
    client
        .open_final_task_subscription_listener(filter)
        .expect("live stdio must admit an incremental official Tasks listener");

    let cx = Cx::for_request();
    let cancellation = modern::McpRequestCancellation::new();
    let acknowledgement = client
        .next_final_task_subscription_event(&cx, &cancellation)
        .expect("official Tasks listen must emit its acknowledgement");
    assert!(
        matches!(
            acknowledgement,
            modern::StdioTaskSubscriptionEvent::Acknowledged(ref accepted)
                if modern::task_subscription_ids(accepted)
                    .expect("acknowledged Tasks filter stays valid")
                    .as_deref()
                    == Some([task_id.clone()].as_slice())
        ),
        "the first incremental Tasks listen record must be the accepted taskIds: {acknowledgement:?}"
    );

    client
        .cancel_task(task_id.clone())
        .expect("typed tasks/cancel acknowledges the durable cancellation request");

    let notification_deadline = Instant::now() + STDIO_COMPLETION_ABSOLUTE_TIMEOUT;
    loop {
        let event = client
            .next_final_task_subscription_event(&cx, &cancellation)
            .expect("official Tasks listen must retain later status updates");
        match event {
            modern::StdioTaskSubscriptionEvent::Notification(notification)
                if matches!(notification.params.task, modern::FinalTask::Cancelled(_)) =>
            {
                assert_eq!(
                    notification.params.task.base().task_id,
                    task_id,
                    "the Tasks notification must keep the created id"
                );
                break;
            }
            modern::StdioTaskSubscriptionEvent::Notification(_)
            | modern::StdioTaskSubscriptionEvent::Acknowledged(_) => {
                assert!(
                    Instant::now() < notification_deadline,
                    "the caller-owned supervisor publishes cancellation within the public bound"
                );
            }
            modern::StdioTaskSubscriptionEvent::Terminal => {
                panic!("the live Tasks listener must retain cancellation before terminal")
            }
        }
    }

    let observed = client
        .get_task(task_id)
        .expect("typed tasks/get remains usable after the listener observed cancellation");
    assert!(
        matches!(observed.task, modern::FinalTask::Cancelled(_)),
        "the same session must still admit tasks/get after listen: {observed:?}"
    );

    client
        .close()
        .expect("modern Tasks listen stdio client cleanup");
}

#[cfg(unix)]
#[cfg(feature = "tasks")]
#[test]
fn e2e_public_stdio_catalog_and_tasks_listen_stay_live_on_the_same_client() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client starts the shipped caller-owned Task service");

    let created = client
        .call_tool_outcome("durable_task", json!({}))
        .expect("the typed ModernOnly facade client creates one durable Task");
    let modern::FinalToolCallOutcome::Task(created) = created else {
        panic!("the task-capable tool returns the exact final Task result branch");
    };
    let task_id = created.task.base().task_id.clone();

    client
        .open_subscriptions_listener(modern::SubscriptionFilter {
            tools_list_changed: Some(true),
            ..modern::SubscriptionFilter::default()
        })
        .expect("live stdio must admit a catalog listener while official Tasks remain unused");

    let cx = Cx::for_request();
    let cancellation = modern::McpRequestCancellation::new();
    let catalog_ack = client
        .next_subscription_event(&cx, &cancellation)
        .expect("catalog listen must emit its acknowledgement");
    assert!(
        matches!(
            catalog_ack,
            modern::StdioSubscriptionEvent::Acknowledged(ref filter)
                if filter.tools_list_changed == Some(true)
        ),
        "the first catalog listen record must be the accepted filter: {catalog_ack:?}"
    );

    let mut task_filter = modern::SubscriptionFilter::default();
    modern::set_task_subscription_ids(&mut task_filter, vec![task_id.clone()])
        .expect("the public Tasks filter is valid");
    client
        .open_final_task_subscription_listener(task_filter)
        .expect(
            "the same stdio Client must admit official Tasks listen while catalog listen is live",
        );

    let task_ack = client
        .next_final_task_subscription_event(&cx, &cancellation)
        .expect("official Tasks listen must emit its acknowledgement");
    assert!(
        matches!(
            task_ack,
            modern::StdioTaskSubscriptionEvent::Acknowledged(ref accepted)
                if modern::task_subscription_ids(accepted)
                    .expect("acknowledged Tasks filter stays valid")
                    .as_deref()
                    == Some([task_id.clone()].as_slice())
        ),
        "the first incremental Tasks listen record must be the accepted taskIds: {task_ack:?}"
    );

    let hidden = client
        .call_tool("hide_echo", json!({}))
        .expect("disabling a peer tool must complete while both listeners are live");
    assert!(
        hidden.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => text == "hidden",
            _ => false,
        }),
        "the same stdio Client must still admit tools/call while both listeners are live: {hidden:?}"
    );

    let changed = client
        .next_subscription_event(&cx, &cancellation)
        .expect("catalog listen must retain tools/list_changed while Tasks listen is live");
    assert!(
        matches!(
            changed,
            modern::StdioSubscriptionEvent::Notification(
                modern::ServerNotification::ToolsListChanged(_)
            )
        ),
        "live stdio must retain catalog list_changed on the same client as Tasks listen: {changed:?}"
    );

    client
        .cancel_task(task_id.clone())
        .expect("typed tasks/cancel remains usable while both listeners are live");

    let notification_deadline = Instant::now() + STDIO_COMPLETION_ABSOLUTE_TIMEOUT;
    loop {
        let event = client
            .next_final_task_subscription_event(&cx, &cancellation)
            .expect("official Tasks listen must retain later status updates while catalog listen is live");
        match event {
            modern::StdioTaskSubscriptionEvent::Notification(notification)
                if matches!(notification.params.task, modern::FinalTask::Cancelled(_)) =>
            {
                assert_eq!(
                    notification.params.task.base().task_id,
                    task_id,
                    "the Tasks notification must keep the created id"
                );
                break;
            }
            modern::StdioTaskSubscriptionEvent::Notification(_)
            | modern::StdioTaskSubscriptionEvent::Acknowledged(_) => {
                assert!(
                    Instant::now() < notification_deadline,
                    "the caller-owned supervisor publishes cancellation within the public bound"
                );
            }
            modern::StdioTaskSubscriptionEvent::Terminal => {
                panic!("the live Tasks listener must retain cancellation before terminal")
            }
        }
    }

    let observed = client
        .get_task(task_id)
        .expect("typed tasks/get remains usable after both listeners observed their events");
    assert!(
        matches!(observed.task, modern::FinalTask::Cancelled(_)),
        "the same stdio client must still admit tasks/get after dual listen: {observed:?}"
    );

    client
        .close()
        .expect("modern dual-listen stdio client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_only_rejects_the_exact_legacy_shipped_server() {
    // This differs from the matched ModernOnly positive only in the child
    // server's policy. The public client must not silently downgrade.
    let result = connect_modern_stdio_to_shipped_echo_server("legacy-only");

    assert!(
        result.is_err(),
        "a ModernOnly facade client must reject the exact legacy server instead of downgrading"
    );
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_only_round_trips_with_the_shipped_facade_server() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client completes the exact legacy lifecycle");

    assert_eq!(
        client.protocol_version(),
        fastmcp_rust::legacy_2024::PROTOCOL_VERSION
    );
    client
        .ping()
        .expect("the explicit LegacyOnly core connection remains usable");
    let legacy_resource = client
        .read_resource("info://mrtr-resource")
        .expect_err("exact-2024 cannot activate the final MRTR resource handler");
    assert_eq!(legacy_resource.code, McpErrorCode::InternalError);
    assert_eq!(
        legacy_resource.message,
        "final #[resource] handlers must be invoked through ResourceHandler::read_final"
    );
    let legacy_prompt = client
        .get_prompt(
            "mrtr_prompt",
            HashMap::from([("mode".to_owned(), "terminal".to_owned())]),
        )
        .expect_err("exact-2024 cannot activate the final MRTR prompt handler");
    assert_eq!(legacy_prompt.code, McpErrorCode::InternalError);
    assert_eq!(
        legacy_prompt.message,
        "final #[prompt] handlers must be invoked through PromptHandler::get_final"
    );
    client.close().expect("legacy-only stdio client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_composes_nested_tool_and_resource() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client completes the exact legacy lifecycle");

    let composed = client
        .call_tool("compose_echo", json!({"message": "alpha"}))
        .expect("live exact-2024 stdio compose_echo must nest echo and info://server");
    assert!(
        composed.content.iter().any(|content| match content {
            LegacyContent::Text { text, .. } => {
                text.starts_with("compose:alpha|") && text.contains("echo-server")
            }
            _ => false,
        }),
        "compose_echo must retain the nested echo text and server-info resource: {composed:?}"
    );

    let missing_tool = client.call_tool(
        "compose_echo",
        json!({
            "message": "alpha",
            "tool": "stdio-e2e-missing",
        }),
    );
    let missing_tool = match missing_tool {
        Ok(result) if result.is_error => format!("{result:?}"),
        Err(error) => format!("{error:?}"),
        Ok(result) => panic!(
            "changing only the nested tool name must refuse before the peer resource: {result:?}"
        ),
    };
    assert!(
        missing_tool.contains("stdio-e2e-missing")
            || missing_tool.contains("compose-nested-tool")
            || missing_tool.contains("Unknown tool"),
        "the nested unknown tool must stay a handler-visible refusal: {missing_tool}"
    );

    let missing_resource = client.call_tool(
        "compose_echo",
        json!({
            "message": "beta",
            "resource": "info://stdio-e2e-missing",
        }),
    );
    let missing_resource = match missing_resource {
        Ok(result) if result.is_error => format!("{result:?}"),
        Err(error) => format!("{error:?}"),
        Ok(result) => panic!(
            "changing only the nested resource URI must refuse after the peer tool: {result:?}"
        ),
    };
    assert!(
        missing_resource.contains("info://stdio-e2e-missing")
            || missing_resource.contains("compose-nested-resource")
            || missing_resource.contains("not found"),
        "the nested unknown resource must stay a handler-visible refusal: {missing_resource}"
    );

    client
        .close()
        .expect("legacy-only stdio compose client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_composes_nested_prompt() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client completes the exact legacy lifecycle");

    let composed = client
        .call_tool("compose_prompt", json!({"name": "alpha"}))
        .expect("live exact-2024 stdio compose_prompt must nest the greeting prompt");
    assert!(
        composed.content.iter().any(|content| match content {
            LegacyContent::Text { text, .. } => {
                text == "compose-prompt:Please greet alpha in a friendly way."
            }
            _ => false,
        }),
        "compose_prompt must retain the nested greeting text: {composed:?}"
    );

    let missing = client.call_tool(
        "compose_prompt",
        json!({
            "name": "alpha",
            "prompt": "stdio-e2e-missing",
        }),
    );
    let missing = match missing {
        Ok(result) if result.is_error => format!("{result:?}"),
        Err(error) => format!("{error:?}"),
        Ok(result) => panic!("changing only the nested prompt name must refuse: {result:?}"),
    };
    assert!(
        missing.contains("stdio-e2e-missing")
            || missing.contains("compose-nested-prompt")
            || missing.contains("not found"),
        "the nested unknown prompt must stay a handler-visible refusal: {missing}"
    );

    client
        .close()
        .expect("legacy-only stdio compose-prompt client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_resource_and_prompt_compose_nested_prompt() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client completes the exact legacy lifecycle");

    let resource = client
        .read_resource("info://compose-prompt")
        .expect("live exact-2024 stdio info://compose-prompt must nest greeting");
    assert!(
        resource.contents.iter().any(|content| match content {
            LegacyResourceContent::Text { text, .. } => {
                text == "compose-prompt:Please greet alpha in a friendly way."
            }
            _ => false,
        }),
        "info://compose-prompt must retain the nested greeting text: {resource:?}"
    );
    let missing_resource = client
        .read_resource("info://compose-prompt-missing")
        .expect_err("changing only the nested prompt name must refuse the resource compose");
    let missing_resource = format!("{missing_resource:?}");
    assert!(
        missing_resource.contains("stdio-e2e-missing")
            || missing_resource.contains("compose-nested-prompt")
            || missing_resource.contains("not found"),
        "the nested unknown prompt must stay a handler-visible refusal: {missing_resource}"
    );

    let prompt = client
        .get_prompt(
            "compose_from_prompt",
            HashMap::from([("name".to_owned(), "alpha".to_owned())]),
        )
        .expect("live exact-2024 stdio compose_from_prompt must nest greeting");
    assert!(
        prompt
            .messages
            .iter()
            .any(|message| match &message.content {
                LegacyContent::Text { text, .. } => {
                    text == "compose-prompt:Please greet alpha in a friendly way."
                }
                _ => false,
            }),
        "compose_from_prompt must retain the nested greeting text: {prompt:?}"
    );
    let missing_prompt = client
        .get_prompt(
            "compose_from_prompt",
            HashMap::from([
                ("name".to_owned(), "alpha".to_owned()),
                ("prompt".to_owned(), "stdio-e2e-missing".to_owned()),
            ]),
        )
        .expect_err("changing only the nested prompt name must refuse the prompt compose");
    let missing_prompt = format!("{missing_prompt:?}");
    assert!(
        missing_prompt.contains("stdio-e2e-missing")
            || missing_prompt.contains("compose-nested-prompt")
            || missing_prompt.contains("not found"),
        "the nested unknown prompt must stay a handler-visible refusal: {missing_prompt}"
    );

    client
        .close()
        .expect("legacy-only stdio resource/prompt compose-prompt client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_prompt_composes_nested_tool_and_resource() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client completes the exact legacy lifecycle");

    let composed = client
        .get_prompt(
            "compose_greeting",
            HashMap::from([
                ("name".to_owned(), "alpha".to_owned()),
                ("tool".to_owned(), "echo".to_owned()),
                ("resource".to_owned(), "info://server".to_owned()),
            ]),
        )
        .expect("live exact-2024 stdio compose_greeting must nest echo and info://server");
    assert!(
        composed
            .messages
            .iter()
            .any(|message| match &message.content {
                LegacyContent::Text { text, .. } => {
                    text.starts_with("compose:alpha|") && text.contains("echo-server")
                }
                _ => false,
            }),
        "compose_greeting must retain the nested echo text and server-info resource: {composed:?}"
    );

    let missing_tool = client
        .get_prompt(
            "compose_greeting",
            HashMap::from([
                ("name".to_owned(), "alpha".to_owned()),
                ("tool".to_owned(), "stdio-e2e-missing".to_owned()),
                ("resource".to_owned(), "info://server".to_owned()),
            ]),
        )
        .expect_err("changing only the nested tool name must refuse before the peer resource");
    let missing_tool = format!("{missing_tool:?}");
    assert!(
        missing_tool.contains("stdio-e2e-missing")
            || missing_tool.contains("compose-nested-tool")
            || missing_tool.contains("Unknown tool"),
        "the nested unknown tool must stay a handler-visible refusal: {missing_tool}"
    );

    client
        .close()
        .expect("legacy-only stdio prompt compose client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_resource_composes_nested_tool_and_resource() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client completes the exact legacy lifecycle");

    let composed = client
        .read_resource("info://compose")
        .expect("live exact-2024 stdio info://compose must nest echo and info://server");
    assert!(
        composed.contents.iter().any(|content| match content {
            LegacyResourceContent::Text { text, .. } => {
                text.starts_with("compose:alpha|") && text.contains("echo-server")
            }
            _ => false,
        }),
        "info://compose must retain the nested echo text and server-info resource: {composed:?}"
    );

    let missing_tool = client
        .read_resource("info://compose-missing-tool")
        .expect_err("changing only the nested tool name must refuse before the peer resource");
    let missing_tool = format!("{missing_tool:?}");
    assert!(
        missing_tool.contains("stdio-e2e-missing")
            || missing_tool.contains("compose-nested-tool")
            || missing_tool.contains("Unknown tool"),
        "the nested unknown tool must stay a handler-visible refusal: {missing_tool}"
    );

    let missing_resource = client
        .read_resource("info://compose-missing-resource")
        .expect_err("changing only the nested resource URI must refuse after the peer tool");
    let missing_resource = format!("{missing_resource:?}");
    assert!(
        missing_resource.contains("info://stdio-e2e-missing")
            || missing_resource.contains("compose-nested-resource")
            || missing_resource.contains("not found"),
        "the nested unknown resource must stay a handler-visible refusal: {missing_resource}"
    );

    client
        .close()
        .expect("legacy-only stdio resource compose client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_handler_timeout_refuses_late_tool_and_admits_fast_peer() {
    let mut client = legacy_2024::client_builder()
        .env("FASTMCP_PROTOCOL_POLICY", "legacy-only")
        .request_timeout_policy(
            RequestTimeoutPolicy::new(
                STDIO_COMPLETION_IDLE_TIMEOUT,
                STDIO_COMPLETION_ABSOLUTE_TIMEOUT,
            )
            .expect("the public handler-timeout client policy is valid"),
        )
        .connect_stdio_with_cx(shipped_echo_server_executable(), &[], &Cx::for_request())
        .expect("a LegacyOnly facade client completes the exact legacy lifecycle");

    let timed_out = client
        .call_tool("slow_echo", json!({}))
        .expect_err("a handler that outlives its timeout must be refused");
    let timed_out = format!("{timed_out:?}");
    assert!(
        timed_out.contains("Request timeout exceeded") || timed_out.contains("RequestCancelled"),
        "the refused late tools/call must keep the handler-timeout error: {timed_out}"
    );

    let fast = client
        .call_tool("fast_echo", json!({}))
        .expect("changing only the tool must still be admitted after a handler timeout");
    assert!(
        fast.content.iter().any(|content| match content {
            LegacyContent::Text { text, .. } => text == "fast",
            _ => false,
        }),
        "the fast peer tool must still complete: {fast:?}"
    );

    client
        .close()
        .expect("legacy-only stdio handler-timeout client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_default_parameter_is_injected_and_overridable() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client completes the exact legacy lifecycle");

    let injected = client
        .call_tool("greet", json!({"name": "World"}))
        .expect("omitting the defaulted argument must still be admitted");
    assert!(
        injected.content.iter().any(|content| match content {
            LegacyContent::Text { text, .. } => text == "greet:World!",
            _ => false,
        }),
        "the generated default must be injected at call time: {injected:?}"
    );

    let overridden = client
        .call_tool("greet", json!({"name": "World", "suffix": "?"}))
        .expect("supplying the defaulted argument must override the generated default");
    assert!(
        overridden.content.iter().any(|content| match content {
            LegacyContent::Text { text, .. } => text == "greet:World?",
            _ => false,
        }),
        "changing only the suffix must override the generated default: {overridden:?}"
    );

    let missing_name = client.call_tool("greet", json!({"suffix": "!"}));
    let missing_name = match missing_name {
        Ok(result) if result.is_error => format!("{result:?}"),
        Err(error) => format!("{error:?}"),
        Ok(result) => {
            panic!("a missing required generated argument must stay an error: {result:?}")
        }
    };
    assert!(
        missing_name.contains("name")
            || missing_name.contains("required")
            || missing_name.contains("Invalid")
            || missing_name.contains("input schema")
            || missing_name.contains("inputSchema"),
        "omitting only the required sibling must stay a handler-visible refusal: {missing_name}"
    );

    let injected_prompt = client
        .get_prompt(
            "compose_greeting",
            HashMap::from([("name".to_owned(), "alpha".to_owned())]),
        )
        .expect("omitting defaulted prompt arguments must still compose echo and info://server");
    assert!(
        injected_prompt
            .messages
            .iter()
            .any(|message| match &message.content {
                LegacyContent::Text { text, .. } => {
                    text.starts_with("compose:alpha|") && text.contains("echo-server")
                }
                _ => false,
            }),
        "prompt defaults must inject echo and info://server: {injected_prompt:?}"
    );

    client
        .close()
        .expect("legacy-only stdio default-parameter client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_output_schema_is_listed_and_call_stays_unstructured() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client completes the exact legacy lifecycle");

    let listed = client
        .list_tools()
        .expect("live exact-2024 stdio must list the output-schema tools");
    let structured = listed
        .iter()
        .find(|tool| tool.name == "structured_echo")
        .expect("structured_echo must remain on the live catalog");
    let echo = listed
        .iter()
        .find(|tool| tool.name == "echo")
        .expect("the bare echo peer must remain on the live catalog");
    assert_eq!(
        structured
            .output_schema
            .as_ref()
            .and_then(|schema| schema.get("required")),
        Some(&json!(["value"])),
        "tools/list must retain the advertised output schema: {structured:?}"
    );
    assert_eq!(
        echo.output_schema, None,
        "changing only the missing output schema must keep the echo peer bare: {echo:?}"
    );

    let called = client
        .call_tool("structured_echo", json!({"value": "alpha"}))
        .expect("live exact-2024 stdio must admit the structured output tool");
    assert!(
        called.content.iter().any(|content| match content {
            LegacyContent::Text { text, .. } => text == "tool:alpha",
            _ => false,
        }),
        "the structured tool must still author text content: {called:?}"
    );

    client
        .close()
        .expect("legacy-only stdio output-schema client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_rich_content_retains_image_and_peer_stays_text() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client completes the exact legacy lifecycle");

    let rich = client
        .call_tool("rich_echo", json!({}))
        .expect("live exact-2024 stdio must retain the representable image block");
    assert!(
        rich.content.iter().any(|content| match content {
            LegacyContent::Image {
                data, mime_type, ..
            } => data == "e2eimage" && mime_type == "image/png",
            _ => false,
        }),
        "tools/call must retain the authored image block: {rich:?}"
    );
    assert!(
        rich.content
            .iter()
            .all(|content| !matches!(content, LegacyContent::Text { .. })),
        "exact-2024 must not invent a text projection of the image: {rich:?}"
    );

    let peer = client
        .call_tool("echo", json!({"message": "alpha"}))
        .expect("the text-only echo peer must still be callable");
    assert!(
        peer.content
            .iter()
            .all(|content| matches!(content, LegacyContent::Text { .. })),
        "changing only the missing rich content must keep the echo peer text-only: {peer:?}"
    );

    client
        .close()
        .expect("legacy-only stdio rich-content client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_initialize_retains_instructions() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client completes the exact legacy lifecycle");
    assert_eq!(
        client.instructions(),
        Some(ECHO_SERVER_INSTRUCTIONS),
        "live exact-2024 stdio initialize must retain the shipped echo instructions"
    );
    client
        .close()
        .expect("instructed legacy stdio client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_notification_tools_list_changed_is_retained() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client completes the exact legacy lifecycle");

    let hidden = client
        .call_tool("hide_echo", json!({}))
        .expect("live exact-2024 stdio must admit hide_echo");
    assert!(
        hidden.content.iter().any(|content| match content {
            LegacyContent::Text { text, .. } => text == "hidden",
            _ => false,
        }),
        "hide_echo must disable the echo tool: {hidden:?}"
    );

    let notifications = client
        .take_server_notifications()
        .expect("exact-2024 stdio notifications must decode");
    assert!(
        notifications.iter().any(|notification| matches!(
            notification,
            legacy_2024::ServerNotification::ToolsListChanged
        )),
        "live exact-2024 stdio must retain notifications/tools/list_changed: {notifications:?}"
    );

    client
        .close()
        .expect("legacy-only stdio list_changed client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_notification_tools_list_changed_peer_stays_silent() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client completes the exact legacy lifecycle");

    client
        .call_tool("echo", json!({"message": "alpha"}))
        .expect("the text-only echo peer must still be callable");
    let notifications = client
        .take_server_notifications()
        .expect("exact-2024 stdio notifications must decode");
    assert!(
        !notifications.iter().any(|notification| matches!(
            notification,
            legacy_2024::ServerNotification::ToolsListChanged
        )),
        "changing only the missing catalog mutation must keep tools/list_changed silent: {notifications:?}"
    );

    client
        .close()
        .expect("legacy-only stdio silent list_changed client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_notification_ctx_info_is_retained() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client completes the exact legacy lifecycle");

    client
        .set_log_level(legacy_2024::LogLevel::Info)
        .expect("exact-2024 logging/setLevel must be admitted");
    client
        .call_tool("echo", json!({"message": "log"}))
        .expect("ctx.info must not prevent the shipped echo tool from completing");
    let notifications = client
        .take_server_notifications()
        .expect("exact-2024 stdio notifications must decode");
    assert!(
        notifications.iter().any(|notification| matches!(
            notification,
            legacy_2024::ServerNotification::Message(message)
                if message.level == legacy_2024::LogLevel::Info
                    && message.data == json!("echo-handler-info")
        )),
        "live exact-2024 stdio must retain ctx.info after set_log_level(Info): {notifications:?}"
    );

    client
        .close()
        .expect("legacy-only stdio log client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_notification_ctx_info_peer_stays_silent() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client completes the exact legacy lifecycle");

    client
        .call_tool("echo", json!({"message": "quiet"}))
        .expect("the echo peer must still be callable without set_log_level");
    let notifications = client
        .take_server_notifications()
        .expect("exact-2024 stdio notifications must decode");
    assert!(
        !notifications.iter().any(|notification| matches!(
            notification,
            legacy_2024::ServerNotification::Message(message)
                if message.data == json!("echo-handler-info")
        )),
        "omitting only logging/setLevel must keep ctx.info silent: {notifications:?}"
    );

    client
        .close()
        .expect("legacy-only stdio silent log client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_progress_marker_is_retained_from_live_echo() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client completes the exact legacy lifecycle");

    client
        .call_tool("echo", json!({"message": "no-token"}))
        .expect("echo still completes without a progress token");
    let silent = client
        .take_server_notifications()
        .expect("exact-2024 stdio notifications must decode");
    assert!(
        !silent.iter().any(|notification| matches!(
            notification,
            legacy_2024::ServerNotification::Progress(_)
        )),
        "without a progressToken the shipped echo tool must not emit request-scoped progress: {silent:?}"
    );

    let marker = legacy_2024::ProgressMarker::from("stdio-legacy-progress");
    client
        .call_tool_with_progress_marker("echo", json!({"message": "token"}), marker.clone())
        .expect("a progressToken must not prevent the shipped echo tool from completing");
    let progress = client
        .take_server_notifications()
        .expect("exact-2024 stdio notifications must decode");
    assert!(
        progress.iter().any(|notification| matches!(
            notification,
            legacy_2024::ServerNotification::Progress(params)
                if params.progress_marker == marker
                    && params.message.as_deref() == Some("echoed")
        )),
        "live exact-2024 stdio must retain notifications/progress after a progressToken: {progress:?}"
    );

    client
        .read_resource("info://server")
        .expect("a resources/read without a progress token still completes");
    let silent_resource = client
        .take_server_notifications()
        .expect("exact-2024 stdio notifications must decode");
    assert!(
        !silent_resource.iter().any(|notification| matches!(
            notification,
            legacy_2024::ServerNotification::Progress(_)
        )),
        "without a progressToken the shipped server_info resource must not emit request-scoped progress: {silent_resource:?}"
    );

    let resource_marker = legacy_2024::ProgressMarker::from("stdio-legacy-resource-progress");
    client
        .read_resource_with_progress_marker("info://server", resource_marker.clone())
        .expect(
            "a progressToken must not prevent the shipped server_info resource from completing",
        );
    let resource_progress = client
        .take_server_notifications()
        .expect("exact-2024 stdio notifications must decode");
    assert!(
        resource_progress.iter().any(|notification| matches!(
            notification,
            legacy_2024::ServerNotification::Progress(params)
                if params.progress_marker == resource_marker
                    && params.message.as_deref() == Some("info")
        )),
        "live exact-2024 stdio must retain resource notifications/progress after a progressToken: {resource_progress:?}"
    );

    let mut greeting_arguments = std::collections::HashMap::new();
    greeting_arguments.insert("name".to_owned(), "no-token".to_owned());
    client
        .get_prompt("greeting", greeting_arguments)
        .expect("a prompts/get without a progress token still completes");
    let silent_prompt = client
        .take_server_notifications()
        .expect("exact-2024 stdio notifications must decode");
    assert!(
        !silent_prompt.iter().any(|notification| matches!(
            notification,
            legacy_2024::ServerNotification::Progress(_)
        )),
        "without a progressToken the shipped greeting prompt must not emit request-scoped progress: {silent_prompt:?}"
    );

    let prompt_marker = legacy_2024::ProgressMarker::from("stdio-legacy-prompt-progress");
    let mut greeting_with_token = std::collections::HashMap::new();
    greeting_with_token.insert("name".to_owned(), "token".to_owned());
    client
        .get_prompt_with_progress_marker("greeting", greeting_with_token, prompt_marker.clone())
        .expect("a progressToken must not prevent the shipped greeting prompt from completing");
    let prompt_progress = client
        .take_server_notifications()
        .expect("exact-2024 stdio notifications must decode");
    assert!(
        prompt_progress.iter().any(|notification| matches!(
            notification,
            legacy_2024::ServerNotification::Progress(params)
                if params.progress_marker == prompt_marker
                    && params.message.as_deref() == Some("greeted")
        )),
        "live exact-2024 stdio must retain prompt notifications/progress after a progressToken: {prompt_progress:?}"
    );

    let completion_params = legacy_2024::LegacyCompletionParams {
        reference: legacy_2024::LegacyCompletionReference::Prompt {
            name: "greeting".to_owned(),
        },
        argument: legacy_2024::LegacyCompletionArgument {
            name: "name".to_owned(),
            value: "co".to_owned(),
        },
        meta: None,
    };
    client
        .complete(completion_params.clone())
        .expect("a completion/complete without a progress token still completes");
    let silent_completion = client
        .take_server_notifications()
        .expect("exact-2024 stdio notifications must decode");
    assert!(
        !silent_completion.iter().any(|notification| matches!(
            notification,
            legacy_2024::ServerNotification::Progress(_)
        )),
        "without a progressToken the shipped greeting completion must not emit request-scoped progress: {silent_completion:?}"
    );

    let completion_marker = legacy_2024::ProgressMarker::from("stdio-legacy-completion-progress");
    let completed = client
        .complete_with_progress_marker(completion_params, completion_marker.clone())
        .expect("a progressToken must not prevent the shipped greeting completion from completing");
    assert_eq!(
        completed.completion.values,
        vec!["stdio-completion-legacy".to_owned()],
        "the exact-2024 completion provider must retain its values: {completed:?}"
    );
    let completion_progress = client
        .take_server_notifications()
        .expect("exact-2024 stdio notifications must decode");
    assert!(
        completion_progress.iter().any(|notification| matches!(
            notification,
            legacy_2024::ServerNotification::Progress(params)
                if params.progress_marker == completion_marker
                    && params.message.as_deref() == Some("stdio-completion-legacy-halfway")
        )),
        "live exact-2024 stdio must retain completion notifications/progress after a progressToken: {completion_progress:?}"
    );

    client
        .close()
        .expect("legacy-only stdio progress client cleanup");
}

#[cfg(all(unix, any(target_os = "linux", target_os = "macos")))]
const STDIO_FS_PREFIX: &str = "e2e";
#[cfg(all(unix, any(target_os = "linux", target_os = "macos")))]
const STDIO_FS_TEMPLATE: &str = "file:///e2e/{+path}";
#[cfg(all(unix, any(target_os = "linux", target_os = "macos")))]
const STDIO_FS_FILE_URI: &str = "file:///e2e/note.txt";
#[cfg(all(unix, any(target_os = "linux", target_os = "macos")))]
const STDIO_FS_FILE_TEXT: &str = "filesystem:stdio";

#[cfg(all(unix, any(target_os = "linux", target_os = "macos")))]
#[test]
fn e2e_public_stdio_modern_filesystem_provider_lists_and_reads_live_file() {
    let root = std::env::temp_dir().join(format!(
        "fastmcp-public-stdio-fs-e2e-{}",
        std::process::id()
    ));
    std::fs::create_dir_all(&root).expect("the stdio filesystem e2e root is created");
    std::fs::write(root.join("note.txt"), STDIO_FS_FILE_TEXT)
        .expect("the stdio filesystem e2e file is written");
    let root_path = root
        .to_str()
        .expect("the stdio filesystem e2e root is utf-8")
        .to_owned();

    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server_with_env(
        "modern-only",
        &[
            ("FASTMCP_FS_ROOT", root_path.as_str()),
            ("FASTMCP_FS_PREFIX", STDIO_FS_PREFIX),
        ],
    )
    .expect("a ModernOnly facade client connects to the filesystem echo peer");

    let listed = client
        .list_resource_templates(None)
        .expect("live stdio must list the FilesystemProvider template");
    assert!(
        listed.resource_templates.iter().any(|template| {
            template.uri_template == STDIO_FS_TEMPLATE && template.name == STDIO_FS_PREFIX
        }),
        "FilesystemProvider must advertise its reversible file template: {:?}",
        listed.resource_templates
    );

    let unmatched = client.read_resource("file:///other/note.txt").expect_err(
        "changing only the prefix the template cannot bind must refuse before dispatch",
    );
    assert_eq!(
        unmatched.code,
        McpErrorCode::InvalidParams,
        "an unmatched filesystem URI must stay InvalidParams: {unmatched:?}"
    );

    let file = client
        .read_resource(STDIO_FS_FILE_URI)
        .expect("resources/read must expand the live file URI through the filesystem handler");
    assert!(
        matches!(
            file.contents.as_slice(),
            [EmbeddedResourceContents::Text { text, .. }] if text == STDIO_FS_FILE_TEXT
        ),
        "the live filesystem read must retain the file bytes: {:?}",
        file.contents
    );

    client
        .close()
        .expect("modern-only stdio filesystem client cleanup");
}

#[cfg(all(unix, any(target_os = "linux", target_os = "macos")))]
#[test]
fn e2e_public_stdio_legacy_filesystem_provider_lists_and_reads_live_file() {
    let root = std::env::temp_dir().join(format!(
        "fastmcp-public-stdio-legacy-fs-e2e-{}",
        std::process::id()
    ));
    std::fs::create_dir_all(&root).expect("the exact-2024 stdio filesystem e2e root is created");
    std::fs::write(root.join("note.txt"), STDIO_FS_FILE_TEXT)
        .expect("the exact-2024 stdio filesystem e2e file is written");
    let root_path = root
        .to_str()
        .expect("the exact-2024 stdio filesystem e2e root is utf-8")
        .to_owned();

    let mut client = connect_legacy_stdio_to_shipped_echo_server_with_env(
        "legacy-only",
        &[
            ("FASTMCP_FS_ROOT", root_path.as_str()),
            ("FASTMCP_FS_PREFIX", STDIO_FS_PREFIX),
        ],
    )
    .expect("a LegacyOnly facade client connects to the filesystem echo peer");

    let listed = client
        .list_resource_templates()
        .expect("live exact-2024 stdio must list the FilesystemProvider template");
    assert!(
        listed.iter().any(|template| {
            template.uri_template == STDIO_FS_TEMPLATE && template.name == STDIO_FS_PREFIX
        }),
        "FilesystemProvider must advertise its reversible file template: {listed:?}"
    );

    let unmatched = client.read_resource("file:///other/note.txt").expect_err(
        "changing only the prefix the template cannot bind must refuse before dispatch",
    );
    assert_eq!(
        unmatched.code,
        McpErrorCode::ResourceNotFound,
        "an unmatched filesystem URI must stay ResourceNotFound on exact-2024: {unmatched:?}"
    );

    let file = client
        .read_resource(STDIO_FS_FILE_URI)
        .expect("resources/read must expand the live file URI through the filesystem handler");
    assert!(
        file.contents.iter().any(|content| match content {
            LegacyResourceContent::Text { text, .. } => text == STDIO_FS_FILE_TEXT,
            _ => false,
        }),
        "the live exact-2024 filesystem read must retain the file bytes: {:?}",
        file.contents
    );

    client
        .close()
        .expect("legacy-only stdio filesystem client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_hide_catalog_refuses_later_read_and_prompt() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client connects to the shipped echo server");

    let before = client
        .read_resource("info://server")
        .expect("the shipped echo resource must be readable before hide_catalog");
    assert!(
        before.contents.iter().any(|content| match content {
            LegacyResourceContent::Text { text, .. } => text.contains("echo-server"),
            _ => false,
        }),
        "the live exact-2024 stdio resource must retain the echo handler value: {before:?}"
    );

    let hidden = client
        .call_tool("hide_catalog", json!({}))
        .expect("disabling a shipped resource and prompt must complete");
    assert!(
        hidden.content.iter().any(|content| match content {
            LegacyContent::Text { text, .. } => text == "hidden",
            _ => false,
        }),
        "exact-2024 stdio session state must retain disable_resource and disable_prompt: {hidden:?}"
    );

    let disabled_resource = client.read_resource("info://server").expect_err(
        "hide_catalog must refuse a later info://server read on the same exact-2024 session",
    );
    let disabled_resource = format!("{disabled_resource:?}");
    assert!(
        disabled_resource.contains("disabled") && disabled_resource.contains("info://server"),
        "the refused resource read must be the session-disabled URI: {disabled_resource}"
    );
    let disabled_prompt = client
        .get_prompt(
            "greeting",
            HashMap::from([("name".to_owned(), "Bea".to_owned())]),
        )
        .expect_err("hide_catalog must refuse a later greeting get on the same exact-2024 session");
    let disabled_prompt = format!("{disabled_prompt:?}");
    assert!(
        disabled_prompt.contains("disabled") && disabled_prompt.contains("greeting"),
        "the refused prompt get must be the session-disabled prompt: {disabled_prompt}"
    );

    let shown = client
        .call_tool("show_catalog", json!({}))
        .expect("re-enabling a shipped resource and prompt must complete");
    assert!(
        shown.content.iter().any(|content| match content {
            LegacyContent::Text { text, .. } => text == "shown",
            _ => false,
        }),
        "exact-2024 stdio session state must retain enable_resource and enable_prompt: {shown:?}"
    );
    let restored = client.read_resource("info://server").expect(
        "show_catalog must restore a later info://server read on the same exact-2024 session",
    );
    assert!(
        restored.contents.iter().any(|content| match content {
            LegacyResourceContent::Text { text, .. } => text.contains("echo-server"),
            _ => false,
        }),
        "the restored exact-2024 stdio resource must retain the echo handler value: {restored:?}"
    );
    let restored_prompt = client
        .get_prompt(
            "greeting",
            HashMap::from([("name".to_owned(), "Cyd".to_owned())]),
        )
        .expect("show_catalog must restore a later greeting get on the same exact-2024 session");
    assert!(
        restored_prompt
            .messages
            .iter()
            .any(|message| match &message.content {
                LegacyContent::Text { text, .. } => {
                    text == "Please greet Cyd in a friendly way."
                }
                _ => false,
            }),
        "the restored exact-2024 stdio prompt must retain the echo handler value: {restored_prompt:?}"
    );

    client
        .close()
        .expect("legacy-only stdio hide_catalog client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_hide_echo_refuses_later_call_and_show_restores() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client connects to the shipped echo server");

    let before = client
        .call_tool("echo", json!({"message": "alpha"}))
        .expect("the shipped echo tool must be callable before hide_echo");
    assert!(
        before.content.iter().any(|content| match content {
            LegacyContent::Text { text, .. } => text.contains("alpha"),
            _ => false,
        }),
        "the live exact-2024 stdio echo must retain the handler text: {before:?}"
    );

    let hidden = client
        .call_tool("hide_echo", json!({}))
        .expect("disabling the shipped echo tool must complete");
    assert!(
        hidden.content.iter().any(|content| match content {
            LegacyContent::Text { text, .. } => text == "hidden",
            _ => false,
        }),
        "exact-2024 stdio session state must retain disable_tool: {hidden:?}"
    );

    let disabled = client.call_tool("echo", json!({"message": "beta"}));
    let disabled = match disabled {
        Ok(result) => {
            assert!(
                result.is_error,
                "hide_echo must turn a later echo call into a tool-level error: {result:?}"
            );
            format!("{result:?}")
        }
        Err(error) => format!("{error:?}"),
    };
    assert!(
        disabled.contains("disabled")
            || disabled.contains("echo")
            || disabled.contains("Method not found")
            || disabled.contains("MethodNotFound"),
        "the refused echo call must name the session-disabled tool: {disabled}"
    );

    let peer = client
        .call_tool("add", json!({"a": 2, "b": 3}))
        .expect("changing only the missing hide must keep an undisabled tool callable");
    assert!(
        peer.content.iter().any(|content| match content {
            LegacyContent::Text { text, .. } => text.contains('5'),
            _ => false,
        }),
        "an undisabled peer tool must still complete after hide_echo: {peer:?}"
    );

    let shown = client
        .call_tool("show_echo", json!({}))
        .expect("re-enabling the shipped echo tool must complete");
    assert!(
        shown.content.iter().any(|content| match content {
            LegacyContent::Text { text, .. } => text == "shown",
            _ => false,
        }),
        "exact-2024 stdio session state must retain enable_tool: {shown:?}"
    );
    let restored = client
        .call_tool("echo", json!({"message": "gamma"}))
        .expect("show_echo must restore a later echo call on the same exact-2024 session");
    assert!(
        restored.content.iter().any(|content| match content {
            LegacyContent::Text { text, .. } => text.contains("gamma"),
            _ => false,
        }),
        "the restored exact-2024 stdio echo must retain the handler text: {restored:?}"
    );

    client
        .close()
        .expect("legacy-only stdio hide_echo client cleanup");
}

#[cfg(unix)]
const STDIO_LEAK_RESOURCE_URI: &str = "info://leak";
#[cfg(unix)]
const STDIO_LEAK_SECRET: &str = "secret-db-dsn";

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_mask_error_details_hides_resource_execution_secret() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server_with_env(
        "modern-only",
        &[("FASTMCP_MASK_ERROR_DETAILS", "1")],
    )
    .expect("a ModernOnly facade client connects to the masked echo peer");
    let masked = client
        .read_resource(STDIO_LEAK_RESOURCE_URI)
        .expect_err("a leaking resource must stay a resources/read error");
    let masked = format!("{masked:?}");
    assert!(
        masked.contains("Internal server error"),
        "mask_error_details must replace the execution secret: {masked}"
    );
    assert!(
        !masked.contains(STDIO_LEAK_SECRET),
        "mask_error_details must not leak the execution secret: {masked}"
    );
    client
        .close()
        .expect("modern-only stdio masked client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_unmask_error_details_keeps_resource_execution_secret() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client connects to the unmasked echo peer");
    let unmasked = client
        .read_resource(STDIO_LEAK_RESOURCE_URI)
        .expect_err("changing only the missing mask flag must still refuse the leaking resource");
    let unmasked = format!("{unmasked:?}");
    assert!(
        unmasked.contains(STDIO_LEAK_SECRET),
        "disabling mask_error_details must keep the execution secret: {unmasked}"
    );
    client
        .close()
        .expect("modern-only stdio unmasked client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_mask_error_details_hides_resource_execution_secret() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server_with_env(
        "legacy-only",
        &[("FASTMCP_MASK_ERROR_DETAILS", "1")],
    )
    .expect("a LegacyOnly facade client connects to the masked echo peer");
    let masked = client
        .read_resource(STDIO_LEAK_RESOURCE_URI)
        .expect_err("a leaking resource must stay a resources/read error");
    let masked = format!("{masked:?}");
    assert!(
        masked.contains("Internal server error"),
        "exact-2024 stdio mask_error_details must replace the execution secret: {masked}"
    );
    assert!(
        !masked.contains(STDIO_LEAK_SECRET),
        "exact-2024 stdio mask_error_details must not leak the execution secret: {masked}"
    );
    client
        .close()
        .expect("legacy-only stdio masked client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_unmask_error_details_keeps_resource_execution_secret() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client connects to the unmasked echo peer");
    let unmasked = client
        .read_resource(STDIO_LEAK_RESOURCE_URI)
        .expect_err("changing only the missing mask flag must still refuse the leaking resource");
    let unmasked = format!("{unmasked:?}");
    assert!(
        unmasked.contains(STDIO_LEAK_SECRET),
        "disabling exact-2024 stdio mask_error_details must keep the execution secret: {unmasked}"
    );
    client
        .close()
        .expect("legacy-only stdio unmasked client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_strict_input_validation_refuses_unknown_property() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server_with_env(
        "modern-only",
        &[("FASTMCP_STRICT_INPUT", "1")],
    )
    .expect("a ModernOnly facade client connects to the strict echo peer");
    let admitted = client
        .call_tool("echo", json!({"message": "alpha"}))
        .expect("strict validation must still admit declared arguments");
    assert!(
        !admitted.is_error,
        "declared arguments must not become a tool-level error: {admitted:?}"
    );
    assert!(
        admitted.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => text.contains("alpha"),
            _ => false,
        }),
        "declared arguments must reach the handler under strict validation: {admitted:?}"
    );

    let refused = client.call_tool("echo", json!({"message": "alpha", "extra": 1}));
    let refused = match refused {
        Ok(result) => {
            assert!(
                result.is_error,
                "an unknown property must become a tool-level error when strict validation is on: {result:?}"
            );
            format!("{result:?}")
        }
        Err(error) => format!("{error:?}"),
    };
    assert!(
        refused.contains("do not match the declared input schema")
            || refused.contains("unknown")
            || refused.contains("InvalidParams")
            || refused.contains("extra")
            || refused.contains("additional property"),
        "the strict refusal must name the input-schema mismatch: {refused}"
    );
    client
        .close()
        .expect("modern-only stdio strict client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_lenient_input_validation_admits_unknown_property() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client connects to the lenient echo peer");
    let extra = client
        .call_tool("echo", json!({"message": "alpha", "extra": 1}))
        .expect("lenient validation must admit the same extra property");
    assert!(
        !extra.is_error,
        "changing only the missing strict flag must admit the extra property: {extra:?}"
    );
    assert!(
        extra.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => text.contains("alpha"),
            _ => false,
        }),
        "the extra property must not change the handler result when strict is off: {extra:?}"
    );
    client
        .close()
        .expect("modern-only stdio lenient client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_strict_input_validation_refuses_unknown_property() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server_with_env(
        "legacy-only",
        &[("FASTMCP_STRICT_INPUT", "1")],
    )
    .expect("a LegacyOnly facade client connects to the strict echo peer");
    let admitted = client
        .call_tool("echo", json!({"message": "alpha"}))
        .expect("strict validation must still admit declared arguments");
    assert!(
        !admitted.is_error,
        "declared arguments must not become a tool-level error: {admitted:?}"
    );
    assert!(
        admitted.content.iter().any(|content| match content {
            LegacyContent::Text { text, .. } => text.contains("alpha"),
            _ => false,
        }),
        "declared arguments must reach the handler under strict validation: {admitted:?}"
    );

    let refused = client.call_tool("echo", json!({"message": "alpha", "extra": 1}));
    let refused = match refused {
        Ok(result) => {
            assert!(
                result.is_error,
                "an unknown property must become a tool-level error when strict validation is on: {result:?}"
            );
            format!("{result:?}")
        }
        Err(error) => format!("{error:?}"),
    };
    assert!(
        refused.contains("do not match the declared input schema")
            || refused.contains("unknown")
            || refused.contains("InvalidParams")
            || refused.contains("extra")
            || refused.contains("additional property"),
        "the exact-2024 strict refusal must name the input-schema mismatch: {refused}"
    );
    client
        .close()
        .expect("legacy-only stdio strict client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_lenient_input_validation_admits_unknown_property() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client connects to the lenient echo peer");
    let extra = client
        .call_tool("echo", json!({"message": "alpha", "extra": 1}))
        .expect("lenient validation must admit the same extra property");
    assert!(
        !extra.is_error,
        "changing only the missing strict flag must admit the extra property: {extra:?}"
    );
    assert!(
        extra.content.iter().any(|content| match content {
            LegacyContent::Text { text, .. } => text.contains("alpha"),
            _ => false,
        }),
        "the extra property must not change the handler result when strict is off: {extra:?}"
    );
    client
        .close()
        .expect("legacy-only stdio lenient client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_sliding_window_refuses_second_same_method_and_admits_another() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server_with_env(
        "modern-only",
        &[("FASTMCP_SLIDING_WINDOW", "1")],
    )
    .expect("a ModernOnly facade client connects to the sliding-window echo peer");

    let first = client
        .call_tool("echo", json!({"message": "alpha"}))
        .expect("the first modern stdio tools/call must be admitted by the sliding window");
    assert!(
        !first.is_error,
        "the first sliding-window tools/call must reach the handler: {first:?}"
    );
    assert!(
        first.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => text.contains("alpha"),
            _ => false,
        }),
        "the first sliding-window tools/call must retain the handler text: {first:?}"
    );

    let limited = client.call_tool("echo", json!({"message": "beta"}));
    let limited = match limited {
        Ok(result) => {
            assert!(
                result.is_error,
                "a second tools/call must stay an error result: {result:?}"
            );
            format!("{result:?}")
        }
        Err(error) => format!("{error:?}"),
    };
    assert!(
        limited.contains("Rate limit exceeded"),
        "the refused second modern stdio tools/call must keep the sliding-window error: {limited}"
    );

    client
        .ping()
        .expect("changing only the method must still be admitted by the live sliding window");

    client
        .close()
        .expect("modern-only stdio sliding-window client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_sliding_window_refuses_second_same_method_and_admits_another() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server_with_env(
        "legacy-only",
        &[("FASTMCP_SLIDING_WINDOW", "1")],
    )
    .expect("a LegacyOnly facade client connects to the sliding-window echo peer");

    let first = client
        .call_tool("echo", json!({"message": "alpha"}))
        .expect("the first exact-2024 stdio tools/call must be admitted by the sliding window");
    assert!(
        !first.is_error,
        "the first sliding-window tools/call must reach the handler: {first:?}"
    );
    assert!(
        first.content.iter().any(|content| match content {
            LegacyContent::Text { text, .. } => text.contains("alpha"),
            _ => false,
        }),
        "the first sliding-window tools/call must retain the handler text: {first:?}"
    );

    let limited = client.call_tool("echo", json!({"message": "beta"}));
    let limited = match limited {
        Ok(result) => {
            assert!(
                result.is_error,
                "a second tools/call must stay an error result: {result:?}"
            );
            format!("{result:?}")
        }
        Err(error) => format!("{error:?}"),
    };
    assert!(
        limited.contains("Rate limit exceeded"),
        "the refused second exact-2024 stdio tools/call must keep the sliding-window error: {limited}"
    );

    let listed = client
        .list_tools()
        .expect("changing only the method must still be admitted by the live sliding window");
    assert!(
        listed.iter().any(|tool| tool.name == "echo"),
        "tools/list must stay callable after tools/call is sliding-window limited: {listed:?}"
    );

    client
        .close()
        .expect("legacy-only stdio sliding-window client cleanup");
}

#[cfg(unix)]
fn stdio_modern_tool_text(result: &fastmcp_rust::FinalCallToolResult) -> Option<&str> {
    result.content.iter().find_map(|content| match content {
        ContentBlock::Text { text, .. } => Some(text.as_str()),
        _ => None,
    })
}

#[cfg(unix)]
fn stdio_legacy_tool_text(result: &fastmcp_protocol::CallToolResult) -> Option<&str> {
    result.content.iter().find_map(|content| match content {
        LegacyContent::Text { text, .. } => Some(text.as_str()),
        _ => None,
    })
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_cache_hits_same_allowlisted_call_and_misses_changed_args() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server_with_env(
        "modern-only",
        &[("FASTMCP_CACHE_TOOLS", "1")],
    )
    .expect("a ModernOnly facade client connects to the cached echo peer");

    let first = client
        .call_tool("cache_probe", json!({"token": "alpha"}))
        .expect("the first allowlisted modern stdio tools/call must miss and reach the handler");
    assert!(
        !first.is_error,
        "the first cache_probe call must reach the handler: {first:?}"
    );
    assert_eq!(
        stdio_modern_tool_text(&first),
        Some("alpha:0"),
        "the first cache_probe call must increment the process-local counter: {first:?}"
    );

    let cached = client
        .call_tool("cache_probe", json!({"token": "alpha"}))
        .expect("the second identical allowlisted tools/call must be a cache hit");
    assert!(
        !cached.is_error,
        "the cache hit must stay a complete result: {cached:?}"
    );
    assert_eq!(
        stdio_modern_tool_text(&cached),
        Some("alpha:0"),
        "a cache hit must keep the first complete result without incrementing: {cached:?}"
    );

    let missed = client
        .call_tool("cache_probe", json!({"token": "beta"}))
        .expect("changing only the arguments must miss the cache");
    assert!(
        !missed.is_error,
        "a different-arguments tools/call must reach the handler: {missed:?}"
    );
    assert_eq!(
        stdio_modern_tool_text(&missed),
        Some("beta:1"),
        "a cache miss must increment the process-local counter: {missed:?}"
    );

    client
        .close()
        .expect("modern-only stdio cache client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_cache_off_invokes_handler_twice() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client connects to the uncached echo peer");

    let first = client
        .call_tool("cache_probe", json!({"token": "alpha"}))
        .expect("the first uncached modern stdio tools/call must reach the handler");
    assert_eq!(
        stdio_modern_tool_text(&first),
        Some("alpha:0"),
        "the first uncached cache_probe call must increment: {first:?}"
    );

    let second = client
        .call_tool("cache_probe", json!({"token": "alpha"}))
        .expect("omitting only FASTMCP_CACHE_TOOLS must invoke the handler again");
    assert_eq!(
        stdio_modern_tool_text(&second),
        Some("alpha:1"),
        "changing only the missing cache flag must increment again: {second:?}"
    );

    client
        .close()
        .expect("modern-only stdio uncached client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_cache_hits_same_allowlisted_call_and_misses_changed_args() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server_with_env(
        "legacy-only",
        &[("FASTMCP_CACHE_TOOLS", "1")],
    )
    .expect("a LegacyOnly facade client connects to the cached echo peer");

    let first = client
        .call_tool("cache_probe", json!({"token": "alpha"}))
        .expect(
            "the first allowlisted exact-2024 stdio tools/call must miss and reach the handler",
        );
    assert!(
        !first.is_error,
        "the first cache_probe call must reach the handler: {first:?}"
    );
    assert_eq!(
        stdio_legacy_tool_text(&first),
        Some("alpha:0"),
        "the first cache_probe call must increment the process-local counter: {first:?}"
    );

    let cached = client
        .call_tool("cache_probe", json!({"token": "alpha"}))
        .expect("the second identical allowlisted tools/call must be a cache hit");
    assert!(
        !cached.is_error,
        "the cache hit must stay a complete result: {cached:?}"
    );
    assert_eq!(
        stdio_legacy_tool_text(&cached),
        Some("alpha:0"),
        "a cache hit must keep the first complete result without incrementing: {cached:?}"
    );

    let missed = client
        .call_tool("cache_probe", json!({"token": "beta"}))
        .expect("changing only the arguments must miss the cache");
    assert!(
        !missed.is_error,
        "a different-arguments tools/call must reach the handler: {missed:?}"
    );
    assert_eq!(
        stdio_legacy_tool_text(&missed),
        Some("beta:1"),
        "a cache miss must increment the process-local counter: {missed:?}"
    );

    client
        .close()
        .expect("legacy-only stdio cache client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_cache_off_invokes_handler_twice() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client connects to the uncached echo peer");

    let first = client
        .call_tool("cache_probe", json!({"token": "alpha"}))
        .expect("the first uncached exact-2024 stdio tools/call must reach the handler");
    assert_eq!(
        stdio_legacy_tool_text(&first),
        Some("alpha:0"),
        "the first uncached cache_probe call must increment: {first:?}"
    );

    let second = client
        .call_tool("cache_probe", json!({"token": "alpha"}))
        .expect("omitting only FASTMCP_CACHE_TOOLS must invoke the handler again");
    assert_eq!(
        stdio_legacy_tool_text(&second),
        Some("alpha:1"),
        "changing only the missing cache flag must increment again: {second:?}"
    );

    client
        .close()
        .expect("legacy-only stdio uncached client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_rate_limit_refuses_second_same_method_and_admits_another() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server_with_env(
        "modern-only",
        &[("FASTMCP_RATE_LIMIT", "1")],
    )
    .expect("a ModernOnly facade client connects to the rate-limited echo peer");

    let first = client
        .call_tool("echo", json!({"message": "alpha"}))
        .expect("the first modern stdio tools/call must be admitted by the token bucket");
    assert!(
        !first.is_error,
        "the first rate-limited tools/call must reach the handler: {first:?}"
    );
    assert!(
        first.content.iter().any(|content| match content {
            ContentBlock::Text { text, .. } => text.contains("alpha"),
            _ => false,
        }),
        "the first rate-limited tools/call must retain the handler text: {first:?}"
    );

    let limited = client.call_tool("echo", json!({"message": "beta"}));
    let limited = match limited {
        Ok(result) => {
            assert!(
                result.is_error,
                "a second tools/call must stay an error result: {result:?}"
            );
            format!("{result:?}")
        }
        Err(error) => format!("{error:?}"),
    };
    assert!(
        limited.contains("Rate limit exceeded"),
        "the refused second modern stdio tools/call must keep the token-bucket error: {limited}"
    );

    client
        .ping()
        .expect("changing only the method must still be admitted by the live token bucket");

    client
        .close()
        .expect("modern-only stdio rate-limit client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_rate_limit_refuses_second_same_method_and_admits_another() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server_with_env(
        "legacy-only",
        &[("FASTMCP_RATE_LIMIT", "1")],
    )
    .expect("a LegacyOnly facade client connects to the rate-limited echo peer");

    let first = client
        .call_tool("echo", json!({"message": "alpha"}))
        .expect("the first exact-2024 stdio tools/call must be admitted by the token bucket");
    assert!(
        !first.is_error,
        "the first rate-limited tools/call must reach the handler: {first:?}"
    );
    assert!(
        first.content.iter().any(|content| match content {
            LegacyContent::Text { text, .. } => text.contains("alpha"),
            _ => false,
        }),
        "the first rate-limited tools/call must retain the handler text: {first:?}"
    );

    let limited = client.call_tool("echo", json!({"message": "beta"}));
    let limited = match limited {
        Ok(result) => {
            assert!(
                result.is_error,
                "a second tools/call must stay an error result: {result:?}"
            );
            format!("{result:?}")
        }
        Err(error) => format!("{error:?}"),
    };
    assert!(
        limited.contains("Rate limit exceeded"),
        "the refused second exact-2024 stdio tools/call must keep the token-bucket error: {limited}"
    );

    let listed = client
        .list_tools()
        .expect("changing only the method must still be admitted by the live token bucket");
    assert!(
        listed.iter().any(|tool| tool.name == "echo"),
        "tools/list must stay callable after tools/call is token-bucket limited: {listed:?}"
    );

    client
        .close()
        .expect("legacy-only stdio rate-limit client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_replace_echo_installs_second_handler() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server_with_env(
        "modern-only",
        &[("FASTMCP_REPLACE_ECHO", "1")],
    )
    .expect("a ModernOnly facade client connects to the replace-echo peer");

    let replaced = client
        .call_tool("echo", json!({"message": "alpha"}))
        .expect("Replace must install the second echo registration");
    assert!(
        !replaced.is_error,
        "the replaced echo must stay a complete result: {replaced:?}"
    );
    assert_eq!(
        stdio_modern_tool_text(&replaced),
        Some("replaced:alpha"),
        "changing only on_duplicate to Replace must reach the second handler: {replaced:?}"
    );

    client
        .close()
        .expect("modern-only stdio replace-echo client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_default_echo_keeps_first_handler() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client connects to the default echo peer");

    let kept = client
        .call_tool("echo", json!({"message": "alpha"}))
        .expect("omitting only FASTMCP_REPLACE_ECHO must keep the first echo");
    assert!(
        !kept.is_error,
        "the default echo must stay a complete result: {kept:?}"
    );
    assert_eq!(
        stdio_modern_tool_text(&kept),
        Some("alpha"),
        "changing only the missing replace flag must keep the first handler: {kept:?}"
    );

    client
        .close()
        .expect("modern-only stdio default-echo client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_replace_echo_installs_second_handler() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server_with_env(
        "legacy-only",
        &[("FASTMCP_REPLACE_ECHO", "1")],
    )
    .expect("a LegacyOnly facade client connects to the replace-echo peer");

    let replaced = client
        .call_tool("echo", json!({"message": "alpha"}))
        .expect("Replace must install the second echo registration");
    assert!(
        !replaced.is_error,
        "the replaced echo must stay a complete result: {replaced:?}"
    );
    assert_eq!(
        stdio_legacy_tool_text(&replaced),
        Some("replaced:alpha"),
        "changing only on_duplicate to Replace must reach the second handler: {replaced:?}"
    );

    client
        .close()
        .expect("legacy-only stdio replace-echo client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_default_echo_keeps_first_handler() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client connects to the default echo peer");

    let kept = client
        .call_tool("echo", json!({"message": "alpha"}))
        .expect("omitting only FASTMCP_REPLACE_ECHO must keep the first echo");
    assert!(
        !kept.is_error,
        "the default echo must stay a complete result: {kept:?}"
    );
    assert_eq!(
        stdio_legacy_tool_text(&kept),
        Some("alpha"),
        "changing only the missing replace flag must keep the first handler: {kept:?}"
    );

    client
        .close()
        .expect("legacy-only stdio default-echo client cleanup");
}

#[cfg(unix)]
const STDIO_LIST_PAGE_LIMITS: fastmcp_rust::ListPageLimits =
    fastmcp_rust::ListPageLimits::new(64, 1_048_576);

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_list_page_continues_and_rejects_wrong_catalog_cursor() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server_with_env(
        "modern-only",
        &[("FASTMCP_LIST_PAGE_SIZE", "1")],
    )
    .expect("a ModernOnly facade client connects to the paged echo peer");

    let first = client
        .list_tools(None)
        .expect("the first modern stdio tools/list page must miss and reach the catalog");
    assert_eq!(
        first.tools.len(),
        1,
        "page size 1 must create a real continuation: {first:?}"
    );
    let first_name = first.tools[0].name.clone();
    let cursor = first
        .next_cursor
        .clone()
        .expect("the first page-size-1 tools/list must carry an opaque cursor");

    let second = client
        .list_tools(Some(&cursor))
        .expect("the exact cursor continuation must reach the second live page");
    assert_eq!(
        second.tools.len(),
        1,
        "the continuation must retain one remaining tool: {second:?}"
    );
    assert_ne!(
        second.tools[0].name, first_name,
        "the continuation must advance to a different tool: {second:?}"
    );

    let rejected = client
        .list_resources(Some(&cursor))
        .expect_err("a tools/list cursor must not page resources/list");
    let rejected = format!("{rejected:?}");
    assert!(
        rejected.contains("InvalidParams") || rejected.contains("invalid"),
        "a wrong-catalog cursor must stay InvalidParams: {rejected}"
    );

    client
        .close()
        .expect("modern-only stdio paged client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_default_list_is_not_forced_to_page_size_one() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client connects to the unpaged echo peer");

    let listed = client
        .list_tools(None)
        .expect("omitting only FASTMCP_LIST_PAGE_SIZE must list the full first page");
    assert!(
        listed.tools.len() > 1,
        "changing only the missing page-size flag must keep more than one tool on the first page: {listed:?}"
    );

    client
        .close()
        .expect("modern-only stdio unpaged client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_list_page_continues_and_rejects_wrong_catalog_cursor() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server_with_env(
        "legacy-only",
        &[("FASTMCP_LIST_PAGE_SIZE", "1")],
    )
    .expect("a LegacyOnly facade client connects to the paged echo peer");

    let first = client
        .list_tools_page(None, STDIO_LIST_PAGE_LIMITS)
        .expect("the first exact-2024 stdio tools/list page must miss and reach the catalog");
    assert_eq!(
        first.items.len(),
        1,
        "page size 1 must create a real continuation: {first:?}"
    );
    let first_name = first.items[0].name.clone();
    let cursor = first
        .next_cursor
        .clone()
        .expect("the first page-size-1 tools/list must carry an opaque cursor");

    let second = client
        .list_tools_page(Some(&cursor), STDIO_LIST_PAGE_LIMITS)
        .expect("the exact cursor continuation must reach the second live page");
    assert_eq!(
        second.items.len(),
        1,
        "the continuation must retain one remaining tool: {second:?}"
    );
    assert_ne!(
        second.items[0].name, first_name,
        "the continuation must advance to a different tool: {second:?}"
    );

    let rejected = client
        .list_resources_page(Some(&cursor), STDIO_LIST_PAGE_LIMITS)
        .expect_err("a tools/list cursor must not page resources/list");
    let rejected = format!("{rejected:?}");
    assert!(
        rejected.contains("InvalidParams") || rejected.contains("invalid"),
        "a wrong-catalog cursor must stay InvalidParams: {rejected}"
    );

    client
        .close()
        .expect("legacy-only stdio paged client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_default_list_is_not_forced_to_page_size_one() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client connects to the unpaged echo peer");

    let listed = client
        .list_tools_page(None, STDIO_LIST_PAGE_LIMITS)
        .expect("omitting only FASTMCP_LIST_PAGE_SIZE must list the full first page");
    assert!(
        listed.items.len() > 1,
        "changing only the missing page-size flag must keep more than one tool on the first page: {listed:?}"
    );

    client
        .close()
        .expect("legacy-only stdio unpaged client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_catalog_list_page_continues_and_rejects_wrong_kind_cursor() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server_with_env(
        "modern-only",
        &[("FASTMCP_LIST_PAGE_SIZE", "1")],
    )
    .expect("a ModernOnly facade client connects to the paged echo peer");

    let first_resources = client
        .list_resources(None)
        .expect("the first modern stdio resources/list page must miss and reach the catalog");
    assert_eq!(
        first_resources.resources.len(),
        1,
        "page size 1 must create a real resources continuation: {first_resources:?}"
    );
    let first_resource = first_resources.resources[0].uri.as_str().to_owned();
    let resource_cursor = first_resources
        .next_cursor
        .clone()
        .expect("the first page-size-1 resources/list must carry an opaque cursor");
    let second_resources = client
        .list_resources(Some(&resource_cursor))
        .expect("the exact resources cursor continuation must reach the second live page");
    assert_eq!(
        second_resources.resources.len(),
        1,
        "the resources continuation must retain one remaining resource: {second_resources:?}"
    );
    assert_ne!(
        second_resources.resources[0].uri.as_str(),
        first_resource,
        "the resources continuation must advance to a different URI: {second_resources:?}"
    );
    let rejected_prompts = client
        .list_prompts(Some(&resource_cursor))
        .expect_err("a resources/list cursor must not page prompts/list");
    let rejected_prompts = format!("{rejected_prompts:?}");
    assert!(
        rejected_prompts.contains("InvalidParams") || rejected_prompts.contains("invalid"),
        "a wrong-catalog resources cursor must stay InvalidParams: {rejected_prompts}"
    );

    let first_prompts = client
        .list_prompts(None)
        .expect("the first modern stdio prompts/list page must miss and reach the catalog");
    assert_eq!(
        first_prompts.prompts.len(),
        1,
        "page size 1 must create a real prompts continuation: {first_prompts:?}"
    );
    let first_prompt = first_prompts.prompts[0].name.clone();
    let prompt_cursor = first_prompts
        .next_cursor
        .clone()
        .expect("the first page-size-1 prompts/list must carry an opaque cursor");
    let second_prompts = client
        .list_prompts(Some(&prompt_cursor))
        .expect("the exact prompts cursor continuation must reach the second live page");
    assert_eq!(
        second_prompts.prompts.len(),
        1,
        "the prompts continuation must retain one remaining prompt: {second_prompts:?}"
    );
    assert_ne!(
        second_prompts.prompts[0].name, first_prompt,
        "the prompts continuation must advance to a different name: {second_prompts:?}"
    );
    let rejected_tools = client
        .list_tools(Some(&prompt_cursor))
        .expect_err("a prompts/list cursor must not page tools/list");
    let rejected_tools = format!("{rejected_tools:?}");
    assert!(
        rejected_tools.contains("InvalidParams") || rejected_tools.contains("invalid"),
        "a wrong-catalog prompts cursor must stay InvalidParams: {rejected_tools}"
    );

    let first_templates = client
        .list_resource_templates(None)
        .expect("the first modern stdio templates/list page must miss and reach the catalog");
    assert_eq!(
        first_templates.resource_templates.len(),
        1,
        "page size 1 must create a real templates continuation: {first_templates:?}"
    );
    let first_template = first_templates.resource_templates[0].uri_template.clone();
    let template_cursor = first_templates
        .next_cursor
        .clone()
        .expect("the first page-size-1 templates/list must carry an opaque cursor");
    let second_templates = client
        .list_resource_templates(Some(&template_cursor))
        .expect("the exact templates cursor continuation must reach the second live page");
    assert_eq!(
        second_templates.resource_templates.len(),
        1,
        "the templates continuation must retain one remaining template: {second_templates:?}"
    );
    assert_ne!(
        second_templates.resource_templates[0].uri_template, first_template,
        "the templates continuation must advance to a different URI template: {second_templates:?}"
    );
    let rejected_resources = client
        .list_resources(Some(&template_cursor))
        .expect_err("a templates/list cursor must not page resources/list");
    let rejected_resources = format!("{rejected_resources:?}");
    assert!(
        rejected_resources.contains("InvalidParams") || rejected_resources.contains("invalid"),
        "a wrong-catalog templates cursor must stay InvalidParams: {rejected_resources}"
    );

    client
        .close()
        .expect("modern-only stdio catalog-paged client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_default_catalog_list_is_not_forced_to_page_size_one() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client connects to the unpaged echo peer");

    let resources = client
        .list_resources(None)
        .expect("omitting only FASTMCP_LIST_PAGE_SIZE must list the full first resources page");
    assert!(
        resources.resources.len() > 1,
        "changing only the missing page-size flag must keep more than one resource on the first page: {resources:?}"
    );
    let prompts = client
        .list_prompts(None)
        .expect("omitting only FASTMCP_LIST_PAGE_SIZE must list the full first prompts page");
    assert!(
        prompts.prompts.len() > 1,
        "changing only the missing page-size flag must keep more than one prompt on the first page: {prompts:?}"
    );
    let templates = client
        .list_resource_templates(None)
        .expect("omitting only FASTMCP_LIST_PAGE_SIZE must list the full first templates page");
    assert!(
        templates.resource_templates.len() > 1,
        "changing only the missing page-size flag must keep more than one template on the first page: {templates:?}"
    );

    client
        .close()
        .expect("modern-only stdio unpaged catalog client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_catalog_list_page_continues_and_rejects_wrong_kind_cursor() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server_with_env(
        "legacy-only",
        &[("FASTMCP_LIST_PAGE_SIZE", "1")],
    )
    .expect("a LegacyOnly facade client connects to the paged echo peer");

    let first_resources = client
        .list_resources_page(None, STDIO_LIST_PAGE_LIMITS)
        .expect("the first exact-2024 stdio resources/list page must miss and reach the catalog");
    assert_eq!(
        first_resources.items.len(),
        1,
        "page size 1 must create a real resources continuation: {first_resources:?}"
    );
    let first_resource = first_resources.items[0].uri.clone();
    let resource_cursor = first_resources
        .next_cursor
        .clone()
        .expect("the first page-size-1 resources/list must carry an opaque cursor");
    let second_resources = client
        .list_resources_page(Some(&resource_cursor), STDIO_LIST_PAGE_LIMITS)
        .expect("the exact resources cursor continuation must reach the second live page");
    assert_eq!(
        second_resources.items.len(),
        1,
        "the resources continuation must retain one remaining resource: {second_resources:?}"
    );
    assert_ne!(
        second_resources.items[0].uri, first_resource,
        "the resources continuation must advance to a different URI: {second_resources:?}"
    );
    let rejected_prompts = client
        .list_prompts_page(Some(&resource_cursor), STDIO_LIST_PAGE_LIMITS)
        .expect_err("a resources/list cursor must not page prompts/list");
    let rejected_prompts = format!("{rejected_prompts:?}");
    assert!(
        rejected_prompts.contains("InvalidParams") || rejected_prompts.contains("invalid"),
        "a wrong-catalog resources cursor must stay InvalidParams: {rejected_prompts}"
    );

    let first_prompts = client
        .list_prompts_page(None, STDIO_LIST_PAGE_LIMITS)
        .expect("the first exact-2024 stdio prompts/list page must miss and reach the catalog");
    assert_eq!(
        first_prompts.items.len(),
        1,
        "page size 1 must create a real prompts continuation: {first_prompts:?}"
    );
    let first_prompt = first_prompts.items[0].name.clone();
    let prompt_cursor = first_prompts
        .next_cursor
        .clone()
        .expect("the first page-size-1 prompts/list must carry an opaque cursor");
    let second_prompts = client
        .list_prompts_page(Some(&prompt_cursor), STDIO_LIST_PAGE_LIMITS)
        .expect("the exact prompts cursor continuation must reach the second live page");
    assert_eq!(
        second_prompts.items.len(),
        1,
        "the prompts continuation must retain one remaining prompt: {second_prompts:?}"
    );
    assert_ne!(
        second_prompts.items[0].name, first_prompt,
        "the prompts continuation must advance to a different name: {second_prompts:?}"
    );
    let rejected_tools = client
        .list_tools_page(Some(&prompt_cursor), STDIO_LIST_PAGE_LIMITS)
        .expect_err("a prompts/list cursor must not page tools/list");
    let rejected_tools = format!("{rejected_tools:?}");
    assert!(
        rejected_tools.contains("InvalidParams") || rejected_tools.contains("invalid"),
        "a wrong-catalog prompts cursor must stay InvalidParams: {rejected_tools}"
    );

    let first_templates = client
        .list_resource_templates_page(None, STDIO_LIST_PAGE_LIMITS)
        .expect("the first exact-2024 stdio templates/list page must miss and reach the catalog");
    assert_eq!(
        first_templates.items.len(),
        1,
        "page size 1 must create a real templates continuation: {first_templates:?}"
    );
    let first_template = first_templates.items[0].uri_template.clone();
    let template_cursor = first_templates
        .next_cursor
        .clone()
        .expect("the first page-size-1 templates/list must carry an opaque cursor");
    let second_templates = client
        .list_resource_templates_page(Some(&template_cursor), STDIO_LIST_PAGE_LIMITS)
        .expect("the exact templates cursor continuation must reach the second live page");
    assert_eq!(
        second_templates.items.len(),
        1,
        "the templates continuation must retain one remaining template: {second_templates:?}"
    );
    assert_ne!(
        second_templates.items[0].uri_template, first_template,
        "the templates continuation must advance to a different URI template: {second_templates:?}"
    );
    let rejected_resources = client
        .list_resources_page(Some(&template_cursor), STDIO_LIST_PAGE_LIMITS)
        .expect_err("a templates/list cursor must not page resources/list");
    let rejected_resources = format!("{rejected_resources:?}");
    assert!(
        rejected_resources.contains("InvalidParams") || rejected_resources.contains("invalid"),
        "a wrong-catalog templates cursor must stay InvalidParams: {rejected_resources}"
    );

    client
        .close()
        .expect("legacy-only stdio catalog-paged client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_default_catalog_list_is_not_forced_to_page_size_one() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client connects to the unpaged echo peer");

    let resources = client
        .list_resources_page(None, STDIO_LIST_PAGE_LIMITS)
        .expect("omitting only FASTMCP_LIST_PAGE_SIZE must list the full first resources page");
    assert!(
        resources.items.len() > 1,
        "changing only the missing page-size flag must keep more than one resource on the first page: {resources:?}"
    );
    let prompts = client
        .list_prompts_page(None, STDIO_LIST_PAGE_LIMITS)
        .expect("omitting only FASTMCP_LIST_PAGE_SIZE must list the full first prompts page");
    assert!(
        prompts.items.len() > 1,
        "changing only the missing page-size flag must keep more than one prompt on the first page: {prompts:?}"
    );
    let templates = client
        .list_resource_templates_page(None, STDIO_LIST_PAGE_LIMITS)
        .expect("omitting only FASTMCP_LIST_PAGE_SIZE must list the full first templates page");
    assert!(
        templates.items.len() > 1,
        "changing only the missing page-size flag must keep more than one template on the first page: {templates:?}"
    );

    client
        .close()
        .expect("legacy-only stdio unpaged catalog client cleanup");
}

#[cfg(unix)]
const STDIO_PANIC_TOOL: &str = "panic_probe";
#[cfg(unix)]
const STDIO_PANIC_PAYLOAD: &str = "planted-handler-panic-payload";

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_handler_panic_is_sanitized_and_admits_fast_peer() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server_with_env(
        "modern-only",
        &[("FASTMCP_PANIC_TOOL", "1")],
    )
    .expect("a ModernOnly facade client connects to the panic-probe echo peer");

    let panicked = client
        .call_tool(STDIO_PANIC_TOOL, json!({}))
        .expect_err("a panicking tools/call must stay a protocol error");
    let panicked = format!("{panicked:?}");
    assert!(
        panicked.contains("Internal server error") || panicked.contains("InternalError"),
        "a handler panic must become the sanitized InternalError: {panicked}"
    );
    assert!(
        !panicked.contains(STDIO_PANIC_PAYLOAD),
        "a handler panic must not leak the unwind payload: {panicked}"
    );

    let peer = client
        .call_tool("echo", json!({"message": "after-panic"}))
        .expect("changing only the tool must still be admitted after a sanitized panic");
    assert_eq!(
        stdio_modern_tool_text(&peer),
        Some("after-panic"),
        "the peer echo must still complete after a sanitized panic: {peer:?}"
    );

    client
        .close()
        .expect("modern-only stdio handler-panic client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_handler_panic_is_sanitized_and_admits_fast_peer() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server_with_env(
        "legacy-only",
        &[("FASTMCP_PANIC_TOOL", "1")],
    )
    .expect("a LegacyOnly facade client connects to the panic-probe echo peer");

    let panicked = client
        .call_tool(STDIO_PANIC_TOOL, json!({}))
        .expect_err("a panicking exact-2024 tools/call must stay a protocol error");
    let panicked = format!("{panicked:?}");
    assert!(
        panicked.contains("Internal server error") || panicked.contains("InternalError"),
        "an exact-2024 handler panic must become the sanitized InternalError: {panicked}"
    );
    assert!(
        !panicked.contains(STDIO_PANIC_PAYLOAD),
        "an exact-2024 handler panic must not leak the unwind payload: {panicked}"
    );

    let peer = client
        .call_tool("echo", json!({"message": "after-panic"}))
        .expect("changing only the tool must still be admitted after a sanitized exact-2024 panic");
    assert_eq!(
        stdio_legacy_tool_text(&peer),
        Some("after-panic"),
        "the exact-2024 peer echo must still complete after a sanitized panic: {peer:?}"
    );

    client
        .close()
        .expect("legacy-only stdio handler-panic client cleanup");
}

#[cfg(unix)]
const STDIO_PANIC_RESOURCE_URI: &str = "info://panic";
#[cfg(unix)]
const STDIO_PANIC_PROMPT_NAME: &str = "panic_greeting";

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_catalog_panic_is_sanitized_and_admits_fast_peer() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server_with_env(
        "modern-only",
        &[("FASTMCP_PANIC_CATALOG", "1")],
    )
    .expect("a ModernOnly facade client connects to the panic-catalog echo peer");

    let panicked_resource = client
        .read_resource(STDIO_PANIC_RESOURCE_URI)
        .expect_err("a panicking resources/read must stay a protocol error");
    let panicked_resource = format!("{panicked_resource:?}");
    assert!(
        panicked_resource.contains("Internal server error")
            || panicked_resource.contains("InternalError"),
        "a resource panic must become the sanitized InternalError: {panicked_resource}"
    );
    assert!(
        !panicked_resource.contains(STDIO_PANIC_PAYLOAD),
        "a resource panic must not leak the unwind payload: {panicked_resource}"
    );

    let panicked_prompt = client
        .get_prompt(STDIO_PANIC_PROMPT_NAME, HashMap::new())
        .expect_err("a panicking prompts/get must stay a protocol error");
    let panicked_prompt = format!("{panicked_prompt:?}");
    assert!(
        panicked_prompt.contains("Internal server error")
            || panicked_prompt.contains("InternalError"),
        "a prompt panic must become the sanitized InternalError: {panicked_prompt}"
    );
    assert!(
        !panicked_prompt.contains(STDIO_PANIC_PAYLOAD),
        "a prompt panic must not leak the unwind payload: {panicked_prompt}"
    );

    let peer_resource = client
        .read_resource("info://server")
        .expect("changing only the resource must still be admitted after a sanitized panic");
    let peer_resource = format!("{peer_resource:?}");
    assert!(
        peer_resource.contains("echo-server") || peer_resource.contains("info://server"),
        "the peer resource must still complete after a sanitized catalog panic: {peer_resource}"
    );

    let peer_prompt = client
        .get_prompt(
            "greeting",
            HashMap::from([("name".to_owned(), "World".to_owned())]),
        )
        .expect("changing only the prompt must still be admitted after a sanitized panic");
    let peer_prompt = format!("{peer_prompt:?}");
    assert!(
        peer_prompt.contains("World") || peer_prompt.contains("greet"),
        "the peer prompt must still complete after a sanitized catalog panic: {peer_prompt}"
    );

    client
        .close()
        .expect("modern-only stdio catalog-panic client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_catalog_panic_is_sanitized_and_admits_fast_peer() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server_with_env(
        "legacy-only",
        &[("FASTMCP_PANIC_CATALOG", "1")],
    )
    .expect("a LegacyOnly facade client connects to the panic-catalog echo peer");

    let panicked_resource = client
        .read_resource(STDIO_PANIC_RESOURCE_URI)
        .expect_err("a panicking exact-2024 resources/read must stay a protocol error");
    let panicked_resource = format!("{panicked_resource:?}");
    assert!(
        panicked_resource.contains("Internal server error")
            || panicked_resource.contains("InternalError"),
        "an exact-2024 resource panic must become the sanitized InternalError: {panicked_resource}"
    );
    assert!(
        !panicked_resource.contains(STDIO_PANIC_PAYLOAD),
        "an exact-2024 resource panic must not leak the unwind payload: {panicked_resource}"
    );

    let panicked_prompt = client
        .get_prompt(STDIO_PANIC_PROMPT_NAME, HashMap::new())
        .expect_err("a panicking exact-2024 prompts/get must stay a protocol error");
    let panicked_prompt = format!("{panicked_prompt:?}");
    assert!(
        panicked_prompt.contains("Internal server error")
            || panicked_prompt.contains("InternalError"),
        "an exact-2024 prompt panic must become the sanitized InternalError: {panicked_prompt}"
    );
    assert!(
        !panicked_prompt.contains(STDIO_PANIC_PAYLOAD),
        "an exact-2024 prompt panic must not leak the unwind payload: {panicked_prompt}"
    );

    let peer_resource = client.read_resource("info://server").expect(
        "changing only the resource must still be admitted after a sanitized exact-2024 panic",
    );
    let peer_resource = format!("{peer_resource:?}");
    assert!(
        peer_resource.contains("echo-server") || peer_resource.contains("info://server"),
        "the exact-2024 peer resource must still complete after a sanitized catalog panic: {peer_resource}"
    );

    let peer_prompt = client
        .get_prompt(
            "greeting",
            HashMap::from([("name".to_owned(), "World".to_owned())]),
        )
        .expect(
            "changing only the prompt must still be admitted after a sanitized exact-2024 panic",
        );
    let peer_prompt = format!("{peer_prompt:?}");
    assert!(
        peer_prompt.contains("World") || peer_prompt.contains("greet"),
        "the exact-2024 peer prompt must still complete after a sanitized catalog panic: {peer_prompt}"
    );

    client
        .close()
        .expect("legacy-only stdio catalog-panic client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_completion_panic_is_sanitized_and_admits_fast_peer() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server_with_env(
        "modern-only",
        &[("FASTMCP_PANIC_COMPLETE", "1")],
    )
    .expect("a ModernOnly facade client connects to the panic-complete echo peer");

    let params = modern::CompletionParams {
        reference: modern::CompletionReference::PromptWithTitle {
            name: "greeting".to_owned(),
            title: "Greeting".to_owned(),
        },
        argument: modern::FinalCompletionArgument {
            name: "name".to_owned(),
            value: "co".to_owned(),
        },
        context: Some(modern::FinalCompletionContext {
            arguments: Some(std::collections::BTreeMap::from([(
                "locale".to_owned(),
                "en-US".to_owned(),
            )])),
        }),
    };
    let panicked = client
        .complete(params)
        .expect_err("a panicking completion/complete must stay a protocol error");
    let panicked = format!("{panicked:?}");
    assert!(
        panicked.contains("Internal server error") || panicked.contains("InternalError"),
        "a completion panic must become the sanitized InternalError: {panicked}"
    );
    assert!(
        !panicked.contains(STDIO_PANIC_PAYLOAD),
        "a completion panic must not leak the unwind payload: {panicked}"
    );

    let peer = client
        .call_tool("echo", json!({"message": "after-complete-panic"}))
        .expect(
            "changing only the method must still be admitted after a sanitized completion panic",
        );
    assert_eq!(
        stdio_modern_tool_text(&peer),
        Some("after-complete-panic"),
        "the peer echo must still complete after a sanitized completion panic: {peer:?}"
    );

    client
        .close()
        .expect("modern-only stdio completion-panic client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_completion_panic_is_sanitized_and_admits_fast_peer() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server_with_env(
        "legacy-only",
        &[("FASTMCP_PANIC_COMPLETE", "1")],
    )
    .expect("a LegacyOnly facade client connects to the panic-complete echo peer");

    let panicked = client
        .complete(legacy_2024::LegacyCompletionParams {
            reference: legacy_2024::LegacyCompletionReference::Prompt {
                name: "greeting".to_owned(),
            },
            argument: legacy_2024::LegacyCompletionArgument {
                name: "name".to_owned(),
                value: "co".to_owned(),
            },
            meta: None,
        })
        .expect_err("a panicking exact-2024 completion/complete must stay a protocol error");
    let panicked = format!("{panicked:?}");
    assert!(
        panicked.contains("Internal server error") || panicked.contains("InternalError"),
        "an exact-2024 completion panic must become the sanitized InternalError: {panicked}"
    );
    assert!(
        !panicked.contains(STDIO_PANIC_PAYLOAD),
        "an exact-2024 completion panic must not leak the unwind payload: {panicked}"
    );

    let peer = client
        .call_tool("echo", json!({"message": "after-complete-panic"}))
        .expect("changing only the method must still be admitted after a sanitized exact-2024 completion panic");
    assert_eq!(
        stdio_legacy_tool_text(&peer),
        Some("after-complete-panic"),
        "the exact-2024 peer echo must still complete after a sanitized completion panic: {peer:?}"
    );

    client
        .close()
        .expect("legacy-only stdio completion-panic client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_default_catalog_does_not_register_panic_probe() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client connects to the default echo peer");

    let missing = client
        .call_tool(STDIO_PANIC_TOOL, json!({}))
        .expect_err("omitting only FASTMCP_PANIC_TOOL must keep panic_probe unregistered");
    let missing = format!("{missing:?}");
    assert!(
        missing.contains("not found")
            || missing.contains("MethodNotFound")
            || missing.contains("ToolNotFound")
            || missing.contains("Unknown"),
        "changing only the missing panic-tool flag must stay a missing-tool refusal: {missing}"
    );
    assert!(
        !missing.contains(STDIO_PANIC_PAYLOAD),
        "an unregistered panic_probe must not leak the unwind payload: {missing}"
    );

    let peer = client
        .call_tool("echo", json!({"message": "no-panic-tool"}))
        .expect("the default catalog must still admit echo");
    assert_eq!(
        stdio_modern_tool_text(&peer),
        Some("no-panic-tool"),
        "omitting only FASTMCP_PANIC_TOOL must keep echo admitted: {peer:?}"
    );

    client
        .close()
        .expect("modern-only stdio missing panic-probe client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_default_catalog_does_not_register_panic_probe() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client connects to the default echo peer");

    let missing = client.call_tool(STDIO_PANIC_TOOL, json!({})).expect_err(
        "omitting only FASTMCP_PANIC_TOOL must keep exact-2024 panic_probe unregistered",
    );
    let missing = format!("{missing:?}");
    assert!(
        missing.contains("not found")
            || missing.contains("MethodNotFound")
            || missing.contains("ToolNotFound")
            || missing.contains("Unknown"),
        "changing only the missing panic-tool flag must stay a missing-tool refusal: {missing}"
    );
    assert!(
        !missing.contains(STDIO_PANIC_PAYLOAD),
        "an unregistered exact-2024 panic_probe must not leak the unwind payload: {missing}"
    );

    let peer = client
        .call_tool("echo", json!({"message": "no-panic-tool"}))
        .expect("the exact-2024 default catalog must still admit echo");
    assert_eq!(
        stdio_legacy_tool_text(&peer),
        Some("no-panic-tool"),
        "omitting only FASTMCP_PANIC_TOOL must keep exact-2024 echo admitted: {peer:?}"
    );

    client
        .close()
        .expect("legacy-only stdio missing panic-probe client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_transformed_echo_renames_argument() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server_with_env(
        "modern-only",
        &[("FASTMCP_TRANSFORM_ECHO", "1")],
    )
    .expect("a ModernOnly facade client connects to the transformed echo peer");

    let renamed = client
        .call_tool("echo_text", json!({"text": "alpha"}))
        .expect("the renamed argument must reach the parent echo handler");
    assert_eq!(
        stdio_modern_tool_text(&renamed),
        Some("alpha"),
        "rename_arg must rewrite text back to message: {renamed:?}"
    );

    let stale = client.call_tool("echo_text", json!({"message": "alpha"}));
    let stale = match stale {
        Ok(result) => format!("{result:?}"),
        Err(error) => format!("{error:?}"),
    };
    assert!(
        stale.contains("InvalidParams")
            || stale.contains("required")
            || stale.contains("message")
            || stale.contains("text")
            || stale.contains("is_error")
            || stale.contains("error"),
        "calling the pre-rename argument name must fail: {stale}"
    );

    let parent = client
        .call_tool("echo", json!({"message": "alpha"}))
        .expect("the parent echo must stay registered beside the transform");
    assert_eq!(
        stdio_modern_tool_text(&parent),
        Some("alpha"),
        "the parent echo must keep the original argument name: {parent:?}"
    );

    client
        .close()
        .expect("modern-only stdio transformed-echo client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_transformed_echo_renames_argument() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server_with_env(
        "legacy-only",
        &[("FASTMCP_TRANSFORM_ECHO", "1")],
    )
    .expect("a LegacyOnly facade client connects to the transformed echo peer");

    let renamed = client
        .call_tool("echo_text", json!({"text": "alpha"}))
        .expect("the renamed argument must reach the parent echo handler");
    assert_eq!(
        stdio_legacy_tool_text(&renamed),
        Some("alpha"),
        "rename_arg must rewrite text back to message: {renamed:?}"
    );

    let stale = client.call_tool("echo_text", json!({"message": "alpha"}));
    let stale = match stale {
        Ok(result) => format!("{result:?}"),
        Err(error) => format!("{error:?}"),
    };
    assert!(
        stale.contains("InvalidParams")
            || stale.contains("required")
            || stale.contains("message")
            || stale.contains("text")
            || stale.contains("is_error")
            || stale.contains("error"),
        "calling the pre-rename argument name must fail: {stale}"
    );

    let parent = client
        .call_tool("echo", json!({"message": "alpha"}))
        .expect("the parent echo must stay registered beside the transform");
    assert_eq!(
        stdio_legacy_tool_text(&parent),
        Some("alpha"),
        "the parent echo must keep the original argument name: {parent:?}"
    );

    client
        .close()
        .expect("legacy-only stdio transformed-echo client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_transformed_echo_hides_argument_and_injects_default() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server_with_env(
        "modern-only",
        &[("FASTMCP_TRANSFORM_HIDE", "1")],
    )
    .expect("a ModernOnly facade client connects to the hide-arg echo peer");

    let injected = client
        .call_tool("echo_hidden", json!({}))
        .expect("the hide-arg tools/call must inject the configured default");
    assert_eq!(
        stdio_modern_tool_text(&injected),
        Some("hidden-default"),
        "the hidden default must reach the parent echo handler: {injected:?}"
    );

    let parent = client
        .call_tool("echo", json!({"message": "alpha"}))
        .expect("the parent echo must stay registered beside the hide-arg transform");
    assert_eq!(
        stdio_modern_tool_text(&parent),
        Some("alpha"),
        "the parent echo must keep the original argument: {parent:?}"
    );

    client
        .close()
        .expect("modern-only stdio hide-arg client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_transformed_echo_hides_argument_and_injects_default() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server_with_env(
        "legacy-only",
        &[("FASTMCP_TRANSFORM_HIDE", "1")],
    )
    .expect("a LegacyOnly facade client connects to the hide-arg echo peer");

    let injected = client
        .call_tool("echo_hidden", json!({}))
        .expect("the hide-arg tools/call must inject the configured default");
    assert_eq!(
        stdio_legacy_tool_text(&injected),
        Some("hidden-default"),
        "the hidden default must reach the parent echo handler: {injected:?}"
    );

    let parent = client
        .call_tool("echo", json!({"message": "alpha"}))
        .expect("the parent echo must stay registered beside the hide-arg transform");
    assert_eq!(
        stdio_legacy_tool_text(&parent),
        Some("alpha"),
        "the parent echo must keep the original argument: {parent:?}"
    );

    client
        .close()
        .expect("legacy-only stdio hide-arg client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_hide_arg_schema_drops_message() {
    let mut client = connect_modern_stdio_to_shipped_echo_server_with_env(
        "modern-only",
        &[("FASTMCP_TRANSFORM_HIDE", "1")],
    )
    .expect("a ModernOnly facade client connects to the hide-arg echo peer");

    let listed = client
        .list_tools(None)
        .expect("hide-arg catalog must list echo_hidden");
    let hidden = listed
        .tools
        .iter()
        .find(|tool| tool.name == "echo_hidden")
        .unwrap_or_else(|| panic!("the hide-arg catalog must advertise echo_hidden: {listed:?}"));
    let schema =
        serde_json::to_string(&hidden.input_schema).expect("the hide-arg schema serializes");
    assert!(
        !schema.contains("\"message\""),
        "the hide-arg schema must drop the hidden argument: {schema}"
    );
    let parent = listed
        .tools
        .iter()
        .find(|tool| tool.name == "echo")
        .unwrap_or_else(|| panic!("the parent echo must stay listed: {listed:?}"));
    let parent_schema =
        serde_json::to_string(&parent.input_schema).expect("the parent schema serializes");
    assert!(
        parent_schema.contains("\"message\""),
        "the parent echo schema must keep message: {parent_schema}"
    );

    client
        .close()
        .expect("modern-only stdio hide-arg schema client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_hide_arg_schema_drops_message() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server_with_env(
        "legacy-only",
        &[("FASTMCP_TRANSFORM_HIDE", "1")],
    )
    .expect("a LegacyOnly facade client connects to the hide-arg echo peer");

    let listed = client
        .list_tools()
        .expect("hide-arg catalog must list echo_hidden");
    let hidden = listed
        .iter()
        .find(|tool| tool.name == "echo_hidden")
        .unwrap_or_else(|| panic!("the hide-arg catalog must advertise echo_hidden: {listed:?}"));
    let schema =
        serde_json::to_string(&hidden.input_schema).expect("the hide-arg schema serializes");
    assert!(
        !schema.contains("\"message\""),
        "the hide-arg schema must drop the hidden argument: {schema}"
    );
    let parent = listed
        .iter()
        .find(|tool| tool.name == "echo")
        .unwrap_or_else(|| panic!("the parent echo must stay listed: {listed:?}"));
    let parent_schema =
        serde_json::to_string(&parent.input_schema).expect("the parent schema serializes");
    assert!(
        parent_schema.contains("\"message\""),
        "the parent echo schema must keep message: {parent_schema}"
    );

    client
        .close()
        .expect("legacy-only stdio hide-arg schema client cleanup");
}

#[cfg(unix)]
fn stdio_tool_list_params(include: Option<&[&str]>, exclude: Option<&[&str]>) -> ListToolsParams {
    ListToolsParams {
        include_tags: include.map(|tags| tags.iter().map(|tag| (*tag).to_owned()).collect()),
        exclude_tags: exclude.map(|tags| tags.iter().map(|tag| (*tag).to_owned()).collect()),
        ..ListToolsParams::default()
    }
}

#[cfg(unix)]
fn stdio_resource_list_params(
    include: Option<&[&str]>,
    exclude: Option<&[&str]>,
) -> ListResourcesParams {
    ListResourcesParams {
        include_tags: include.map(|tags| tags.iter().map(|tag| (*tag).to_owned()).collect()),
        exclude_tags: exclude.map(|tags| tags.iter().map(|tag| (*tag).to_owned()).collect()),
        ..ListResourcesParams::default()
    }
}

#[cfg(unix)]
fn stdio_prompt_list_params(
    include: Option<&[&str]>,
    exclude: Option<&[&str]>,
) -> ListPromptsParams {
    ListPromptsParams {
        include_tags: include.map(|tags| tags.iter().map(|tag| (*tag).to_owned()).collect()),
        exclude_tags: exclude.map(|tags| tags.iter().map(|tag| (*tag).to_owned()).collect()),
        ..ListPromptsParams::default()
    }
}

#[cfg(unix)]
fn stdio_template_list_params(
    include: Option<&[&str]>,
    exclude: Option<&[&str]>,
) -> ListResourceTemplatesParams {
    ListResourceTemplatesParams {
        include_tags: include.map(|tags| tags.iter().map(|tag| (*tag).to_owned()).collect()),
        exclude_tags: exclude.map(|tags| tags.iter().map(|tag| (*tag).to_owned()).collect()),
        ..ListResourceTemplatesParams::default()
    }
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_list_tools_include_and_exclude_tags() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client connects to the tagged echo peer");

    let demo = client
        .list_tools_with_params(stdio_tool_list_params(Some(&["demo"]), None))
        .expect("includeTags demo must list the tagged echo tool");
    assert!(
        demo.tools.iter().any(|tool| tool.name == "echo"),
        "includeTags demo must retain echo: {demo:?}"
    );
    assert!(
        demo.tools.iter().all(|tool| tool.name != "add"),
        "includeTags demo must omit add: {demo:?}"
    );

    let math = client
        .list_tools_with_params(stdio_tool_list_params(Some(&["math"]), None))
        .expect("changing only includeTags must list the math-tagged add tool");
    assert!(
        math.tools.iter().any(|tool| tool.name == "add"),
        "includeTags math must retain add: {math:?}"
    );
    assert!(
        math.tools.iter().all(|tool| tool.name != "echo"),
        "includeTags math must omit echo: {math:?}"
    );

    let excluded = client
        .list_tools_with_params(stdio_tool_list_params(None, Some(&["demo"])))
        .expect("excludeTags demo must omit only the demo-tagged tool");
    assert!(
        excluded.tools.iter().any(|tool| tool.name == "add"),
        "excludeTags demo must keep add: {excluded:?}"
    );
    assert!(
        excluded.tools.iter().all(|tool| tool.name != "echo"),
        "excludeTags demo must omit echo: {excluded:?}"
    );

    let listed = client
        .list_tools(None)
        .expect("an unfiltered modern tools/list must keep both tagged tools");
    assert!(
        listed.tools.iter().any(|tool| tool.name == "echo")
            && listed.tools.iter().any(|tool| tool.name == "add"),
        "omitting only the tag filters must list echo and add: {listed:?}"
    );

    client
        .close()
        .expect("modern-only stdio tag-filter client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_list_tools_include_and_exclude_tags() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client connects to the tagged echo peer");

    let demo = client
        .list_tools_with_params(stdio_tool_list_params(Some(&["demo"]), None))
        .expect("includeTags demo must list the tagged echo tool");
    assert!(
        demo.iter().any(|tool| tool.name == "echo"),
        "includeTags demo must retain echo: {demo:?}"
    );
    assert!(
        demo.iter().all(|tool| tool.name != "add"),
        "includeTags demo must omit add: {demo:?}"
    );
    assert!(
        demo.iter()
            .any(|tool| tool.name == "echo" && tool.tags.iter().any(|tag| tag == "demo")),
        "exact-2024 includeTags must retain the demo tag on echo: {demo:?}"
    );

    let math = client
        .list_tools_with_params(stdio_tool_list_params(Some(&["math"]), None))
        .expect("changing only includeTags must list the math-tagged add tool");
    assert!(
        math.iter().any(|tool| tool.name == "add"),
        "includeTags math must retain add: {math:?}"
    );
    assert!(
        math.iter().all(|tool| tool.name != "echo"),
        "includeTags math must omit echo: {math:?}"
    );

    let excluded = client
        .list_tools_with_params(stdio_tool_list_params(None, Some(&["demo"])))
        .expect("excludeTags demo must omit only the demo-tagged tool");
    assert!(
        excluded.iter().any(|tool| tool.name == "add"),
        "excludeTags demo must keep add: {excluded:?}"
    );
    assert!(
        excluded.iter().all(|tool| tool.name != "echo"),
        "excludeTags demo must omit echo: {excluded:?}"
    );

    let listed = client
        .list_tools()
        .expect("an unfiltered exact-2024 tools/list must keep both tagged tools");
    assert!(
        listed.iter().any(|tool| tool.name == "echo")
            && listed.iter().any(|tool| tool.name == "add"),
        "omitting only the tag filters must list echo and add: {listed:?}"
    );

    client
        .close()
        .expect("legacy-only stdio tag-filter client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_list_resources_include_and_exclude_tags() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client connects to the tagged echo peer");

    let server = client
        .list_resources_with_params(stdio_resource_list_params(Some(&["server"]), None))
        .expect("includeTags server must list the tagged info://server resource");
    assert!(
        server
            .resources
            .iter()
            .any(|resource| resource.uri.as_str() == "info://server"),
        "includeTags server must retain info://server: {server:?}"
    );
    assert!(
        server
            .resources
            .iter()
            .all(|resource| resource.uri.as_str() != "info://leak"),
        "includeTags server must omit info://leak: {server:?}"
    );

    let secret = client
        .list_resources_with_params(stdio_resource_list_params(Some(&["secret"]), None))
        .expect("changing only includeTags must list the secret-tagged leak resource");
    assert!(
        secret
            .resources
            .iter()
            .any(|resource| resource.uri.as_str() == "info://leak"),
        "includeTags secret must retain info://leak: {secret:?}"
    );
    assert!(
        secret
            .resources
            .iter()
            .all(|resource| resource.uri.as_str() != "info://server"),
        "includeTags secret must omit info://server: {secret:?}"
    );

    let excluded = client
        .list_resources_with_params(stdio_resource_list_params(None, Some(&["server"])))
        .expect("excludeTags server must omit only the server-tagged resource");
    assert!(
        excluded
            .resources
            .iter()
            .any(|resource| resource.uri.as_str() == "info://leak"),
        "excludeTags server must keep info://leak: {excluded:?}"
    );
    assert!(
        excluded
            .resources
            .iter()
            .all(|resource| resource.uri.as_str() != "info://server"),
        "excludeTags server must omit info://server: {excluded:?}"
    );

    let listed = client
        .list_resources(None)
        .expect("an unfiltered modern resources/list must keep both tagged resources");
    assert!(
        listed
            .resources
            .iter()
            .any(|resource| resource.uri.as_str() == "info://server")
            && listed
                .resources
                .iter()
                .any(|resource| resource.uri.as_str() == "info://leak"),
        "omitting only the tag filters must list info://server and info://leak: {listed:?}"
    );

    client
        .close()
        .expect("modern-only stdio resource tag-filter client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_list_resources_include_and_exclude_tags() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client connects to the tagged echo peer");

    let server = client
        .list_resources_with_params(stdio_resource_list_params(Some(&["server"]), None))
        .expect("includeTags server must list the tagged info://server resource");
    assert!(
        server
            .iter()
            .any(|resource| resource.uri == "info://server"),
        "includeTags server must retain info://server: {server:?}"
    );
    assert!(
        server.iter().all(|resource| resource.uri != "info://leak"),
        "includeTags server must omit info://leak: {server:?}"
    );
    assert!(
        server.iter().any(|resource| resource.uri == "info://server"
            && resource.tags.iter().any(|tag| tag == "server")),
        "exact-2024 includeTags must retain the server tag on info://server: {server:?}"
    );

    let secret = client
        .list_resources_with_params(stdio_resource_list_params(Some(&["secret"]), None))
        .expect("changing only includeTags must list the secret-tagged leak resource");
    assert!(
        secret.iter().any(|resource| resource.uri == "info://leak"),
        "includeTags secret must retain info://leak: {secret:?}"
    );
    assert!(
        secret
            .iter()
            .all(|resource| resource.uri != "info://server"),
        "includeTags secret must omit info://server: {secret:?}"
    );

    let excluded = client
        .list_resources_with_params(stdio_resource_list_params(None, Some(&["server"])))
        .expect("excludeTags server must omit only the server-tagged resource");
    assert!(
        excluded
            .iter()
            .any(|resource| resource.uri == "info://leak"),
        "excludeTags server must keep info://leak: {excluded:?}"
    );
    assert!(
        excluded
            .iter()
            .all(|resource| resource.uri != "info://server"),
        "excludeTags server must omit info://server: {excluded:?}"
    );

    let listed = client
        .list_resources()
        .expect("an unfiltered exact-2024 resources/list must keep both tagged resources");
    assert!(
        listed
            .iter()
            .any(|resource| resource.uri == "info://server")
            && listed.iter().any(|resource| resource.uri == "info://leak"),
        "omitting only the tag filters must list info://server and info://leak: {listed:?}"
    );

    client
        .close()
        .expect("legacy-only stdio resource tag-filter client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_list_prompts_include_and_exclude_tags() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client connects to the tagged echo peer");

    let onboarding = client
        .list_prompts_with_params(stdio_prompt_list_params(Some(&["onboarding"]), None))
        .expect("includeTags onboarding must list the tagged greeting prompt");
    assert!(
        onboarding
            .prompts
            .iter()
            .any(|prompt| prompt.name == "greeting"),
        "includeTags onboarding must retain greeting: {onboarding:?}"
    );
    assert!(
        onboarding
            .prompts
            .iter()
            .all(|prompt| prompt.name != "compose_greeting"),
        "includeTags onboarding must omit compose_greeting: {onboarding:?}"
    );

    let compose = client
        .list_prompts_with_params(stdio_prompt_list_params(Some(&["compose"]), None))
        .expect("changing only includeTags must list the compose-tagged prompt");
    assert!(
        compose
            .prompts
            .iter()
            .any(|prompt| prompt.name == "compose_greeting"),
        "includeTags compose must retain compose_greeting: {compose:?}"
    );
    assert!(
        compose
            .prompts
            .iter()
            .all(|prompt| prompt.name != "greeting"),
        "includeTags compose must omit greeting: {compose:?}"
    );

    let excluded = client
        .list_prompts_with_params(stdio_prompt_list_params(None, Some(&["onboarding"])))
        .expect("excludeTags onboarding must omit only the onboarding-tagged prompt");
    assert!(
        excluded
            .prompts
            .iter()
            .any(|prompt| prompt.name == "compose_greeting"),
        "excludeTags onboarding must keep compose_greeting: {excluded:?}"
    );
    assert!(
        excluded
            .prompts
            .iter()
            .all(|prompt| prompt.name != "greeting"),
        "excludeTags onboarding must omit greeting: {excluded:?}"
    );

    let listed = client
        .list_prompts(None)
        .expect("an unfiltered modern prompts/list must keep both tagged prompts");
    assert!(
        listed
            .prompts
            .iter()
            .any(|prompt| prompt.name == "greeting")
            && listed
                .prompts
                .iter()
                .any(|prompt| prompt.name == "compose_greeting"),
        "omitting only the tag filters must list greeting and compose_greeting: {listed:?}"
    );

    client
        .close()
        .expect("modern-only stdio prompt tag-filter client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_list_prompts_include_and_exclude_tags() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client connects to the tagged echo peer");

    let onboarding = client
        .list_prompts_with_params(stdio_prompt_list_params(Some(&["onboarding"]), None))
        .expect("includeTags onboarding must list the tagged greeting prompt");
    assert!(
        onboarding.iter().any(|prompt| prompt.name == "greeting"),
        "includeTags onboarding must retain greeting: {onboarding:?}"
    );
    assert!(
        onboarding
            .iter()
            .all(|prompt| prompt.name != "compose_greeting"),
        "includeTags onboarding must omit compose_greeting: {onboarding:?}"
    );
    assert!(
        onboarding
            .iter()
            .any(|prompt| prompt.name == "greeting"
                && prompt.tags.iter().any(|tag| tag == "onboarding")),
        "exact-2024 includeTags must retain the onboarding tag on greeting: {onboarding:?}"
    );

    let compose = client
        .list_prompts_with_params(stdio_prompt_list_params(Some(&["compose"]), None))
        .expect("changing only includeTags must list the compose-tagged prompt");
    assert!(
        compose
            .iter()
            .any(|prompt| prompt.name == "compose_greeting"),
        "includeTags compose must retain compose_greeting: {compose:?}"
    );
    assert!(
        compose.iter().all(|prompt| prompt.name != "greeting"),
        "includeTags compose must omit greeting: {compose:?}"
    );

    let excluded = client
        .list_prompts_with_params(stdio_prompt_list_params(None, Some(&["onboarding"])))
        .expect("excludeTags onboarding must omit only the onboarding-tagged prompt");
    assert!(
        excluded
            .iter()
            .any(|prompt| prompt.name == "compose_greeting"),
        "excludeTags onboarding must keep compose_greeting: {excluded:?}"
    );
    assert!(
        excluded.iter().all(|prompt| prompt.name != "greeting"),
        "excludeTags onboarding must omit greeting: {excluded:?}"
    );

    let listed = client
        .list_prompts()
        .expect("an unfiltered exact-2024 prompts/list must keep both tagged prompts");
    assert!(
        listed.iter().any(|prompt| prompt.name == "greeting")
            && listed
                .iter()
                .any(|prompt| prompt.name == "compose_greeting"),
        "omitting only the tag filters must list greeting and compose_greeting: {listed:?}"
    );

    client
        .close()
        .expect("legacy-only stdio prompt tag-filter client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_list_resource_templates_include_and_exclude_tags() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client connects to the tagged echo peer");

    let notes = client
        .list_resource_templates_with_params(stdio_template_list_params(Some(&["notes"]), None))
        .expect("includeTags notes must list the note template");
    assert!(
        notes
            .resource_templates
            .iter()
            .any(|template| template.uri_template == "note://{name}"),
        "includeTags notes must retain note://{{name}}: {notes:?}"
    );
    assert!(
        notes
            .resource_templates
            .iter()
            .all(|template| template.uri_template != "memo://{name}"),
        "includeTags notes must omit memo://{{name}}: {notes:?}"
    );

    let memos = client
        .list_resource_templates_with_params(stdio_template_list_params(Some(&["memos"]), None))
        .expect("changing only includeTags must list the memo template");
    assert!(
        memos
            .resource_templates
            .iter()
            .any(|template| template.uri_template == "memo://{name}"),
        "includeTags memos must retain memo://{{name}}: {memos:?}"
    );
    assert!(
        memos
            .resource_templates
            .iter()
            .all(|template| template.uri_template != "note://{name}"),
        "includeTags memos must omit note://{{name}}: {memos:?}"
    );

    let excluded = client
        .list_resource_templates_with_params(stdio_template_list_params(None, Some(&["notes"])))
        .expect("excludeTags notes must omit only the notes template");
    assert!(
        excluded
            .resource_templates
            .iter()
            .any(|template| template.uri_template == "memo://{name}"),
        "excludeTags notes must keep memo://{{name}}: {excluded:?}"
    );
    assert!(
        excluded
            .resource_templates
            .iter()
            .all(|template| template.uri_template != "note://{name}"),
        "excludeTags notes must omit note://{{name}}: {excluded:?}"
    );

    let listed = client
        .list_resource_templates(None)
        .expect("an unfiltered modern templates/list must keep both tagged templates");
    assert!(
        listed
            .resource_templates
            .iter()
            .any(|template| template.uri_template == "note://{name}")
            && listed
                .resource_templates
                .iter()
                .any(|template| template.uri_template == "memo://{name}"),
        "omitting only the tag filters must list note and memo templates: {listed:?}"
    );

    client
        .close()
        .expect("modern-only stdio template tag-filter client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_list_resource_templates_include_and_exclude_tags() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client connects to the tagged echo peer");

    let notes = client
        .list_resource_templates_with_params(stdio_template_list_params(Some(&["notes"]), None))
        .expect("includeTags notes must list the note template");
    assert!(
        notes
            .iter()
            .any(|template| template.uri_template == "note://{name}"),
        "includeTags notes must retain note://{{name}}: {notes:?}"
    );
    assert!(
        notes
            .iter()
            .all(|template| template.uri_template != "memo://{name}"),
        "includeTags notes must omit memo://{{name}}: {notes:?}"
    );
    assert!(
        notes
            .iter()
            .any(|template| template.uri_template == "note://{name}"
                && template.tags.iter().any(|tag| tag == "notes")),
        "exact-2024 includeTags must retain the notes tag on note://{{name}}: {notes:?}"
    );

    let memos = client
        .list_resource_templates_with_params(stdio_template_list_params(Some(&["memos"]), None))
        .expect("changing only includeTags must list the memo template");
    assert!(
        memos
            .iter()
            .any(|template| template.uri_template == "memo://{name}"),
        "includeTags memos must retain memo://{{name}}: {memos:?}"
    );
    assert!(
        memos
            .iter()
            .all(|template| template.uri_template != "note://{name}"),
        "includeTags memos must omit note://{{name}}: {memos:?}"
    );

    let excluded = client
        .list_resource_templates_with_params(stdio_template_list_params(None, Some(&["notes"])))
        .expect("excludeTags notes must omit only the notes template");
    assert!(
        excluded
            .iter()
            .any(|template| template.uri_template == "memo://{name}"),
        "excludeTags notes must keep memo://{{name}}: {excluded:?}"
    );
    assert!(
        excluded
            .iter()
            .all(|template| template.uri_template != "note://{name}"),
        "excludeTags notes must omit note://{{name}}: {excluded:?}"
    );

    let listed = client
        .list_resource_templates()
        .expect("an unfiltered exact-2024 templates/list must keep both tagged templates");
    assert!(
        listed
            .iter()
            .any(|template| template.uri_template == "note://{name}")
            && listed
                .iter()
                .any(|template| template.uri_template == "memo://{name}"),
        "omitting only the tag filters must list note and memo templates: {listed:?}"
    );

    client
        .close()
        .expect("legacy-only stdio template tag-filter client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_list_catalog_include_tags_honor_cancellation_domain() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client connects before tagged catalog cancellation");
    let cx = Cx::for_request();
    let live = fastmcp_rust::McpRequestCancellation::new();

    let server = client
        .list_resources_with_params_and_cancellation(
            &cx,
            &live,
            stdio_resource_list_params(Some(&["server"]), None),
        )
        .expect("an uncancelled domain must still send includeTags on resources/list");
    assert!(
        server
            .resources
            .iter()
            .any(|resource| resource.uri.as_str() == "info://server"),
        "live cancellation domain plus includeTags server must retain info://server: {server:?}"
    );
    assert!(
        server
            .resources
            .iter()
            .all(|resource| resource.uri.as_str() != "info://leak"),
        "live cancellation domain plus includeTags server must omit info://leak: {server:?}"
    );

    let onboarding = client
        .list_prompts_with_params_and_cancellation(
            &cx,
            &live,
            stdio_prompt_list_params(Some(&["onboarding"]), None),
        )
        .expect("an uncancelled domain must still send includeTags on prompts/list");
    assert!(
        onboarding
            .prompts
            .iter()
            .any(|prompt| prompt.name == "greeting"),
        "live cancellation domain plus includeTags onboarding must retain greeting: {onboarding:?}"
    );
    assert!(
        onboarding
            .prompts
            .iter()
            .all(|prompt| prompt.name != "compose_greeting"),
        "live cancellation domain plus includeTags onboarding must omit compose_greeting: {onboarding:?}"
    );

    let notes = client
        .list_resource_templates_with_params_and_cancellation(
            &cx,
            &live,
            stdio_template_list_params(Some(&["notes"]), None),
        )
        .expect("an uncancelled domain must still send includeTags on resources/templates/list");
    assert!(
        notes
            .resource_templates
            .iter()
            .any(|template| template.uri_template == "note://{name}"),
        "live cancellation domain plus includeTags notes must retain note://{{name}}: {notes:?}"
    );
    assert!(
        notes
            .resource_templates
            .iter()
            .all(|template| template.uri_template != "memo://{name}"),
        "live cancellation domain plus includeTags notes must omit memo://{{name}}: {notes:?}"
    );

    let already = fastmcp_rust::McpRequestCancellation::new();
    already.cancel();
    let pre_send_resources = client
        .list_resources_with_params_and_cancellation(
            &cx,
            &already,
            stdio_resource_list_params(Some(&["server"]), None),
        )
        .expect_err("pre-send cancellation must reject a tagged resources/list locally");
    assert_eq!(pre_send_resources.code, McpErrorCode::RequestCancelled);
    let pre_send_prompts = client
        .list_prompts_with_params_and_cancellation(
            &cx,
            &already,
            stdio_prompt_list_params(Some(&["onboarding"]), None),
        )
        .expect_err("pre-send cancellation must reject a tagged prompts/list locally");
    assert_eq!(pre_send_prompts.code, McpErrorCode::RequestCancelled);
    let pre_send_templates = client
        .list_resource_templates_with_params_and_cancellation(
            &cx,
            &already,
            stdio_template_list_params(Some(&["notes"]), None),
        )
        .expect_err("pre-send cancellation must reject a tagged resources/templates/list locally");
    assert_eq!(pre_send_templates.code, McpErrorCode::RequestCancelled);

    client
        .ping()
        .expect("modern stdio ping remains usable after tagged catalog cancellation");
    client
        .close()
        .expect("modern-only stdio tagged catalog cancellation client cleanup");
}

const STDIO_SERVER_INFO_ICON: &str = "https://example.test/echo-server.png";
const STDIO_GREETING_ICON: &str = "https://example.test/echo-greeting.png";

#[cfg(unix)]
#[test]
fn e2e_public_stdio_modern_list_resources_and_prompts_retain_icons() {
    let mut client = connect_bounded_modern_stdio_to_shipped_echo_server("modern-only")
        .expect("a ModernOnly facade client connects to the icon-bearing echo peer");

    let listed = client
        .list_resources(None)
        .expect("modern resources/list must retain shipped icons");
    let server = listed
        .resources
        .iter()
        .find(|resource| resource.uri.as_str() == "info://server")
        .expect("info://server must remain on the live catalog");
    let leak = listed
        .resources
        .iter()
        .find(|resource| resource.uri.as_str() == "info://leak")
        .expect("info://leak must remain the iconless peer");
    let icons = server
        .icons
        .as_ref()
        .expect("info://server must advertise its exact-final icon");
    assert_eq!(icons.len(), 1);
    assert_eq!(icons[0].src.as_str(), STDIO_SERVER_INFO_ICON);
    assert_eq!(
        leak.icons, None,
        "changing only the missing icon must keep info://leak iconless: {leak:?}"
    );

    let listed_prompts = client
        .list_prompts(None)
        .expect("modern prompts/list must retain shipped icons");
    let greeting = listed_prompts
        .prompts
        .iter()
        .find(|prompt| prompt.name == "greeting")
        .expect("greeting must remain on the live catalog");
    let compose = listed_prompts
        .prompts
        .iter()
        .find(|prompt| prompt.name == "compose_greeting")
        .expect("compose_greeting must remain the iconless peer");
    let greeting_icons = greeting
        .icons
        .as_ref()
        .expect("greeting must advertise its exact-final icon");
    assert_eq!(greeting_icons.len(), 1);
    assert_eq!(greeting_icons[0].src.as_str(), STDIO_GREETING_ICON);
    assert_eq!(
        compose.icons, None,
        "changing only the missing icon must keep compose_greeting iconless: {compose:?}"
    );

    client
        .close()
        .expect("modern-only stdio catalog-icon client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_list_resources_and_prompts_retain_icons() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client connects to the icon-bearing echo peer");

    let listed = client
        .list_resources()
        .expect("exact-2024 resources/list must retain shipped icons");
    let server = listed
        .iter()
        .find(|resource| resource.uri == "info://server")
        .expect("info://server must remain on the live catalog");
    let leak = listed
        .iter()
        .find(|resource| resource.uri == "info://leak")
        .expect("info://leak must remain the iconless peer");
    assert_eq!(
        server.icon.as_ref().and_then(|icon| icon.src.as_deref()),
        Some(STDIO_SERVER_INFO_ICON),
        "exact-2024 info://server must retain its icon src: {server:?}"
    );
    assert_eq!(
        leak.icon, None,
        "changing only the missing icon must keep info://leak iconless: {leak:?}"
    );

    let listed_prompts = client
        .list_prompts()
        .expect("exact-2024 prompts/list must retain shipped icons");
    let greeting = listed_prompts
        .iter()
        .find(|prompt| prompt.name == "greeting")
        .expect("greeting must remain on the live catalog");
    let compose = listed_prompts
        .iter()
        .find(|prompt| prompt.name == "compose_greeting")
        .expect("compose_greeting must remain the iconless peer");
    assert_eq!(
        greeting.icon.as_ref().and_then(|icon| icon.src.as_deref()),
        Some(STDIO_GREETING_ICON),
        "exact-2024 greeting must retain its icon src: {greeting:?}"
    );
    assert_eq!(
        compose.icon, None,
        "changing only the missing icon must keep compose_greeting iconless: {compose:?}"
    );

    client
        .close()
        .expect("legacy-only stdio catalog-icon client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_initialize_retains_instructions_peer_stays_bare() {
    let mut bare = connect_legacy_stdio_to_shipped_echo_server_with_env(
        "legacy-only",
        &[("FASTMCP_NO_INSTRUCTIONS", "1")],
    )
    .expect("a LegacyOnly facade client connects to the bare echo peer");
    assert_eq!(
        bare.instructions(),
        None,
        "changing only the missing instructions must keep the peer bare"
    );
    bare.close().expect("bare legacy stdio client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_legacy_stdio_roots_callback_reaches_context() {
    let callback_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let handlers = legacy_2024::LegacyReverseRequestHandlers::new().with_roots_list({
        let callback_calls = Arc::clone(&callback_calls);
        move |_cx, _cancellation, _params| {
            callback_calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            Box::pin(async {
                Ok(legacy_2024::ListRootsResult::new(vec![
                    legacy_2024::Root::with_name("file:///workspace", "workspace"),
                ]))
            })
        }
    });
    let runtime = asupersync::runtime::RuntimeBuilder::current_thread()
        .build()
        .expect("legacy callback runtime builds");
    runtime.block_on(async move {
        let cx = Cx::current().expect("legacy callback runtime installs its Cx");
        let mut client = connect_legacy_stdio_to_shipped_echo_server_with_reverse_handlers(
            "legacy-only",
            handlers,
        )
        .expect("the roots callback is configured before exact legacy initialization");
        let result = client
            .call_tool_with_cx(&cx, "client_root_uri", json!({}))
            .await
            .expect("the sealed legacy facade services roots/list before its typed tool result");
        assert!(!result.is_error);
        assert!(matches!(
            result.content.first(),
            Some(LegacyContent::Text { text, .. }) if text == "file:///workspace"
        ));
        assert_eq!(
            callback_calls.load(std::sync::atomic::Ordering::Relaxed),
            1,
            "the tool's context authority issues exactly one roots/list callback"
        );
        client.close().expect("legacy roots client cleanup");
    });
}

#[cfg(unix)]
#[test]
fn e2e_public_legacy_stdio_roots_without_capability_has_no_callback_authority() {
    // This differs from the positive path only by omitting its roots callback.
    // The builder consequently omits the roots capability before initialization.
    let runtime = asupersync::runtime::RuntimeBuilder::current_thread()
        .build()
        .expect("legacy missing-roots runtime builds");
    runtime.block_on(async move {
        let cx = Cx::current().expect("legacy missing-roots runtime installs its Cx");
        let mut client = connect_legacy_stdio_to_shipped_echo_server_with_reverse_handlers(
            "legacy-only",
            legacy_2024::LegacyReverseRequestHandlers::new(),
        )
        .expect("the exact legacy connection without roots capability initializes");
        let result = client
            .call_tool_with_cx(&cx, "client_root_uri", json!({}))
            .await
            .expect("missing roots authority remains a typed legacy tool result");
        assert!(result.is_error);
        assert!(matches!(
            result.content.first(),
            Some(LegacyContent::Text { text, .. })
                if text == "Roots not available: client does not support roots capability"
        ));
        client.close().expect("legacy roots client cleanup");
    });
}

#[cfg(unix)]
#[test]
fn e2e_public_legacy_stdio_sampling_callback_reaches_context() {
    let callback_calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let handlers = legacy_2024::LegacyReverseRequestHandlers::new().with_sampling_create_message({
        let callback_calls = Arc::clone(&callback_calls);
        move |_cx, _cancellation, _params| {
            callback_calls.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            Box::pin(async {
                Ok(legacy_2024::LegacyCreateMessageResult::text(
                    "sampled-legacy",
                    "stdio-legacy-model",
                ))
            })
        }
    });
    let runtime = asupersync::runtime::RuntimeBuilder::current_thread()
        .build()
        .expect("legacy sampling runtime builds");
    runtime.block_on(async move {
        let cx = Cx::current().expect("legacy sampling runtime installs its Cx");
        let mut client = connect_legacy_stdio_to_shipped_echo_server_with_reverse_handlers(
            "legacy-only",
            handlers,
        )
        .expect("the sampling callback is configured before exact legacy initialization");
        let result = client
            .call_tool_with_cx(&cx, "sample_text", json!({}))
            .await
            .expect("the sealed legacy facade services sampling/createMessage before its typed tool result");
        assert!(!result.is_error);
        assert!(matches!(
            result.content.first(),
            Some(LegacyContent::Text { text, .. }) if text == "sampled-legacy"
        ));
        assert_eq!(
            callback_calls.load(std::sync::atomic::Ordering::Relaxed),
            1,
            "the tool's context authority issues exactly one sampling/createMessage callback"
        );
        client.close().expect("legacy sampling client cleanup");
    });
}

#[cfg(unix)]
#[test]
fn e2e_public_legacy_stdio_sampling_without_capability_has_no_callback_authority() {
    let runtime = asupersync::runtime::RuntimeBuilder::current_thread()
        .build()
        .expect("legacy missing-sampling runtime builds");
    runtime.block_on(async move {
        let cx = Cx::current().expect("legacy missing-sampling runtime installs its Cx");
        let mut client = connect_legacy_stdio_to_shipped_echo_server_with_reverse_handlers(
            "legacy-only",
            legacy_2024::LegacyReverseRequestHandlers::new(),
        )
        .expect("the exact legacy connection without sampling capability initializes");
        let result = client
            .call_tool_with_cx(&cx, "sample_text", json!({}))
            .await
            .expect("missing sampling authority remains a typed legacy tool result");
        assert!(result.is_error);
        assert!(matches!(
            result.content.first(),
            Some(LegacyContent::Text { text, .. })
                if text.contains("does not support sampling capability")
        ));
        client.close().expect("legacy sampling client cleanup");
    });
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_ping_is_admitted_and_missing_tool_stays_refused() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client completes the exact legacy lifecycle");

    client
        .ping()
        .expect("live exact-2024 stdio must admit ping");

    let missing = client
        .call_tool("stdio-e2e-missing", json!({}))
        .expect_err("changing only the missing tool must keep the session refused");
    let missing = format!("{missing:?}");
    assert!(
        missing.contains("MethodNotFound")
            || missing.contains("InvalidParams")
            || missing.contains("InvalidRequest")
            || missing.contains("not found")
            || missing.contains("Unknown tool"),
        "a missing exact-2024 stdio tool must stay a handler-visible refusal: {missing}"
    );

    client
        .close()
        .expect("legacy-only stdio ping client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_complete_is_retained_and_unknown_prompt_is_refused() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client completes the exact legacy lifecycle");

    assert!(
        client.server_capabilities().completions.is_some(),
        "the shipped echo server must advertise completions: {:?}",
        client.server_capabilities()
    );

    let completed = client
        .complete(legacy_2024::LegacyCompletionParams {
            reference: legacy_2024::LegacyCompletionReference::Prompt {
                name: "greeting".to_owned(),
            },
            argument: legacy_2024::LegacyCompletionArgument {
                name: "name".to_owned(),
                value: "co".to_owned(),
            },
            meta: None,
        })
        .expect("live exact-2024 stdio must complete the shipped greeting provider");
    assert_eq!(
        completed.completion.values,
        vec!["stdio-completion-legacy".to_owned()],
        "the exact-2024 completion provider must retain its values: {completed:?}"
    );

    client
        .close()
        .expect("legacy-only stdio complete client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_roots_list_changed_is_admitted_and_unadvertised_peer_is_refused() {
    let command = shipped_echo_server_executable();
    let mut admitted = legacy_2024::client_builder()
        .env("FASTMCP_PROTOCOL_POLICY", "legacy-only")
        .capabilities(ClientCapabilities {
            roots: Some(legacy_2024::RootsCapability { list_changed: true }),
            ..ClientCapabilities::default()
        })
        .reverse_request_handlers(
            legacy_2024::LegacyReverseRequestHandlers::new().with_roots_list(
                |_cx, _cancel, _params| {
                    Box::pin(async { Ok(legacy_2024::ListRootsResult::new(Vec::new())) })
                },
            ),
        )
        .connect_stdio_with_cx(command, &[], &Cx::for_request())
        .expect(
            "an advertised roots.listChanged stdio client completes the exact legacy lifecycle",
        );

    admitted.roots_list_changed().expect(
        "live exact-2024 stdio must admit notifications/roots/list_changed when advertised",
    );
    admitted
        .ping()
        .expect("the same session must still admit ping after roots/list_changed");

    let mut refused = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a bare LegacyOnly facade client completes the exact legacy lifecycle");
    let missing = refused
        .roots_list_changed()
        .expect_err("changing only the missing roots.listChanged advertisement must refuse");
    let missing = format!("{missing:?}");
    assert!(
        missing.contains("roots.listChanged") || missing.contains("InvalidRequest"),
        "the unadvertised refusal must keep the capability gate: {missing}"
    );
    refused
        .ping()
        .expect("changing only the missing advertisement must leave ping admitted");

    admitted
        .close()
        .expect("legacy-only stdio advertised roots-change client cleanup");
    refused
        .close()
        .expect("legacy-only stdio bare roots-change client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_resource_template_completion_is_retained_and_unregistered_template_is_refused()
 {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client completes the exact legacy lifecycle");

    let completed = client
        .complete(legacy_2024::LegacyCompletionParams {
            reference: legacy_2024::LegacyCompletionReference::Resource {
                uri: "note://{name}".to_owned(),
            },
            argument: legacy_2024::LegacyCompletionArgument {
                name: "name".to_owned(),
                value: "al".to_owned(),
            },
            meta: None,
        })
        .expect("live exact-2024 stdio must complete the shipped note template provider");
    assert_eq!(
        completed.completion.values,
        vec!["stdio-note-completion-legacy".to_owned()],
        "the exact-2024 note template provider must retain its values: {completed:?}"
    );

    let missing_provider = client
        .complete(legacy_2024::LegacyCompletionParams {
            reference: legacy_2024::LegacyCompletionReference::Resource {
                uri: "memo://{name}".to_owned(),
            },
            argument: legacy_2024::LegacyCompletionArgument {
                name: "name".to_owned(),
                value: "al".to_owned(),
            },
            meta: None,
        })
        .expect_err("changing only the template URI must refuse the greeting catch-all");
    assert_eq!(missing_provider.code, McpErrorCode::InvalidParams);

    let greeting = client
        .complete(legacy_2024::LegacyCompletionParams {
            reference: legacy_2024::LegacyCompletionReference::Prompt {
                name: "greeting".to_owned(),
            },
            argument: legacy_2024::LegacyCompletionArgument {
                name: "name".to_owned(),
                value: "co".to_owned(),
            },
            meta: None,
        })
        .expect("the note provider must leave the greeting prompt provider usable");
    assert_eq!(
        greeting.completion.values,
        vec!["stdio-completion-legacy".to_owned()],
        "the exact-2024 greeting provider must still complete after note template completion: {greeting:?}"
    );

    client
        .close()
        .expect("legacy-only stdio note-completion client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_complete_peer_without_handler_is_refused() {
    let mut omitted = connect_legacy_stdio_to_shipped_echo_server_with_env(
        "legacy-only",
        &[("FASTMCP_NO_COMPLETIONS", "1")],
    )
    .expect("a LegacyOnly facade client connects to the completions-omitted echo peer");

    assert!(
        omitted.server_capabilities().completions.is_none(),
        "changing only the missing completion handler must omit completions: {:?}",
        omitted.server_capabilities()
    );
    omitted
        .complete(legacy_2024::LegacyCompletionParams {
            reference: legacy_2024::LegacyCompletionReference::Prompt {
                name: "greeting".to_owned(),
            },
            argument: legacy_2024::LegacyCompletionArgument {
                name: "name".to_owned(),
                value: "co".to_owned(),
            },
            meta: None,
        })
        .expect_err("changing only the missing completion handler must refuse complete");

    omitted
        .close()
        .expect("legacy-only stdio complete-omitted client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_subscribe_then_unsubscribe_gates_resource_updated() {
    let mut client = connect_legacy_stdio_to_shipped_echo_server("legacy-only")
        .expect("a LegacyOnly facade client completes the exact legacy lifecycle");

    let silent = client
        .call_tool("touch_server_info", json!({}))
        .expect("touching an unsubscribed resource must complete");
    assert!(
        silent.content.iter().any(|content| match content {
            LegacyContent::Text { text, .. } => text == "silent",
            _ => false,
        }),
        "without resources/subscribe the handler must not claim updated delivery: {silent:?}"
    );
    let notifications = client
        .take_server_notifications()
        .expect("exact-2024 stdio notifications must decode");
    assert!(
        !notifications.iter().any(|notification| matches!(
            notification,
            legacy_2024::ServerNotification::ResourceUpdated(_)
        )),
        "omitting only resources/subscribe must keep resources/updated silent: {notifications:?}"
    );

    client
        .subscribe_resource("info://server")
        .expect("exact-2024 stdio resources/subscribe must be admitted");
    let notified = client
        .call_tool("touch_server_info", json!({}))
        .expect("touching a subscribed resource must complete");
    assert!(
        notified.content.iter().any(|content| match content {
            LegacyContent::Text { text, .. } => text == "notified",
            _ => false,
        }),
        "resources/subscribe must count as notify_resource_updated delivery: {notified:?}"
    );
    let notifications = client
        .take_server_notifications()
        .expect("exact-2024 stdio notifications must decode");
    assert!(
        notifications.iter().any(|notification| matches!(
            notification,
            legacy_2024::ServerNotification::ResourceUpdated(params)
                if params.uri == "info://server"
        )),
        "live exact-2024 stdio must retain notifications/resources/updated: {notifications:?}"
    );

    client
        .unsubscribe_resource("info://server")
        .expect("exact-2024 stdio resources/unsubscribe must be admitted");
    let silent_again = client
        .call_tool("touch_server_info", json!({}))
        .expect("touching an unsubscribed resource must complete");
    assert!(
        silent_again.content.iter().any(|content| match content {
            LegacyContent::Text { text, .. } => text == "silent",
            _ => false,
        }),
        "resources/unsubscribe must stop notify_resource_updated delivery: {silent_again:?}"
    );
    let notifications = client
        .take_server_notifications()
        .expect("exact-2024 stdio notifications must decode");
    assert!(
        !notifications.iter().any(|notification| matches!(
            notification,
            legacy_2024::ServerNotification::ResourceUpdated(_)
        )),
        "changing only resources/unsubscribe must keep later resources/updated silent: {notifications:?}"
    );

    client
        .close()
        .expect("legacy-only stdio subscribe client cleanup");
}

#[cfg(unix)]
#[test]
fn e2e_public_stdio_legacy_only_rejects_the_modern_shipped_server() {
    // This differs from the matched LegacyOnly positive only in the child
    // server's policy. The public client must not infer a legacy lifecycle.
    let result = connect_legacy_stdio_to_shipped_echo_server("modern-only");

    assert!(
        result.is_err(),
        "a LegacyOnly facade client must reject the modern server instead of selecting a foreign era"
    );
}