fastmcp-server 0.11.0

MCP server implementation for FastMCP
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
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
23997
23998
23999
24000
24001
24002
24003
24004
24005
24006
24007
24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035
24036
24037
24038
24039
24040
24041
24042
24043
24044
24045
24046
24047
24048
24049
24050
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077
24078
24079
24080
24081
24082
24083
24084
24085
24086
24087
24088
24089
24090
24091
24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105
24106
24107
24108
24109
24110
24111
24112
24113
24114
24115
24116
24117
24118
24119
24120
24121
24122
24123
24124
24125
24126
24127
24128
24129
24130
24131
24132
24133
24134
24135
24136
24137
24138
24139
24140
24141
24142
24143
24144
24145
24146
24147
24148
24149
24150
24151
24152
24153
24154
24155
24156
24157
24158
24159
24160
24161
24162
24163
24164
24165
24166
24167
24168
24169
24170
24171
24172
24173
24174
24175
24176
24177
24178
24179
24180
24181
24182
24183
24184
24185
24186
24187
24188
24189
24190
24191
24192
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210
24211
24212
24213
24214
24215
24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266
24267
24268
24269
24270
24271
24272
24273
24274
24275
24276
24277
24278
24279
24280
24281
24282
24283
24284
24285
24286
24287
24288
24289
24290
24291
24292
24293
24294
24295
24296
24297
24298
24299
24300
24301
24302
24303
24304
24305
24306
24307
24308
24309
24310
24311
24312
24313
24314
24315
24316
24317
24318
24319
24320
24321
24322
24323
24324
24325
24326
24327
24328
24329
24330
24331
24332
24333
24334
24335
24336
24337
24338
24339
24340
24341
24342
24343
24344
24345
24346
24347
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359
24360
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405
24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
24437
24438
24439
24440
24441
24442
24443
24444
24445
24446
24447
24448
24449
24450
24451
24452
24453
24454
24455
24456
24457
24458
24459
24460
24461
24462
24463
24464
24465
24466
24467
24468
24469
24470
24471
24472
24473
24474
24475
24476
24477
24478
24479
24480
24481
24482
24483
24484
24485
24486
24487
24488
24489
24490
24491
24492
24493
24494
24495
24496
24497
24498
24499
24500
24501
24502
24503
24504
24505
24506
24507
24508
24509
24510
24511
24512
24513
24514
24515
24516
24517
24518
24519
24520
24521
24522
24523
24524
24525
24526
24527
24528
24529
24530
24531
24532
24533
24534
24535
24536
24537
24538
24539
24540
24541
24542
24543
24544
24545
24546
24547
24548
24549
24550
24551
24552
24553
24554
24555
24556
24557
24558
24559
24560
24561
24562
24563
24564
24565
24566
24567
24568
24569
24570
24571
24572
24573
24574
24575
24576
24577
24578
24579
24580
24581
24582
24583
24584
24585
24586
24587
24588
24589
24590
24591
24592
24593
24594
24595
24596
24597
24598
24599
24600
24601
24602
24603
24604
24605
24606
24607
24608
24609
24610
24611
24612
24613
24614
24615
24616
24617
24618
24619
24620
24621
24622
24623
24624
24625
24626
24627
24628
24629
24630
24631
24632
24633
24634
24635
24636
24637
24638
24639
24640
24641
24642
24643
24644
24645
24646
24647
24648
24649
24650
24651
24652
24653
24654
24655
24656
24657
24658
24659
24660
24661
24662
24663
24664
24665
24666
24667
24668
24669
24670
24671
24672
24673
24674
24675
24676
24677
24678
24679
24680
24681
24682
24683
24684
24685
24686
24687
24688
24689
24690
24691
24692
24693
24694
24695
24696
24697
24698
24699
24700
24701
24702
24703
24704
24705
24706
24707
24708
24709
24710
24711
24712
24713
24714
24715
24716
24717
24718
24719
24720
24721
24722
24723
24724
24725
24726
24727
24728
24729
24730
24731
24732
24733
24734
24735
24736
24737
24738
24739
24740
24741
24742
24743
24744
24745
24746
24747
24748
24749
24750
24751
24752
24753
24754
24755
24756
24757
24758
24759
24760
24761
24762
24763
24764
24765
24766
24767
24768
24769
24770
24771
24772
24773
24774
24775
24776
24777
24778
24779
24780
24781
24782
24783
24784
24785
24786
24787
24788
24789
24790
24791
24792
24793
24794
24795
24796
24797
24798
24799
24800
24801
24802
24803
24804
24805
24806
24807
24808
24809
24810
24811
24812
24813
24814
24815
24816
24817
24818
24819
24820
24821
24822
24823
24824
24825
24826
24827
24828
24829
24830
24831
24832
24833
24834
24835
24836
24837
24838
24839
24840
24841
24842
24843
24844
24845
24846
24847
24848
24849
24850
24851
24852
24853
24854
24855
24856
24857
24858
24859
24860
24861
24862
24863
24864
24865
24866
24867
24868
24869
24870
24871
24872
24873
24874
24875
24876
24877
24878
24879
24880
24881
24882
24883
24884
24885
24886
24887
24888
24889
24890
24891
24892
24893
24894
24895
24896
24897
24898
24899
24900
24901
24902
24903
24904
24905
24906
24907
24908
24909
24910
24911
24912
24913
24914
24915
24916
24917
24918
24919
24920
24921
24922
24923
24924
24925
24926
24927
24928
24929
24930
24931
24932
24933
24934
24935
24936
24937
24938
24939
24940
24941
24942
24943
24944
24945
24946
24947
24948
24949
24950
24951
24952
24953
24954
24955
24956
24957
24958
24959
24960
24961
24962
24963
24964
24965
24966
24967
24968
24969
24970
24971
24972
24973
24974
24975
24976
24977
24978
24979
24980
24981
24982
24983
24984
24985
24986
24987
24988
24989
24990
24991
24992
24993
24994
24995
24996
24997
24998
24999
25000
25001
25002
25003
25004
25005
25006
25007
25008
25009
25010
25011
25012
25013
25014
25015
25016
25017
25018
25019
25020
25021
25022
25023
25024
25025
25026
25027
25028
25029
25030
25031
25032
25033
25034
25035
25036
25037
25038
25039
25040
25041
25042
25043
25044
25045
25046
25047
25048
25049
25050
25051
25052
25053
25054
25055
25056
25057
25058
25059
25060
25061
25062
25063
25064
25065
25066
25067
25068
25069
25070
25071
25072
25073
25074
25075
25076
25077
25078
25079
25080
25081
25082
25083
25084
25085
25086
25087
25088
25089
25090
25091
25092
25093
25094
25095
25096
25097
25098
25099
25100
25101
25102
25103
25104
25105
25106
25107
25108
25109
25110
25111
25112
25113
25114
25115
25116
25117
25118
25119
25120
25121
25122
25123
25124
25125
25126
25127
25128
25129
25130
25131
25132
25133
25134
25135
25136
25137
25138
25139
25140
25141
25142
25143
25144
25145
25146
25147
25148
25149
25150
25151
25152
25153
25154
25155
25156
25157
25158
25159
25160
25161
25162
25163
25164
25165
25166
25167
25168
25169
25170
25171
25172
25173
25174
25175
25176
25177
25178
25179
25180
25181
25182
25183
25184
25185
25186
25187
25188
25189
25190
25191
25192
25193
25194
25195
25196
25197
25198
25199
25200
25201
25202
25203
25204
25205
25206
25207
25208
25209
25210
25211
25212
25213
25214
25215
25216
25217
25218
25219
25220
25221
25222
25223
25224
25225
25226
25227
25228
25229
25230
25231
25232
25233
25234
25235
25236
25237
25238
25239
25240
25241
25242
25243
25244
25245
25246
25247
25248
25249
25250
25251
25252
25253
25254
25255
25256
25257
25258
25259
25260
25261
25262
25263
25264
25265
25266
25267
25268
25269
25270
25271
25272
25273
25274
25275
25276
25277
25278
25279
25280
25281
25282
25283
25284
25285
25286
25287
25288
25289
25290
25291
25292
25293
25294
25295
25296
25297
25298
25299
25300
25301
25302
25303
25304
25305
25306
25307
25308
25309
25310
25311
25312
25313
25314
25315
25316
25317
25318
25319
25320
25321
25322
25323
25324
25325
25326
25327
25328
25329
25330
25331
25332
25333
25334
25335
25336
25337
25338
25339
25340
25341
25342
25343
25344
25345
25346
25347
25348
25349
25350
25351
25352
25353
25354
25355
25356
25357
25358
25359
25360
25361
25362
25363
25364
25365
25366
25367
25368
25369
25370
25371
25372
25373
25374
25375
25376
25377
25378
25379
25380
25381
25382
25383
25384
25385
25386
25387
25388
25389
25390
25391
25392
25393
25394
25395
25396
25397
25398
25399
25400
25401
25402
25403
25404
25405
25406
25407
25408
25409
25410
25411
25412
25413
25414
25415
25416
25417
25418
25419
25420
25421
25422
25423
25424
25425
25426
25427
25428
25429
25430
25431
25432
25433
25434
25435
25436
25437
25438
25439
25440
25441
25442
25443
25444
25445
25446
25447
25448
25449
25450
25451
25452
25453
25454
25455
25456
25457
25458
25459
25460
25461
25462
25463
25464
25465
25466
25467
25468
25469
25470
25471
25472
25473
25474
25475
25476
25477
25478
25479
25480
25481
25482
25483
25484
25485
25486
25487
25488
25489
25490
25491
25492
25493
25494
25495
25496
25497
25498
25499
25500
25501
25502
25503
25504
25505
25506
25507
25508
25509
25510
25511
25512
25513
25514
25515
25516
25517
25518
25519
25520
25521
25522
25523
25524
25525
25526
25527
25528
25529
25530
25531
25532
25533
25534
25535
25536
25537
25538
25539
25540
25541
25542
25543
25544
25545
25546
25547
25548
25549
25550
25551
25552
25553
25554
25555
25556
25557
25558
25559
25560
25561
25562
25563
25564
25565
25566
25567
25568
25569
25570
25571
25572
25573
25574
25575
25576
25577
25578
25579
25580
25581
25582
25583
25584
25585
25586
25587
25588
25589
25590
25591
25592
25593
25594
25595
25596
25597
25598
25599
25600
25601
25602
25603
25604
25605
25606
25607
25608
25609
25610
25611
25612
25613
25614
25615
25616
25617
25618
25619
25620
25621
25622
25623
25624
25625
25626
25627
25628
25629
25630
25631
25632
25633
25634
25635
25636
25637
25638
25639
25640
25641
25642
25643
25644
25645
25646
25647
25648
25649
25650
25651
25652
25653
25654
25655
25656
25657
25658
25659
25660
25661
25662
25663
25664
25665
25666
25667
25668
25669
25670
25671
25672
25673
25674
25675
25676
25677
25678
25679
25680
25681
25682
25683
25684
25685
25686
25687
25688
25689
25690
25691
25692
25693
25694
25695
25696
25697
25698
25699
25700
25701
25702
25703
25704
25705
25706
25707
25708
25709
25710
25711
25712
25713
25714
25715
25716
25717
25718
25719
25720
25721
25722
25723
25724
25725
25726
25727
25728
25729
25730
25731
25732
25733
25734
25735
25736
25737
25738
25739
25740
25741
25742
25743
25744
25745
25746
25747
25748
25749
25750
25751
25752
25753
25754
25755
25756
25757
25758
25759
25760
25761
25762
25763
25764
25765
25766
25767
25768
25769
25770
25771
25772
25773
25774
25775
25776
25777
25778
25779
25780
25781
25782
25783
25784
25785
25786
25787
25788
25789
25790
25791
25792
25793
25794
25795
25796
25797
25798
25799
25800
25801
25802
25803
25804
25805
25806
25807
25808
25809
25810
25811
25812
25813
25814
25815
25816
25817
25818
25819
25820
25821
25822
25823
25824
25825
25826
25827
25828
25829
25830
25831
25832
25833
25834
25835
25836
25837
25838
25839
25840
25841
25842
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852
25853
25854
25855
25856
25857
25858
25859
25860
25861
25862
25863
25864
25865
25866
25867
25868
25869
25870
25871
25872
25873
25874
25875
25876
25877
25878
25879
25880
25881
25882
25883
25884
25885
25886
25887
25888
25889
25890
25891
25892
25893
25894
25895
25896
25897
25898
25899
25900
25901
25902
25903
25904
25905
25906
25907
25908
25909
25910
25911
25912
25913
25914
25915
25916
25917
25918
25919
25920
25921
25922
25923
25924
25925
25926
25927
25928
25929
25930
25931
25932
25933
25934
25935
25936
25937
25938
25939
25940
25941
25942
25943
25944
25945
25946
25947
25948
25949
25950
25951
25952
25953
25954
25955
25956
25957
25958
25959
25960
25961
25962
25963
25964
25965
25966
25967
25968
25969
25970
25971
25972
25973
25974
25975
25976
25977
25978
25979
25980
25981
25982
25983
25984
25985
25986
25987
25988
25989
25990
25991
25992
25993
25994
25995
25996
25997
25998
25999
26000
26001
26002
26003
26004
26005
26006
26007
26008
26009
26010
26011
26012
26013
26014
26015
26016
26017
26018
26019
26020
26021
26022
26023
26024
26025
26026
26027
26028
26029
26030
26031
26032
26033
26034
26035
26036
26037
26038
26039
26040
26041
26042
26043
26044
26045
26046
26047
26048
26049
26050
26051
26052
26053
26054
26055
26056
26057
26058
26059
26060
26061
26062
26063
26064
26065
26066
26067
26068
26069
26070
26071
26072
26073
26074
26075
26076
26077
26078
26079
26080
26081
26082
26083
26084
26085
26086
26087
26088
26089
26090
26091
26092
26093
26094
26095
26096
26097
26098
26099
26100
26101
26102
26103
26104
26105
26106
26107
26108
26109
26110
26111
26112
26113
26114
26115
26116
26117
26118
26119
26120
26121
26122
26123
26124
26125
26126
26127
26128
26129
26130
26131
26132
26133
26134
26135
26136
26137
26138
26139
26140
26141
26142
26143
26144
26145
26146
26147
26148
26149
26150
26151
26152
26153
26154
26155
26156
26157
26158
26159
26160
26161
26162
26163
26164
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176
26177
26178
26179
26180
26181
26182
26183
26184
26185
26186
26187
26188
26189
26190
26191
26192
26193
26194
26195
26196
26197
26198
26199
26200
26201
26202
26203
26204
26205
26206
26207
26208
26209
26210
26211
26212
26213
26214
26215
26216
26217
26218
26219
26220
26221
26222
26223
26224
26225
26226
26227
26228
26229
26230
26231
26232
26233
26234
26235
26236
26237
26238
26239
26240
26241
26242
26243
26244
26245
26246
26247
26248
26249
26250
26251
26252
26253
26254
26255
26256
26257
26258
26259
26260
26261
26262
26263
26264
26265
26266
26267
26268
26269
26270
26271
26272
26273
26274
26275
26276
26277
26278
26279
26280
26281
26282
26283
26284
26285
26286
26287
26288
26289
26290
26291
26292
26293
26294
26295
26296
26297
26298
26299
26300
26301
26302
26303
26304
26305
26306
26307
26308
26309
26310
26311
26312
26313
26314
26315
26316
26317
26318
26319
26320
26321
26322
26323
26324
26325
26326
26327
26328
26329
26330
26331
26332
26333
26334
26335
26336
26337
26338
26339
26340
26341
26342
26343
26344
26345
26346
26347
26348
26349
26350
26351
26352
26353
26354
26355
26356
26357
26358
26359
26360
26361
26362
26363
26364
26365
26366
26367
26368
26369
26370
26371
26372
26373
26374
26375
26376
26377
26378
26379
26380
26381
26382
26383
26384
26385
26386
26387
26388
26389
26390
26391
26392
26393
26394
26395
26396
26397
26398
26399
26400
26401
26402
26403
26404
26405
26406
26407
26408
26409
26410
26411
26412
26413
26414
26415
26416
26417
26418
26419
26420
26421
26422
26423
26424
26425
26426
26427
26428
26429
26430
26431
26432
26433
26434
26435
26436
26437
26438
26439
26440
26441
26442
26443
26444
26445
26446
26447
26448
26449
26450
26451
26452
26453
26454
26455
26456
26457
26458
26459
26460
26461
26462
26463
26464
26465
26466
26467
26468
26469
26470
26471
26472
26473
26474
26475
26476
26477
26478
26479
26480
26481
26482
26483
26484
26485
26486
26487
26488
26489
26490
26491
26492
26493
26494
26495
26496
26497
26498
26499
26500
26501
26502
26503
26504
26505
26506
26507
26508
26509
26510
26511
26512
26513
26514
26515
26516
26517
26518
26519
26520
26521
26522
26523
26524
26525
26526
26527
26528
26529
26530
26531
26532
26533
26534
26535
26536
26537
26538
26539
26540
26541
26542
26543
26544
26545
26546
26547
26548
26549
26550
26551
26552
26553
26554
26555
26556
26557
26558
26559
26560
26561
26562
26563
26564
26565
26566
26567
26568
26569
26570
26571
26572
26573
26574
26575
26576
26577
26578
26579
26580
26581
26582
26583
26584
26585
26586
26587
26588
26589
26590
26591
26592
26593
26594
26595
26596
26597
26598
26599
26600
26601
26602
26603
26604
26605
26606
26607
26608
26609
26610
26611
26612
26613
26614
26615
26616
26617
26618
26619
26620
26621
26622
26623
26624
26625
26626
26627
26628
26629
26630
26631
26632
26633
26634
26635
26636
26637
26638
26639
26640
26641
26642
26643
26644
26645
26646
26647
26648
26649
26650
26651
26652
26653
26654
26655
26656
26657
26658
26659
26660
26661
26662
26663
26664
26665
26666
26667
26668
26669
26670
26671
26672
26673
26674
26675
26676
26677
26678
26679
26680
26681
26682
26683
26684
26685
26686
26687
26688
26689
26690
26691
26692
26693
26694
26695
26696
26697
26698
26699
26700
26701
26702
26703
26704
26705
26706
26707
26708
26709
26710
26711
26712
26713
26714
26715
26716
26717
26718
26719
26720
26721
26722
26723
26724
26725
26726
26727
26728
26729
26730
26731
26732
26733
26734
26735
26736
26737
26738
26739
26740
26741
26742
26743
26744
26745
26746
26747
26748
26749
26750
26751
26752
26753
26754
26755
26756
26757
26758
26759
26760
26761
26762
26763
26764
26765
26766
26767
26768
26769
26770
26771
26772
26773
26774
26775
26776
26777
26778
26779
26780
26781
26782
26783
26784
26785
26786
26787
26788
26789
26790
26791
26792
26793
26794
26795
26796
26797
26798
26799
26800
26801
26802
26803
26804
26805
26806
26807
26808
26809
26810
26811
26812
26813
26814
26815
26816
26817
26818
26819
26820
26821
26822
26823
26824
26825
26826
26827
26828
26829
26830
26831
26832
26833
26834
26835
26836
26837
26838
26839
26840
26841
26842
26843
26844
26845
26846
26847
26848
26849
26850
26851
26852
26853
26854
26855
26856
26857
26858
26859
26860
26861
26862
26863
26864
26865
26866
26867
26868
26869
26870
26871
26872
26873
26874
26875
26876
26877
26878
26879
26880
26881
26882
26883
26884
26885
26886
26887
26888
26889
26890
26891
26892
26893
26894
26895
26896
26897
26898
26899
26900
26901
26902
26903
26904
26905
26906
26907
26908
26909
26910
26911
26912
26913
26914
26915
26916
26917
26918
26919
26920
26921
26922
26923
26924
26925
26926
26927
26928
26929
26930
26931
26932
26933
26934
26935
26936
26937
26938
26939
26940
26941
26942
26943
26944
26945
26946
26947
26948
26949
26950
26951
26952
26953
26954
26955
26956
26957
26958
26959
26960
26961
26962
26963
26964
26965
26966
26967
26968
26969
26970
26971
26972
26973
26974
26975
26976
26977
26978
26979
26980
26981
26982
26983
26984
26985
26986
26987
26988
26989
26990
26991
26992
26993
26994
26995
26996
26997
26998
26999
27000
27001
27002
27003
27004
27005
27006
27007
27008
27009
27010
27011
27012
27013
27014
27015
27016
27017
27018
27019
27020
27021
27022
27023
27024
27025
27026
27027
27028
27029
27030
27031
27032
27033
27034
27035
27036
27037
27038
27039
27040
27041
27042
27043
27044
27045
27046
27047
27048
27049
27050
27051
27052
27053
27054
27055
27056
27057
27058
27059
27060
27061
27062
27063
27064
27065
27066
27067
27068
27069
27070
27071
27072
27073
27074
27075
27076
27077
27078
27079
27080
27081
27082
27083
27084
27085
27086
27087
27088
27089
27090
27091
27092
27093
27094
27095
27096
27097
27098
27099
27100
27101
27102
27103
27104
27105
27106
27107
27108
27109
27110
27111
27112
27113
27114
27115
27116
27117
27118
27119
27120
27121
27122
27123
27124
27125
27126
27127
27128
27129
27130
27131
27132
27133
27134
27135
27136
27137
27138
27139
27140
27141
27142
27143
27144
27145
27146
27147
27148
27149
27150
27151
27152
27153
27154
27155
27156
27157
27158
27159
27160
27161
27162
27163
27164
27165
27166
27167
27168
27169
27170
27171
27172
27173
27174
27175
27176
27177
27178
27179
27180
27181
27182
27183
27184
27185
27186
27187
27188
27189
27190
27191
27192
27193
27194
27195
27196
27197
27198
27199
27200
27201
27202
27203
27204
27205
27206
27207
27208
27209
27210
27211
27212
27213
27214
27215
27216
27217
27218
27219
27220
27221
27222
27223
27224
27225
27226
27227
27228
27229
27230
27231
27232
27233
27234
27235
27236
27237
27238
27239
27240
27241
27242
27243
27244
27245
27246
27247
27248
27249
27250
27251
27252
27253
27254
27255
27256
27257
27258
27259
27260
27261
27262
27263
27264
27265
27266
27267
27268
27269
27270
27271
27272
27273
27274
27275
27276
27277
27278
27279
27280
27281
27282
27283
27284
27285
27286
27287
27288
27289
27290
27291
27292
27293
27294
27295
27296
27297
27298
27299
27300
27301
27302
27303
27304
27305
27306
27307
27308
27309
27310
27311
27312
27313
27314
27315
27316
27317
27318
27319
27320
27321
27322
27323
27324
27325
27326
27327
27328
27329
27330
27331
27332
27333
27334
27335
27336
27337
27338
27339
27340
27341
27342
27343
27344
27345
27346
27347
27348
27349
27350
27351
27352
27353
27354
27355
27356
27357
27358
27359
27360
27361
27362
27363
27364
27365
27366
27367
27368
27369
27370
27371
27372
27373
27374
27375
27376
27377
27378
27379
27380
27381
27382
27383
27384
27385
27386
27387
27388
27389
27390
27391
27392
27393
27394
27395
27396
27397
27398
27399
27400
27401
27402
27403
27404
27405
27406
27407
27408
27409
27410
27411
27412
27413
27414
27415
27416
27417
27418
27419
27420
27421
27422
27423
27424
27425
27426
27427
27428
27429
27430
27431
27432
27433
27434
27435
27436
27437
27438
27439
27440
27441
27442
27443
27444
27445
27446
27447
27448
27449
27450
27451
27452
27453
27454
27455
27456
27457
27458
27459
27460
27461
27462
27463
27464
27465
27466
27467
27468
27469
27470
27471
27472
27473
27474
27475
27476
27477
27478
27479
27480
27481
27482
27483
27484
27485
27486
27487
27488
27489
27490
27491
27492
27493
27494
27495
27496
27497
27498
27499
27500
27501
27502
27503
27504
27505
27506
27507
27508
27509
27510
27511
27512
27513
27514
27515
27516
27517
27518
27519
27520
27521
27522
27523
27524
27525
27526
27527
27528
27529
27530
27531
27532
27533
27534
27535
27536
27537
27538
27539
27540
27541
27542
27543
27544
27545
27546
27547
27548
27549
27550
27551
27552
27553
27554
27555
27556
27557
27558
27559
27560
27561
27562
27563
27564
27565
27566
27567
27568
27569
27570
27571
27572
27573
27574
27575
27576
27577
27578
27579
27580
27581
27582
27583
27584
27585
27586
27587
27588
27589
27590
27591
27592
27593
27594
27595
27596
27597
27598
27599
27600
27601
27602
27603
27604
27605
27606
27607
27608
27609
27610
27611
27612
27613
27614
27615
27616
27617
27618
27619
27620
27621
27622
27623
27624
27625
27626
27627
27628
27629
27630
27631
27632
27633
27634
27635
27636
27637
27638
27639
27640
27641
27642
27643
27644
27645
27646
27647
27648
27649
27650
27651
27652
27653
27654
27655
27656
27657
27658
27659
27660
27661
27662
27663
27664
27665
27666
27667
27668
27669
27670
27671
27672
27673
27674
27675
27676
27677
27678
27679
27680
27681
27682
27683
27684
27685
27686
27687
27688
27689
27690
27691
27692
27693
27694
27695
27696
27697
27698
27699
27700
27701
27702
27703
27704
27705
27706
27707
27708
27709
27710
27711
27712
27713
27714
27715
27716
27717
27718
27719
27720
27721
27722
27723
27724
27725
27726
27727
27728
27729
27730
27731
27732
27733
27734
27735
27736
27737
27738
27739
27740
27741
27742
27743
27744
27745
27746
27747
27748
27749
27750
27751
27752
27753
27754
27755
27756
27757
27758
27759
27760
27761
27762
27763
27764
27765
27766
27767
27768
27769
27770
27771
27772
27773
27774
27775
27776
27777
27778
27779
27780
27781
27782
27783
27784
27785
27786
27787
27788
27789
27790
27791
27792
27793
27794
27795
27796
27797
27798
27799
27800
27801
27802
27803
27804
27805
27806
27807
27808
27809
27810
27811
27812
27813
27814
27815
27816
27817
27818
27819
27820
27821
27822
27823
27824
27825
27826
27827
27828
27829
27830
27831
27832
27833
27834
27835
27836
27837
27838
27839
27840
27841
27842
27843
27844
27845
27846
27847
27848
27849
27850
27851
27852
27853
27854
27855
27856
27857
27858
27859
27860
27861
27862
27863
27864
27865
27866
27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880
27881
27882
27883
27884
27885
27886
27887
27888
27889
27890
27891
27892
27893
27894
27895
27896
27897
27898
27899
27900
27901
27902
27903
27904
27905
27906
27907
27908
27909
27910
27911
27912
27913
27914
27915
27916
27917
27918
27919
27920
27921
27922
27923
27924
27925
27926
27927
27928
27929
27930
27931
27932
27933
27934
27935
27936
27937
27938
27939
27940
27941
27942
27943
27944
27945
27946
27947
27948
27949
27950
27951
27952
27953
27954
27955
27956
27957
27958
27959
27960
27961
27962
27963
27964
27965
27966
27967
27968
27969
27970
27971
27972
27973
27974
27975
27976
27977
27978
27979
27980
27981
27982
27983
27984
27985
27986
27987
27988
27989
27990
27991
27992
27993
27994
27995
27996
27997
27998
27999
28000
28001
28002
28003
28004
28005
28006
28007
28008
28009
28010
28011
28012
28013
28014
28015
28016
28017
28018
28019
28020
28021
28022
28023
28024
28025
28026
28027
28028
28029
28030
28031
28032
28033
28034
28035
28036
28037
28038
28039
28040
28041
28042
28043
28044
28045
28046
28047
28048
28049
28050
28051
28052
28053
28054
28055
28056
28057
28058
28059
28060
28061
28062
28063
28064
28065
28066
28067
28068
28069
28070
28071
28072
28073
28074
28075
28076
28077
28078
28079
28080
28081
28082
28083
28084
28085
28086
28087
28088
28089
28090
28091
28092
28093
28094
28095
28096
28097
28098
28099
28100
28101
28102
28103
28104
28105
28106
28107
28108
28109
28110
28111
28112
28113
28114
28115
28116
28117
28118
28119
28120
28121
28122
28123
28124
28125
28126
28127
28128
28129
28130
28131
28132
28133
28134
28135
28136
28137
28138
28139
28140
28141
28142
28143
28144
28145
28146
28147
28148
28149
28150
28151
28152
28153
28154
28155
28156
28157
28158
28159
28160
28161
28162
28163
28164
28165
28166
28167
28168
28169
28170
28171
28172
28173
28174
28175
28176
28177
28178
28179
28180
28181
28182
28183
28184
28185
28186
28187
28188
28189
28190
28191
28192
28193
28194
28195
28196
28197
28198
28199
28200
28201
28202
28203
28204
28205
28206
28207
28208
28209
28210
28211
28212
28213
28214
28215
28216
28217
28218
28219
28220
28221
28222
28223
28224
28225
28226
28227
28228
28229
28230
28231
28232
28233
28234
28235
28236
28237
28238
28239
28240
28241
28242
28243
28244
28245
28246
28247
28248
28249
28250
28251
28252
28253
28254
28255
28256
28257
28258
28259
28260
28261
28262
28263
28264
28265
28266
28267
28268
28269
28270
28271
28272
28273
28274
28275
28276
28277
28278
28279
28280
28281
28282
28283
28284
28285
28286
28287
28288
28289
28290
28291
28292
28293
28294
28295
28296
28297
28298
28299
28300
28301
28302
28303
28304
28305
28306
28307
28308
28309
28310
28311
28312
28313
28314
28315
28316
28317
28318
28319
28320
28321
28322
28323
28324
28325
28326
28327
28328
28329
28330
28331
28332
28333
28334
28335
28336
28337
28338
28339
28340
28341
28342
28343
28344
28345
28346
28347
28348
28349
28350
28351
28352
28353
28354
28355
28356
28357
28358
28359
28360
28361
28362
28363
28364
28365
28366
28367
28368
28369
28370
28371
28372
28373
28374
28375
28376
28377
28378
28379
28380
28381
28382
28383
28384
28385
28386
28387
28388
28389
28390
28391
28392
28393
28394
28395
28396
28397
28398
28399
28400
28401
28402
28403
28404
28405
28406
28407
28408
28409
28410
28411
28412
28413
28414
28415
28416
28417
28418
28419
28420
28421
28422
28423
28424
28425
28426
28427
28428
28429
28430
28431
28432
28433
28434
28435
28436
28437
28438
28439
28440
28441
28442
28443
28444
28445
28446
28447
28448
28449
28450
28451
28452
28453
28454
28455
28456
28457
28458
28459
28460
28461
28462
28463
28464
28465
28466
28467
28468
28469
28470
28471
28472
28473
28474
28475
28476
28477
28478
28479
28480
28481
28482
28483
28484
28485
28486
28487
28488
28489
28490
28491
28492
28493
28494
28495
28496
28497
28498
28499
28500
28501
28502
28503
28504
28505
28506
28507
28508
28509
28510
28511
28512
28513
28514
28515
28516
28517
28518
28519
28520
28521
28522
28523
28524
28525
28526
28527
28528
28529
28530
28531
28532
28533
28534
28535
28536
28537
28538
28539
28540
28541
28542
28543
28544
28545
28546
28547
28548
28549
28550
28551
28552
28553
28554
28555
28556
28557
28558
28559
28560
28561
28562
28563
28564
28565
28566
28567
28568
28569
28570
28571
28572
28573
28574
28575
28576
28577
28578
28579
28580
28581
28582
28583
28584
28585
28586
28587
28588
28589
28590
28591
28592
28593
28594
28595
28596
28597
28598
28599
28600
28601
28602
28603
28604
28605
28606
28607
28608
28609
28610
28611
28612
28613
28614
28615
28616
28617
28618
28619
28620
28621
28622
28623
28624
28625
28626
28627
28628
28629
28630
28631
28632
28633
28634
28635
28636
28637
28638
28639
28640
28641
28642
28643
28644
28645
28646
28647
28648
28649
28650
28651
28652
28653
28654
28655
28656
28657
28658
28659
28660
28661
28662
28663
28664
28665
28666
28667
28668
28669
28670
28671
28672
28673
28674
28675
28676
28677
28678
28679
28680
28681
28682
28683
28684
28685
28686
28687
28688
28689
28690
28691
28692
28693
28694
28695
28696
28697
28698
28699
28700
28701
28702
28703
28704
28705
28706
28707
28708
28709
28710
28711
28712
28713
28714
28715
28716
28717
28718
28719
28720
28721
28722
28723
28724
28725
28726
28727
28728
28729
28730
28731
28732
28733
28734
28735
28736
28737
28738
28739
28740
28741
28742
28743
28744
28745
28746
28747
28748
28749
28750
28751
28752
28753
28754
28755
28756
28757
28758
28759
28760
28761
28762
28763
28764
28765
28766
28767
28768
28769
28770
28771
28772
28773
28774
28775
28776
28777
28778
28779
28780
28781
28782
28783
28784
28785
28786
28787
28788
28789
28790
28791
28792
28793
28794
28795
28796
28797
28798
28799
28800
28801
28802
28803
28804
28805
28806
28807
28808
28809
28810
28811
28812
28813
28814
28815
28816
28817
28818
28819
28820
28821
28822
28823
28824
28825
28826
28827
28828
28829
28830
28831
28832
28833
28834
28835
28836
28837
28838
28839
28840
28841
28842
28843
28844
28845
28846
28847
28848
28849
28850
28851
28852
28853
28854
28855
28856
28857
28858
28859
28860
28861
28862
28863
28864
28865
28866
28867
28868
28869
28870
28871
28872
28873
28874
28875
28876
28877
28878
28879
28880
28881
28882
28883
28884
28885
28886
28887
28888
28889
28890
28891
28892
28893
28894
28895
28896
28897
28898
28899
28900
28901
28902
28903
28904
28905
28906
28907
28908
28909
28910
28911
28912
28913
28914
28915
28916
28917
28918
28919
28920
28921
28922
28923
28924
28925
28926
28927
28928
28929
28930
28931
28932
28933
28934
28935
28936
28937
28938
28939
28940
28941
28942
28943
28944
28945
28946
28947
28948
28949
28950
28951
28952
28953
28954
28955
28956
28957
28958
28959
28960
28961
28962
28963
28964
28965
28966
28967
28968
28969
28970
28971
28972
28973
28974
28975
28976
28977
28978
28979
28980
28981
28982
28983
28984
28985
28986
28987
28988
28989
28990
28991
28992
28993
28994
28995
28996
28997
28998
28999
29000
29001
29002
29003
29004
29005
29006
29007
29008
29009
29010
29011
29012
29013
29014
29015
29016
29017
29018
29019
29020
29021
29022
29023
29024
29025
29026
29027
29028
29029
29030
29031
29032
29033
29034
29035
29036
29037
29038
29039
29040
29041
29042
29043
29044
29045
29046
29047
29048
29049
29050
29051
29052
29053
29054
29055
29056
29057
29058
29059
29060
29061
29062
29063
29064
29065
29066
29067
29068
29069
29070
29071
29072
29073
29074
29075
29076
29077
29078
29079
29080
29081
29082
29083
29084
29085
29086
29087
29088
29089
29090
29091
29092
29093
29094
29095
29096
29097
29098
29099
29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110
29111
29112
29113
29114
29115
29116
29117
29118
29119
29120
29121
29122
29123
29124
29125
29126
29127
29128
29129
29130
29131
29132
29133
29134
29135
29136
29137
29138
29139
29140
29141
29142
29143
29144
29145
29146
29147
29148
29149
29150
29151
29152
29153
29154
29155
29156
29157
29158
29159
29160
29161
29162
29163
29164
29165
29166
29167
29168
29169
29170
29171
29172
29173
29174
29175
29176
29177
29178
29179
29180
29181
29182
29183
29184
29185
29186
29187
29188
29189
29190
29191
29192
29193
29194
29195
29196
29197
29198
29199
29200
29201
29202
29203
29204
29205
29206
29207
29208
29209
29210
29211
29212
29213
29214
29215
29216
29217
29218
29219
29220
29221
29222
29223
29224
29225
29226
29227
29228
29229
29230
29231
29232
29233
29234
29235
29236
29237
29238
29239
29240
29241
29242
29243
29244
29245
29246
29247
29248
29249
29250
29251
29252
29253
29254
29255
29256
29257
29258
29259
29260
29261
29262
29263
29264
29265
29266
29267
29268
29269
29270
29271
29272
29273
29274
29275
29276
29277
29278
29279
29280
29281
29282
29283
29284
29285
29286
29287
29288
29289
29290
29291
29292
29293
29294
29295
29296
29297
29298
29299
29300
29301
29302
29303
29304
29305
29306
29307
29308
29309
29310
29311
29312
29313
29314
29315
29316
29317
29318
29319
29320
29321
29322
29323
29324
29325
29326
29327
29328
29329
29330
29331
29332
29333
29334
29335
29336
29337
29338
29339
29340
29341
29342
29343
29344
29345
29346
29347
29348
29349
29350
29351
29352
29353
29354
29355
29356
29357
29358
29359
29360
29361
29362
29363
29364
29365
29366
29367
29368
29369
29370
29371
29372
29373
29374
29375
29376
29377
29378
29379
29380
29381
29382
29383
29384
29385
29386
29387
29388
29389
29390
29391
29392
29393
29394
29395
29396
29397
29398
29399
29400
29401
29402
29403
29404
29405
29406
29407
29408
29409
29410
29411
29412
29413
29414
29415
29416
29417
29418
29419
29420
29421
29422
29423
29424
29425
29426
29427
29428
29429
29430
29431
29432
29433
29434
29435
29436
29437
29438
29439
29440
29441
29442
29443
29444
29445
29446
29447
29448
29449
29450
29451
29452
29453
29454
29455
29456
29457
29458
29459
29460
29461
29462
29463
29464
29465
29466
29467
29468
29469
29470
29471
29472
29473
29474
29475
29476
29477
29478
29479
29480
29481
29482
29483
29484
29485
29486
29487
29488
29489
29490
29491
29492
29493
29494
29495
29496
29497
29498
29499
29500
29501
29502
29503
29504
29505
29506
29507
29508
29509
29510
29511
29512
29513
29514
29515
29516
29517
29518
29519
29520
29521
29522
29523
29524
29525
29526
29527
29528
29529
29530
29531
29532
29533
29534
29535
29536
29537
29538
29539
29540
29541
29542
29543
29544
29545
29546
29547
29548
29549
29550
29551
29552
29553
29554
29555
29556
29557
29558
29559
29560
29561
29562
29563
29564
29565
29566
29567
29568
29569
29570
29571
29572
29573
29574
29575
29576
29577
29578
29579
29580
29581
29582
29583
29584
29585
29586
29587
29588
29589
29590
29591
29592
29593
29594
29595
29596
29597
29598
29599
29600
29601
29602
29603
29604
29605
29606
29607
29608
29609
29610
29611
29612
29613
29614
29615
29616
29617
29618
29619
29620
29621
29622
29623
29624
29625
29626
29627
29628
29629
29630
29631
29632
29633
29634
29635
29636
29637
29638
29639
29640
29641
29642
29643
29644
29645
29646
29647
29648
29649
29650
29651
29652
29653
29654
29655
29656
29657
29658
29659
29660
29661
29662
29663
29664
29665
29666
29667
29668
29669
29670
29671
29672
29673
29674
29675
29676
29677
29678
29679
29680
29681
29682
29683
29684
29685
29686
29687
29688
29689
29690
29691
29692
29693
29694
29695
29696
29697
29698
29699
29700
29701
29702
29703
29704
29705
29706
29707
29708
29709
29710
29711
29712
29713
29714
29715
29716
29717
29718
29719
29720
29721
29722
29723
29724
29725
29726
29727
29728
29729
29730
29731
29732
29733
29734
29735
29736
29737
29738
29739
29740
29741
29742
29743
29744
29745
29746
29747
29748
29749
29750
29751
29752
29753
29754
29755
29756
29757
29758
29759
29760
29761
29762
29763
29764
29765
29766
29767
29768
29769
29770
29771
29772
29773
29774
29775
29776
29777
29778
29779
29780
29781
29782
29783
29784
29785
29786
29787
29788
29789
29790
29791
29792
29793
29794
29795
29796
29797
29798
29799
29800
29801
29802
29803
29804
29805
29806
29807
29808
29809
29810
29811
29812
29813
29814
29815
29816
29817
29818
29819
29820
29821
29822
29823
29824
29825
29826
29827
29828
29829
29830
29831
29832
29833
29834
29835
29836
29837
29838
29839
29840
29841
29842
29843
29844
29845
29846
29847
29848
29849
29850
29851
29852
29853
29854
29855
29856
29857
29858
29859
29860
29861
29862
29863
29864
29865
29866
29867
29868
29869
29870
29871
29872
29873
29874
29875
29876
29877
29878
29879
29880
29881
29882
29883
29884
29885
29886
29887
29888
29889
29890
29891
29892
29893
29894
29895
29896
29897
29898
29899
29900
29901
29902
29903
29904
29905
29906
29907
29908
29909
29910
29911
29912
29913
29914
29915
29916
29917
29918
29919
29920
29921
29922
29923
29924
29925
29926
29927
29928
29929
29930
29931
29932
29933
29934
29935
29936
29937
29938
29939
29940
29941
29942
29943
29944
29945
29946
29947
29948
29949
29950
29951
29952
29953
29954
29955
29956
29957
29958
29959
29960
29961
29962
29963
29964
29965
29966
29967
29968
29969
29970
29971
29972
29973
29974
29975
29976
29977
29978
29979
29980
29981
29982
29983
29984
29985
29986
29987
29988
29989
29990
29991
29992
29993
29994
29995
29996
29997
29998
29999
30000
30001
30002
30003
30004
30005
30006
30007
30008
30009
30010
30011
30012
30013
30014
30015
30016
30017
30018
30019
30020
30021
30022
30023
30024
30025
30026
30027
30028
30029
30030
30031
30032
30033
30034
30035
30036
30037
30038
30039
30040
30041
30042
30043
30044
30045
30046
30047
30048
30049
30050
30051
30052
30053
30054
30055
30056
30057
30058
30059
30060
30061
30062
30063
30064
30065
30066
30067
30068
30069
30070
30071
30072
30073
30074
30075
30076
30077
30078
30079
30080
30081
30082
30083
30084
30085
30086
30087
30088
30089
30090
30091
30092
30093
30094
30095
30096
30097
30098
30099
30100
30101
30102
30103
30104
30105
30106
30107
30108
30109
30110
30111
30112
30113
30114
30115
30116
30117
30118
30119
30120
30121
30122
30123
30124
30125
30126
30127
30128
30129
30130
30131
30132
30133
30134
30135
30136
30137
30138
30139
30140
30141
30142
30143
30144
30145
30146
30147
30148
30149
30150
30151
30152
30153
30154
30155
30156
30157
30158
30159
30160
30161
30162
30163
30164
30165
30166
30167
30168
30169
30170
30171
30172
30173
30174
30175
30176
30177
30178
30179
30180
30181
30182
30183
30184
30185
30186
30187
30188
30189
30190
30191
30192
30193
30194
30195
30196
30197
30198
30199
30200
30201
30202
30203
30204
30205
30206
30207
30208
30209
30210
30211
30212
30213
30214
30215
30216
30217
30218
30219
30220
30221
30222
30223
30224
30225
30226
30227
30228
30229
30230
30231
30232
30233
30234
30235
30236
30237
30238
30239
30240
30241
30242
30243
30244
30245
30246
30247
30248
30249
30250
30251
30252
30253
30254
30255
30256
30257
30258
30259
30260
30261
30262
30263
30264
30265
30266
30267
30268
30269
30270
30271
30272
30273
30274
30275
30276
30277
30278
30279
30280
30281
30282
30283
30284
30285
30286
30287
30288
30289
30290
30291
30292
30293
30294
30295
30296
30297
30298
30299
30300
30301
30302
30303
30304
30305
30306
30307
30308
30309
30310
30311
30312
30313
30314
30315
30316
30317
30318
30319
30320
30321
30322
30323
30324
30325
30326
30327
30328
30329
30330
30331
30332
30333
30334
30335
30336
30337
30338
30339
30340
30341
30342
30343
30344
30345
30346
30347
30348
30349
30350
30351
30352
30353
30354
30355
30356
30357
30358
30359
30360
30361
30362
30363
30364
30365
30366
30367
30368
30369
30370
30371
30372
30373
30374
30375
30376
30377
30378
30379
30380
30381
30382
30383
30384
30385
30386
30387
30388
30389
30390
30391
30392
30393
30394
30395
30396
30397
30398
30399
30400
30401
30402
30403
30404
30405
30406
30407
30408
30409
30410
30411
30412
30413
30414
30415
30416
30417
30418
30419
30420
30421
30422
30423
30424
30425
30426
30427
30428
30429
30430
30431
30432
30433
30434
30435
30436
30437
30438
30439
30440
30441
30442
30443
30444
30445
30446
30447
30448
30449
30450
30451
30452
30453
30454
30455
30456
30457
30458
30459
30460
30461
30462
30463
30464
30465
30466
30467
30468
30469
30470
30471
30472
30473
30474
30475
30476
30477
30478
30479
30480
30481
30482
30483
30484
30485
30486
30487
30488
30489
30490
30491
30492
30493
30494
30495
30496
30497
30498
30499
30500
30501
30502
30503
30504
30505
30506
30507
30508
30509
30510
30511
30512
30513
30514
30515
30516
30517
30518
30519
30520
30521
30522
30523
30524
30525
30526
30527
30528
30529
30530
30531
30532
30533
30534
30535
30536
30537
30538
30539
30540
30541
30542
30543
30544
30545
30546
30547
30548
30549
30550
30551
30552
30553
30554
30555
30556
30557
30558
30559
30560
30561
30562
30563
30564
30565
30566
30567
30568
30569
30570
30571
30572
30573
30574
30575
30576
30577
30578
30579
30580
30581
30582
30583
30584
30585
30586
30587
30588
30589
30590
30591
30592
30593
30594
30595
30596
30597
30598
30599
30600
30601
30602
30603
30604
30605
30606
30607
30608
30609
30610
30611
30612
30613
30614
30615
30616
30617
30618
30619
30620
30621
30622
30623
30624
30625
30626
30627
30628
30629
30630
30631
30632
30633
30634
30635
30636
30637
30638
30639
30640
30641
30642
30643
30644
30645
30646
30647
30648
30649
30650
30651
30652
30653
30654
30655
30656
30657
30658
30659
30660
30661
30662
30663
30664
30665
30666
30667
30668
30669
30670
30671
30672
30673
30674
30675
30676
30677
30678
30679
30680
30681
30682
30683
30684
30685
30686
30687
30688
30689
30690
30691
30692
30693
30694
30695
30696
30697
30698
30699
30700
30701
30702
30703
30704
30705
30706
30707
30708
30709
30710
30711
30712
30713
30714
30715
30716
30717
30718
30719
30720
30721
30722
30723
30724
30725
30726
30727
30728
30729
30730
30731
30732
30733
30734
30735
30736
30737
30738
30739
30740
30741
30742
30743
30744
30745
30746
30747
30748
30749
30750
30751
30752
30753
30754
30755
30756
30757
30758
30759
30760
30761
30762
30763
30764
30765
30766
30767
30768
30769
30770
30771
30772
30773
30774
30775
30776
30777
30778
30779
30780
30781
30782
30783
30784
30785
30786
30787
30788
30789
30790
30791
30792
30793
30794
30795
30796
30797
30798
30799
30800
30801
30802
30803
30804
30805
30806
30807
30808
30809
30810
30811
30812
30813
30814
30815
30816
30817
30818
30819
30820
30821
30822
30823
30824
30825
30826
30827
30828
30829
30830
30831
30832
30833
30834
30835
30836
30837
30838
30839
30840
30841
30842
30843
30844
30845
30846
30847
30848
30849
30850
30851
30852
30853
30854
30855
30856
30857
30858
30859
30860
30861
30862
30863
30864
30865
30866
30867
30868
30869
30870
30871
30872
30873
30874
30875
30876
30877
30878
30879
30880
30881
30882
30883
30884
30885
30886
30887
30888
30889
30890
30891
30892
30893
30894
30895
30896
30897
30898
30899
30900
30901
30902
30903
30904
30905
30906
30907
30908
30909
30910
30911
30912
30913
30914
30915
30916
30917
30918
30919
30920
30921
30922
30923
30924
30925
30926
30927
30928
30929
30930
30931
30932
30933
30934
30935
30936
30937
30938
30939
30940
30941
30942
30943
30944
30945
30946
30947
30948
30949
30950
30951
30952
30953
30954
30955
30956
30957
30958
30959
30960
30961
30962
30963
30964
30965
30966
30967
30968
30969
30970
30971
30972
30973
30974
30975
30976
30977
30978
30979
30980
30981
30982
30983
30984
30985
30986
30987
30988
30989
30990
30991
30992
30993
30994
30995
30996
30997
30998
30999
31000
31001
31002
31003
31004
31005
31006
31007
31008
31009
31010
31011
31012
31013
31014
31015
31016
31017
31018
31019
31020
31021
31022
31023
31024
31025
31026
31027
31028
31029
31030
31031
31032
31033
31034
31035
31036
31037
31038
31039
31040
31041
31042
31043
31044
31045
31046
31047
31048
31049
31050
31051
31052
31053
31054
31055
31056
31057
31058
31059
31060
31061
31062
31063
31064
31065
31066
31067
31068
31069
31070
31071
31072
31073
31074
31075
31076
31077
31078
31079
31080
31081
31082
31083
31084
31085
31086
31087
31088
31089
31090
31091
31092
31093
31094
31095
31096
31097
31098
31099
31100
31101
31102
31103
31104
31105
31106
31107
31108
31109
31110
31111
31112
31113
31114
31115
31116
31117
31118
31119
31120
31121
31122
31123
31124
31125
31126
31127
31128
31129
31130
31131
31132
31133
31134
31135
31136
31137
31138
31139
31140
31141
31142
31143
31144
31145
31146
31147
31148
31149
31150
31151
31152
31153
31154
31155
31156
31157
31158
31159
31160
31161
31162
31163
31164
31165
31166
31167
31168
31169
31170
31171
31172
31173
31174
31175
31176
31177
31178
31179
31180
31181
31182
31183
31184
31185
31186
31187
31188
31189
31190
31191
31192
31193
31194
31195
31196
31197
31198
31199
31200
31201
31202
31203
31204
31205
31206
31207
31208
31209
31210
31211
31212
31213
31214
31215
31216
31217
31218
31219
31220
31221
31222
31223
31224
31225
31226
31227
31228
31229
31230
31231
31232
31233
31234
31235
31236
31237
31238
31239
31240
31241
31242
31243
31244
31245
31246
31247
31248
31249
31250
31251
31252
31253
31254
31255
31256
31257
31258
31259
31260
31261
31262
31263
31264
31265
31266
31267
31268
31269
31270
31271
31272
31273
31274
31275
31276
31277
31278
31279
31280
31281
31282
31283
31284
31285
31286
31287
31288
31289
31290
31291
31292
31293
31294
31295
31296
31297
31298
31299
31300
31301
31302
31303
31304
31305
31306
31307
31308
31309
31310
31311
31312
31313
31314
31315
31316
31317
31318
31319
31320
31321
31322
31323
31324
31325
31326
31327
31328
31329
31330
31331
31332
31333
31334
31335
31336
31337
31338
31339
31340
31341
31342
31343
31344
31345
31346
31347
31348
31349
31350
31351
31352
31353
31354
31355
31356
31357
31358
31359
31360
31361
31362
31363
31364
31365
31366
31367
31368
31369
31370
31371
31372
31373
31374
31375
31376
31377
31378
31379
31380
31381
31382
31383
31384
31385
31386
31387
31388
31389
31390
31391
31392
31393
31394
31395
31396
31397
31398
31399
31400
31401
31402
31403
31404
31405
31406
31407
31408
31409
31410
31411
31412
31413
31414
31415
31416
31417
31418
31419
31420
31421
31422
31423
31424
31425
31426
31427
31428
31429
31430
31431
31432
31433
31434
31435
31436
31437
31438
31439
31440
31441
31442
31443
31444
31445
31446
31447
31448
31449
31450
31451
31452
31453
31454
31455
31456
31457
31458
31459
31460
31461
31462
31463
31464
31465
31466
31467
31468
31469
31470
31471
31472
31473
31474
31475
31476
31477
31478
31479
31480
31481
31482
31483
31484
31485
31486
31487
31488
31489
31490
31491
31492
31493
31494
31495
31496
31497
31498
31499
31500
31501
31502
31503
31504
31505
31506
31507
31508
31509
31510
31511
31512
31513
31514
31515
31516
31517
31518
31519
31520
31521
31522
31523
31524
31525
31526
31527
31528
31529
31530
31531
31532
31533
31534
31535
31536
31537
31538
31539
31540
31541
31542
31543
31544
31545
31546
31547
31548
31549
31550
31551
31552
31553
31554
31555
31556
31557
31558
31559
31560
31561
31562
31563
31564
31565
31566
31567
31568
31569
31570
31571
31572
31573
31574
31575
31576
31577
31578
31579
31580
31581
31582
31583
31584
31585
31586
31587
31588
31589
31590
31591
31592
31593
31594
31595
31596
31597
31598
31599
31600
31601
31602
31603
31604
31605
31606
31607
31608
31609
31610
31611
31612
31613
31614
31615
31616
31617
31618
31619
31620
31621
31622
31623
31624
31625
31626
31627
31628
31629
31630
31631
31632
31633
31634
31635
31636
31637
31638
31639
31640
31641
31642
31643
31644
31645
31646
31647
31648
31649
31650
31651
31652
31653
31654
31655
31656
31657
31658
31659
31660
31661
31662
31663
31664
31665
31666
31667
31668
31669
31670
31671
31672
31673
31674
31675
31676
31677
31678
31679
31680
31681
31682
31683
31684
31685
31686
31687
31688
31689
31690
31691
31692
31693
31694
31695
31696
31697
31698
31699
31700
31701
31702
31703
31704
31705
31706
31707
31708
31709
31710
31711
31712
31713
31714
31715
31716
31717
31718
31719
31720
31721
31722
31723
31724
31725
31726
31727
31728
31729
31730
31731
31732
31733
31734
31735
31736
31737
31738
31739
31740
31741
31742
31743
31744
31745
31746
31747
31748
31749
31750
31751
31752
31753
31754
31755
31756
31757
31758
31759
31760
31761
31762
31763
31764
31765
31766
31767
31768
31769
31770
31771
31772
31773
31774
31775
31776
31777
31778
31779
31780
31781
31782
31783
31784
31785
31786
31787
31788
31789
31790
31791
31792
31793
31794
31795
31796
31797
31798
31799
31800
31801
31802
31803
31804
31805
31806
31807
31808
31809
31810
31811
31812
31813
31814
31815
31816
31817
31818
31819
31820
31821
31822
31823
31824
31825
31826
31827
31828
31829
31830
31831
31832
31833
31834
31835
31836
31837
31838
31839
31840
31841
31842
31843
31844
31845
31846
31847
31848
31849
31850
31851
31852
31853
31854
31855
31856
31857
31858
31859
31860
31861
31862
31863
31864
31865
31866
31867
31868
31869
31870
31871
31872
31873
31874
31875
31876
31877
31878
31879
31880
31881
31882
31883
31884
31885
31886
31887
31888
31889
31890
31891
31892
31893
31894
31895
31896
31897
31898
31899
31900
31901
31902
31903
31904
31905
31906
31907
31908
31909
31910
31911
31912
31913
31914
31915
31916
31917
31918
31919
31920
31921
31922
31923
31924
31925
31926
31927
31928
31929
31930
31931
31932
31933
31934
31935
31936
31937
31938
31939
31940
31941
31942
31943
31944
31945
31946
31947
31948
31949
31950
31951
31952
31953
31954
31955
31956
31957
31958
31959
31960
31961
31962
31963
31964
31965
31966
31967
31968
31969
31970
31971
31972
31973
31974
31975
31976
31977
31978
31979
31980
31981
31982
31983
31984
31985
31986
31987
31988
31989
31990
31991
31992
31993
31994
31995
31996
31997
31998
31999
32000
32001
32002
32003
32004
32005
32006
32007
32008
32009
32010
32011
32012
32013
32014
32015
32016
32017
32018
32019
32020
32021
32022
32023
32024
32025
32026
32027
32028
32029
32030
32031
32032
32033
32034
32035
32036
32037
32038
32039
32040
32041
32042
32043
32044
32045
32046
32047
32048
32049
32050
32051
32052
32053
32054
32055
32056
32057
32058
32059
32060
32061
32062
32063
32064
32065
32066
32067
32068
32069
32070
32071
32072
32073
32074
32075
32076
32077
32078
32079
32080
32081
32082
32083
32084
32085
32086
32087
32088
32089
32090
32091
32092
32093
32094
32095
32096
32097
32098
32099
32100
32101
32102
32103
32104
32105
32106
32107
32108
32109
32110
32111
32112
32113
32114
32115
32116
32117
32118
32119
32120
32121
32122
32123
32124
32125
32126
32127
32128
32129
32130
32131
32132
32133
32134
32135
32136
32137
32138
32139
32140
32141
32142
32143
32144
32145
32146
32147
32148
32149
32150
32151
32152
32153
32154
32155
32156
32157
32158
32159
32160
32161
32162
32163
32164
32165
32166
32167
32168
32169
32170
32171
32172
32173
32174
32175
32176
32177
32178
32179
32180
32181
32182
32183
32184
32185
32186
32187
32188
32189
32190
32191
32192
32193
32194
32195
32196
32197
32198
32199
32200
32201
32202
32203
32204
32205
32206
32207
32208
32209
32210
32211
32212
32213
32214
32215
32216
32217
32218
32219
32220
32221
32222
32223
32224
32225
32226
32227
32228
32229
32230
32231
32232
32233
32234
32235
32236
32237
32238
32239
32240
32241
32242
32243
32244
32245
32246
32247
32248
32249
32250
32251
32252
32253
32254
32255
32256
32257
32258
32259
32260
32261
32262
32263
32264
32265
32266
32267
32268
32269
32270
32271
32272
32273
32274
32275
32276
32277
32278
32279
32280
32281
32282
32283
32284
32285
32286
32287
32288
32289
32290
32291
32292
32293
32294
32295
32296
32297
32298
32299
32300
32301
32302
32303
32304
32305
32306
32307
32308
32309
32310
32311
32312
32313
32314
32315
32316
32317
32318
32319
32320
32321
32322
32323
32324
32325
32326
32327
32328
32329
32330
32331
32332
32333
32334
32335
32336
32337
32338
32339
32340
32341
32342
32343
32344
32345
32346
32347
32348
32349
32350
32351
32352
32353
32354
32355
32356
32357
32358
32359
32360
32361
32362
32363
32364
32365
32366
32367
32368
32369
32370
32371
32372
32373
32374
32375
32376
32377
32378
32379
32380
32381
32382
32383
32384
32385
32386
32387
32388
32389
32390
32391
32392
32393
32394
32395
32396
32397
32398
32399
32400
32401
32402
32403
32404
32405
32406
32407
32408
32409
32410
32411
32412
32413
32414
32415
32416
32417
32418
32419
32420
32421
32422
32423
32424
32425
32426
32427
32428
32429
32430
32431
32432
32433
32434
32435
32436
32437
32438
32439
32440
32441
32442
32443
32444
32445
32446
32447
32448
32449
32450
32451
32452
32453
32454
32455
32456
32457
32458
32459
32460
32461
32462
32463
32464
32465
32466
32467
32468
32469
32470
32471
32472
32473
32474
32475
32476
32477
32478
32479
32480
32481
32482
32483
32484
32485
32486
32487
32488
32489
32490
32491
32492
32493
32494
32495
32496
32497
32498
32499
32500
32501
32502
32503
32504
32505
32506
32507
32508
32509
32510
32511
32512
32513
32514
32515
32516
32517
32518
32519
32520
32521
32522
32523
32524
32525
32526
32527
32528
32529
32530
32531
32532
32533
32534
32535
32536
32537
32538
32539
32540
32541
32542
32543
32544
32545
32546
32547
32548
32549
32550
32551
32552
32553
32554
32555
32556
32557
32558
32559
32560
32561
32562
32563
32564
32565
32566
32567
32568
32569
32570
32571
32572
32573
32574
32575
32576
32577
32578
32579
32580
32581
32582
32583
32584
32585
32586
32587
32588
32589
32590
32591
32592
32593
32594
32595
32596
32597
32598
32599
32600
32601
32602
32603
32604
32605
32606
32607
32608
32609
32610
32611
32612
32613
32614
32615
32616
32617
32618
32619
32620
32621
32622
32623
32624
32625
32626
32627
32628
32629
32630
32631
32632
32633
32634
32635
32636
32637
32638
32639
32640
32641
32642
32643
32644
32645
32646
32647
32648
32649
32650
32651
32652
32653
32654
32655
32656
32657
32658
32659
32660
32661
32662
32663
32664
32665
32666
32667
32668
32669
32670
32671
32672
32673
32674
32675
32676
32677
32678
32679
32680
32681
32682
32683
32684
32685
32686
32687
32688
32689
32690
32691
32692
32693
32694
32695
32696
32697
32698
32699
32700
32701
32702
32703
32704
32705
32706
32707
32708
32709
32710
32711
32712
32713
32714
32715
32716
32717
32718
32719
32720
32721
32722
32723
32724
32725
32726
32727
32728
32729
32730
32731
32732
32733
32734
32735
32736
32737
32738
32739
32740
32741
32742
32743
32744
32745
32746
32747
32748
32749
32750
32751
32752
32753
32754
32755
32756
32757
32758
32759
32760
32761
32762
32763
32764
32765
32766
32767
32768
32769
32770
32771
32772
32773
32774
32775
32776
32777
32778
32779
32780
32781
32782
32783
32784
32785
32786
32787
32788
32789
32790
32791
32792
32793
32794
32795
32796
32797
32798
32799
32800
32801
32802
32803
32804
32805
32806
32807
32808
32809
32810
32811
32812
32813
32814
32815
32816
32817
32818
32819
32820
32821
32822
32823
32824
32825
32826
32827
32828
32829
32830
32831
32832
32833
32834
32835
32836
32837
32838
32839
32840
32841
32842
32843
32844
32845
32846
32847
32848
32849
32850
32851
32852
32853
32854
32855
32856
32857
32858
32859
32860
32861
32862
32863
32864
32865
32866
32867
32868
32869
32870
32871
32872
32873
32874
32875
32876
32877
32878
32879
32880
32881
32882
32883
32884
32885
32886
32887
32888
32889
32890
32891
32892
32893
32894
32895
32896
32897
32898
32899
32900
32901
32902
32903
32904
32905
32906
32907
32908
32909
32910
32911
32912
32913
32914
32915
32916
32917
32918
32919
32920
32921
32922
32923
32924
32925
32926
32927
32928
32929
32930
32931
32932
32933
32934
32935
32936
32937
32938
32939
32940
32941
32942
32943
32944
32945
32946
32947
32948
32949
32950
32951
32952
32953
32954
32955
32956
32957
32958
32959
32960
32961
32962
32963
32964
32965
32966
32967
32968
32969
32970
32971
32972
32973
32974
32975
32976
32977
32978
32979
32980
32981
32982
32983
32984
32985
32986
32987
32988
32989
32990
32991
32992
32993
32994
32995
32996
32997
32998
32999
33000
33001
33002
33003
33004
33005
33006
33007
33008
33009
33010
33011
33012
33013
33014
33015
33016
33017
33018
33019
33020
33021
33022
33023
33024
33025
33026
33027
33028
33029
33030
33031
33032
33033
33034
33035
33036
33037
33038
33039
33040
33041
33042
33043
33044
33045
33046
33047
33048
33049
33050
33051
33052
33053
33054
33055
33056
33057
33058
33059
33060
33061
33062
33063
33064
33065
33066
33067
33068
33069
33070
33071
33072
33073
33074
33075
33076
33077
33078
33079
33080
33081
33082
33083
33084
33085
33086
33087
33088
33089
33090
33091
33092
33093
33094
33095
33096
33097
33098
33099
33100
33101
33102
33103
33104
33105
33106
33107
33108
33109
33110
33111
33112
33113
33114
33115
33116
33117
33118
33119
33120
33121
33122
33123
33124
33125
33126
33127
33128
33129
33130
33131
33132
33133
33134
33135
33136
33137
33138
33139
33140
33141
33142
33143
33144
33145
33146
33147
33148
33149
33150
33151
33152
33153
33154
33155
33156
33157
33158
33159
33160
33161
33162
33163
33164
33165
33166
33167
33168
33169
33170
33171
33172
33173
33174
33175
33176
33177
33178
33179
33180
33181
33182
33183
33184
33185
33186
33187
33188
33189
33190
33191
33192
33193
33194
33195
33196
33197
33198
33199
33200
33201
33202
33203
33204
33205
33206
33207
33208
33209
33210
33211
33212
33213
33214
33215
33216
33217
33218
33219
33220
33221
33222
33223
33224
33225
33226
33227
33228
33229
33230
33231
33232
33233
33234
33235
33236
33237
33238
33239
33240
33241
33242
33243
33244
33245
33246
33247
33248
33249
33250
33251
33252
33253
33254
33255
33256
33257
33258
33259
33260
33261
33262
33263
33264
33265
33266
33267
33268
33269
33270
33271
33272
33273
33274
33275
33276
33277
33278
33279
33280
33281
33282
33283
33284
33285
33286
33287
33288
33289
33290
33291
33292
33293
33294
33295
33296
33297
33298
33299
33300
33301
33302
33303
33304
33305
33306
33307
33308
33309
33310
33311
33312
33313
33314
33315
33316
33317
33318
33319
33320
33321
33322
33323
33324
33325
33326
33327
33328
33329
33330
33331
33332
33333
33334
33335
33336
33337
33338
33339
33340
33341
33342
33343
33344
33345
33346
33347
33348
33349
33350
33351
33352
33353
33354
33355
33356
33357
33358
33359
33360
33361
33362
33363
33364
33365
33366
33367
33368
33369
33370
33371
33372
33373
33374
33375
33376
33377
33378
33379
33380
33381
33382
33383
33384
33385
33386
33387
33388
33389
33390
33391
33392
33393
33394
33395
33396
33397
33398
33399
33400
33401
33402
33403
33404
33405
33406
33407
33408
33409
33410
33411
33412
33413
33414
33415
33416
33417
33418
33419
33420
33421
33422
33423
33424
33425
33426
33427
33428
33429
33430
33431
33432
33433
33434
33435
33436
33437
33438
33439
33440
33441
33442
33443
33444
33445
33446
33447
33448
33449
33450
33451
33452
33453
33454
33455
33456
33457
33458
33459
33460
33461
33462
33463
33464
33465
33466
33467
33468
33469
33470
33471
33472
33473
33474
33475
33476
33477
33478
33479
33480
33481
33482
33483
33484
33485
33486
33487
33488
33489
33490
33491
33492
33493
33494
33495
33496
33497
33498
33499
33500
33501
33502
33503
33504
33505
33506
33507
33508
33509
33510
33511
33512
33513
33514
33515
33516
33517
33518
33519
33520
33521
33522
33523
33524
33525
33526
33527
33528
33529
33530
33531
33532
33533
33534
33535
33536
33537
33538
33539
33540
33541
33542
33543
33544
33545
33546
33547
33548
33549
33550
33551
33552
33553
33554
33555
33556
33557
33558
33559
33560
33561
33562
33563
33564
33565
33566
33567
33568
33569
33570
33571
33572
33573
33574
33575
33576
33577
33578
33579
33580
33581
33582
33583
33584
33585
33586
33587
33588
33589
33590
33591
33592
33593
33594
33595
33596
33597
33598
33599
33600
33601
33602
33603
33604
33605
33606
33607
33608
33609
33610
33611
33612
33613
33614
33615
33616
33617
33618
33619
33620
33621
33622
33623
33624
33625
33626
33627
33628
33629
33630
33631
33632
33633
33634
33635
33636
33637
33638
33639
33640
33641
33642
33643
33644
33645
33646
33647
33648
33649
33650
33651
33652
33653
33654
33655
33656
33657
33658
33659
33660
33661
33662
33663
33664
33665
33666
33667
33668
33669
33670
33671
33672
33673
33674
33675
33676
33677
33678
33679
33680
33681
33682
33683
33684
33685
33686
33687
33688
33689
33690
33691
33692
33693
33694
33695
33696
33697
33698
33699
33700
33701
33702
33703
33704
33705
33706
33707
33708
33709
33710
33711
33712
33713
33714
33715
33716
33717
33718
33719
33720
33721
33722
33723
33724
33725
33726
33727
33728
33729
33730
33731
33732
33733
33734
33735
33736
33737
33738
33739
33740
33741
33742
33743
33744
33745
33746
33747
33748
33749
33750
33751
33752
33753
33754
33755
33756
33757
33758
33759
33760
33761
33762
33763
33764
33765
33766
33767
33768
33769
33770
33771
33772
33773
33774
33775
33776
33777
33778
33779
33780
33781
33782
33783
33784
33785
33786
33787
33788
33789
33790
33791
33792
33793
33794
33795
33796
33797
33798
33799
33800
33801
33802
33803
33804
33805
33806
33807
33808
33809
33810
33811
33812
33813
33814
33815
33816
33817
33818
33819
33820
33821
33822
33823
33824
33825
33826
33827
33828
33829
33830
33831
33832
33833
33834
33835
33836
33837
33838
33839
33840
33841
33842
33843
33844
33845
33846
33847
33848
33849
33850
33851
33852
33853
33854
33855
33856
33857
33858
33859
33860
33861
33862
33863
33864
33865
33866
33867
33868
33869
33870
33871
33872
33873
33874
33875
33876
33877
33878
33879
33880
33881
33882
33883
33884
33885
33886
33887
33888
33889
33890
33891
33892
33893
33894
33895
33896
33897
33898
33899
33900
33901
33902
33903
33904
33905
33906
33907
33908
33909
33910
33911
33912
33913
33914
33915
33916
33917
33918
33919
33920
33921
33922
33923
33924
33925
33926
33927
33928
33929
33930
33931
33932
33933
33934
33935
33936
33937
33938
33939
33940
33941
33942
33943
33944
33945
33946
33947
33948
33949
33950
33951
33952
33953
33954
33955
33956
33957
33958
33959
33960
33961
33962
33963
33964
33965
33966
33967
33968
33969
33970
33971
33972
33973
33974
33975
33976
33977
33978
33979
33980
33981
33982
33983
33984
33985
33986
33987
33988
33989
33990
33991
33992
33993
33994
33995
33996
33997
33998
33999
34000
34001
34002
34003
34004
34005
34006
34007
34008
34009
34010
34011
34012
34013
34014
34015
34016
34017
34018
34019
34020
34021
34022
34023
34024
34025
34026
34027
34028
34029
34030
34031
34032
34033
34034
34035
34036
34037
34038
34039
34040
34041
34042
34043
34044
34045
34046
34047
34048
34049
34050
34051
34052
34053
34054
34055
34056
34057
34058
34059
34060
34061
34062
34063
34064
34065
34066
34067
34068
34069
34070
34071
34072
34073
34074
34075
34076
34077
34078
34079
34080
34081
34082
34083
34084
34085
34086
34087
34088
34089
34090
34091
34092
34093
34094
34095
34096
34097
34098
34099
34100
34101
34102
34103
34104
34105
34106
34107
34108
34109
34110
34111
34112
34113
34114
34115
34116
34117
34118
34119
34120
34121
34122
34123
34124
34125
34126
34127
34128
34129
34130
34131
34132
34133
34134
34135
34136
34137
34138
34139
34140
34141
34142
34143
34144
34145
34146
34147
34148
34149
34150
34151
34152
34153
34154
34155
34156
34157
34158
34159
34160
34161
34162
34163
34164
34165
34166
34167
34168
34169
34170
34171
34172
34173
34174
34175
34176
34177
34178
34179
34180
34181
34182
34183
34184
34185
34186
34187
34188
34189
34190
34191
34192
34193
34194
34195
34196
34197
34198
34199
34200
34201
34202
34203
34204
34205
34206
34207
34208
34209
34210
34211
34212
34213
34214
34215
34216
34217
34218
34219
34220
34221
34222
34223
34224
34225
34226
34227
34228
34229
34230
34231
34232
34233
34234
34235
34236
34237
34238
34239
34240
34241
34242
34243
34244
34245
34246
34247
34248
34249
34250
34251
34252
34253
34254
34255
34256
34257
34258
34259
34260
34261
34262
34263
34264
34265
34266
34267
34268
34269
34270
34271
34272
34273
34274
34275
34276
34277
34278
34279
34280
34281
34282
34283
34284
34285
34286
34287
34288
34289
34290
34291
34292
34293
34294
34295
34296
34297
34298
34299
34300
34301
34302
34303
34304
34305
34306
34307
34308
34309
34310
34311
34312
34313
34314
34315
34316
34317
34318
34319
34320
34321
34322
34323
34324
34325
34326
34327
34328
34329
34330
34331
34332
34333
34334
34335
34336
34337
34338
34339
34340
34341
34342
34343
34344
34345
34346
34347
34348
34349
34350
34351
34352
34353
34354
34355
34356
34357
34358
34359
34360
34361
34362
34363
34364
34365
34366
34367
34368
34369
34370
34371
34372
34373
34374
34375
34376
34377
34378
34379
34380
34381
34382
34383
34384
34385
34386
34387
34388
34389
34390
34391
34392
34393
34394
34395
34396
34397
34398
34399
34400
34401
34402
34403
34404
34405
34406
34407
34408
34409
34410
34411
34412
34413
34414
34415
34416
34417
34418
34419
34420
34421
34422
34423
34424
34425
34426
34427
34428
34429
34430
34431
34432
34433
34434
34435
34436
34437
34438
34439
34440
34441
34442
34443
34444
34445
34446
34447
34448
34449
34450
34451
34452
34453
34454
34455
34456
34457
34458
34459
34460
34461
34462
34463
34464
34465
34466
34467
34468
34469
34470
34471
34472
34473
34474
34475
34476
34477
34478
34479
34480
34481
34482
34483
34484
34485
34486
34487
34488
34489
34490
34491
34492
34493
34494
34495
34496
34497
34498
34499
34500
34501
34502
34503
34504
34505
34506
34507
34508
34509
34510
34511
34512
34513
34514
34515
34516
34517
34518
34519
34520
34521
34522
34523
34524
34525
34526
34527
34528
34529
34530
34531
34532
34533
34534
34535
34536
34537
34538
34539
34540
34541
34542
34543
34544
34545
34546
34547
34548
34549
34550
34551
34552
34553
34554
34555
34556
34557
34558
34559
34560
34561
34562
34563
34564
34565
34566
34567
34568
34569
34570
34571
34572
34573
34574
34575
34576
34577
34578
34579
34580
34581
34582
34583
34584
34585
34586
34587
34588
34589
34590
34591
34592
34593
34594
34595
34596
34597
34598
34599
34600
34601
34602
34603
34604
34605
34606
34607
34608
34609
34610
34611
34612
34613
34614
34615
34616
34617
34618
34619
34620
34621
34622
34623
34624
34625
34626
34627
34628
34629
34630
34631
34632
34633
34634
34635
34636
34637
34638
34639
34640
34641
34642
34643
34644
34645
34646
34647
34648
34649
34650
34651
34652
34653
34654
34655
34656
34657
34658
34659
34660
34661
34662
34663
34664
34665
34666
34667
34668
34669
34670
34671
34672
34673
34674
34675
34676
34677
34678
34679
34680
34681
34682
34683
34684
34685
34686
34687
34688
34689
34690
34691
34692
34693
34694
34695
34696
34697
34698
34699
34700
34701
34702
34703
34704
34705
34706
34707
34708
34709
34710
34711
34712
34713
34714
34715
34716
34717
34718
34719
34720
34721
34722
34723
34724
34725
34726
34727
34728
34729
34730
34731
34732
34733
34734
34735
34736
34737
34738
34739
34740
34741
34742
34743
34744
34745
34746
34747
34748
34749
34750
34751
34752
34753
34754
34755
34756
34757
34758
34759
34760
34761
34762
34763
34764
34765
34766
34767
34768
34769
34770
34771
34772
34773
34774
34775
34776
34777
34778
34779
34780
34781
34782
34783
34784
34785
34786
34787
34788
34789
34790
34791
34792
34793
34794
34795
34796
34797
34798
34799
34800
34801
34802
34803
34804
34805
34806
34807
34808
34809
34810
34811
34812
34813
34814
34815
34816
34817
34818
34819
34820
34821
34822
34823
34824
34825
34826
34827
34828
34829
34830
34831
34832
34833
34834
34835
34836
34837
34838
34839
34840
34841
34842
34843
34844
34845
34846
34847
34848
34849
34850
34851
34852
34853
34854
34855
34856
34857
34858
34859
34860
34861
34862
34863
34864
34865
34866
34867
34868
34869
34870
34871
34872
34873
34874
34875
34876
34877
34878
34879
34880
34881
34882
34883
34884
34885
34886
34887
34888
34889
34890
34891
34892
34893
34894
34895
34896
34897
34898
34899
34900
34901
34902
34903
34904
34905
34906
34907
34908
34909
34910
34911
34912
34913
34914
34915
34916
34917
34918
34919
34920
34921
34922
34923
34924
34925
34926
34927
34928
34929
34930
34931
34932
34933
34934
34935
34936
34937
34938
34939
34940
34941
34942
34943
34944
34945
34946
34947
34948
34949
34950
34951
34952
34953
34954
34955
34956
34957
34958
34959
34960
34961
34962
34963
34964
34965
34966
34967
34968
34969
34970
34971
34972
34973
34974
34975
34976
34977
34978
34979
34980
34981
34982
34983
34984
34985
34986
34987
34988
34989
34990
34991
34992
34993
34994
34995
34996
34997
34998
34999
35000
35001
35002
35003
35004
35005
35006
35007
35008
35009
35010
35011
35012
35013
35014
35015
35016
35017
35018
35019
35020
35021
35022
35023
35024
35025
35026
35027
35028
35029
35030
35031
35032
35033
35034
35035
35036
35037
35038
35039
35040
35041
35042
35043
35044
35045
35046
35047
35048
35049
35050
35051
35052
35053
35054
35055
35056
35057
35058
35059
35060
35061
35062
35063
35064
35065
35066
35067
35068
35069
35070
35071
35072
35073
35074
35075
35076
35077
35078
35079
35080
35081
35082
35083
35084
35085
35086
35087
35088
35089
35090
35091
35092
35093
35094
35095
35096
35097
35098
35099
35100
35101
35102
35103
35104
35105
35106
35107
35108
35109
35110
35111
35112
35113
35114
35115
35116
35117
35118
35119
35120
35121
35122
35123
35124
35125
35126
35127
35128
35129
35130
35131
35132
35133
35134
35135
35136
35137
35138
35139
35140
35141
35142
35143
35144
35145
35146
35147
35148
35149
35150
35151
35152
35153
35154
35155
35156
35157
35158
35159
35160
35161
35162
35163
35164
35165
35166
35167
35168
35169
35170
35171
35172
35173
35174
35175
35176
35177
35178
35179
35180
35181
35182
35183
35184
35185
35186
35187
35188
35189
35190
35191
35192
35193
35194
35195
35196
35197
35198
35199
35200
35201
35202
35203
35204
35205
35206
35207
35208
35209
35210
35211
35212
35213
35214
35215
35216
35217
35218
35219
35220
35221
35222
35223
35224
35225
35226
35227
35228
35229
35230
35231
35232
35233
35234
35235
35236
35237
35238
35239
35240
35241
35242
35243
35244
35245
35246
35247
35248
35249
35250
35251
35252
35253
35254
35255
35256
35257
35258
35259
35260
35261
35262
35263
35264
35265
35266
35267
35268
35269
35270
35271
35272
35273
35274
35275
35276
35277
35278
35279
35280
35281
35282
35283
35284
35285
35286
35287
35288
35289
35290
35291
35292
35293
35294
35295
35296
35297
35298
35299
35300
35301
35302
35303
35304
35305
35306
35307
35308
35309
35310
35311
35312
35313
35314
35315
35316
35317
35318
35319
35320
35321
35322
35323
35324
35325
35326
35327
35328
35329
35330
35331
35332
35333
35334
35335
35336
35337
35338
35339
35340
35341
35342
35343
35344
35345
35346
35347
35348
35349
35350
35351
35352
35353
35354
35355
35356
35357
35358
35359
35360
35361
35362
35363
35364
35365
35366
35367
35368
35369
35370
35371
35372
35373
35374
35375
35376
35377
35378
35379
35380
35381
35382
35383
35384
35385
35386
35387
35388
35389
35390
35391
35392
35393
35394
35395
35396
35397
35398
35399
35400
35401
35402
35403
35404
35405
35406
35407
35408
35409
35410
35411
35412
35413
35414
35415
35416
35417
35418
35419
35420
35421
35422
35423
35424
35425
35426
35427
35428
35429
35430
35431
35432
35433
35434
35435
35436
35437
35438
35439
35440
35441
35442
35443
35444
35445
35446
35447
35448
35449
35450
35451
35452
35453
35454
35455
35456
35457
35458
35459
35460
35461
35462
35463
35464
35465
35466
35467
35468
35469
35470
35471
35472
35473
35474
35475
35476
35477
35478
35479
35480
35481
35482
35483
35484
35485
35486
35487
35488
35489
35490
35491
35492
35493
35494
35495
35496
35497
35498
35499
35500
35501
35502
35503
35504
35505
35506
35507
35508
35509
35510
35511
35512
35513
35514
35515
35516
35517
35518
35519
35520
35521
35522
35523
35524
35525
35526
35527
35528
35529
35530
35531
35532
35533
35534
35535
35536
35537
35538
35539
35540
35541
35542
35543
35544
35545
35546
35547
35548
35549
35550
35551
35552
35553
35554
35555
35556
35557
35558
35559
35560
35561
35562
35563
35564
35565
35566
35567
35568
35569
35570
35571
35572
35573
35574
35575
35576
35577
35578
35579
35580
35581
35582
35583
35584
35585
35586
35587
35588
35589
35590
35591
35592
35593
35594
35595
35596
35597
35598
35599
35600
35601
35602
35603
35604
35605
35606
35607
35608
35609
35610
35611
35612
35613
35614
35615
35616
35617
35618
35619
35620
35621
35622
35623
35624
35625
35626
35627
35628
35629
35630
35631
35632
35633
35634
35635
35636
35637
35638
35639
35640
35641
35642
35643
35644
35645
35646
35647
35648
35649
35650
35651
35652
35653
35654
35655
35656
35657
35658
35659
35660
35661
35662
35663
35664
35665
35666
35667
35668
35669
35670
35671
35672
35673
35674
35675
35676
35677
35678
35679
35680
35681
35682
35683
35684
35685
35686
35687
35688
35689
35690
35691
35692
35693
35694
35695
35696
35697
35698
35699
35700
35701
35702
35703
35704
35705
35706
35707
35708
35709
35710
35711
35712
35713
35714
35715
35716
35717
35718
35719
35720
35721
35722
35723
35724
35725
35726
35727
35728
35729
35730
35731
35732
35733
35734
35735
35736
35737
35738
35739
35740
35741
35742
35743
35744
35745
35746
35747
35748
35749
35750
35751
35752
35753
35754
35755
35756
35757
35758
35759
35760
35761
35762
35763
35764
35765
35766
35767
35768
35769
35770
35771
35772
35773
35774
35775
35776
35777
35778
35779
35780
35781
35782
35783
35784
35785
35786
35787
35788
35789
35790
35791
35792
35793
35794
35795
35796
35797
35798
35799
35800
35801
35802
35803
35804
35805
35806
35807
35808
35809
35810
35811
35812
35813
35814
35815
35816
35817
35818
35819
35820
35821
35822
35823
35824
35825
35826
35827
35828
35829
35830
35831
35832
35833
35834
35835
35836
35837
35838
35839
35840
35841
35842
35843
35844
35845
35846
35847
35848
35849
35850
35851
35852
35853
35854
35855
35856
35857
35858
35859
35860
35861
35862
35863
35864
35865
35866
35867
35868
35869
35870
35871
35872
35873
35874
35875
35876
35877
35878
35879
35880
35881
35882
35883
35884
35885
35886
35887
35888
35889
35890
35891
35892
35893
35894
35895
35896
35897
35898
35899
35900
35901
35902
35903
35904
35905
35906
35907
35908
35909
35910
35911
35912
35913
35914
35915
35916
35917
35918
35919
35920
35921
35922
35923
35924
35925
35926
35927
35928
35929
35930
35931
35932
35933
35934
35935
35936
35937
35938
35939
35940
35941
35942
35943
35944
35945
35946
35947
35948
35949
35950
35951
35952
35953
35954
35955
35956
35957
35958
35959
35960
35961
35962
35963
35964
35965
35966
35967
35968
35969
35970
35971
35972
35973
35974
35975
35976
35977
35978
35979
35980
35981
35982
35983
35984
35985
35986
35987
35988
35989
35990
35991
35992
35993
35994
35995
35996
35997
35998
35999
36000
36001
36002
36003
36004
36005
36006
36007
36008
36009
36010
36011
36012
36013
36014
36015
36016
36017
36018
36019
36020
36021
36022
36023
36024
36025
36026
36027
36028
36029
36030
36031
36032
36033
36034
36035
36036
36037
36038
36039
36040
36041
36042
36043
36044
36045
36046
36047
36048
36049
36050
36051
36052
36053
36054
36055
36056
36057
36058
36059
36060
36061
36062
36063
36064
36065
36066
36067
36068
36069
36070
36071
36072
36073
36074
36075
36076
36077
36078
36079
36080
36081
36082
36083
36084
36085
36086
36087
36088
36089
36090
36091
36092
36093
36094
36095
36096
36097
36098
36099
36100
36101
36102
36103
36104
36105
36106
36107
36108
36109
36110
36111
36112
36113
36114
36115
36116
36117
36118
36119
36120
36121
36122
36123
36124
36125
36126
36127
36128
36129
36130
36131
36132
36133
36134
36135
36136
36137
36138
36139
36140
36141
36142
36143
36144
36145
36146
36147
36148
36149
36150
36151
36152
36153
36154
36155
36156
36157
36158
36159
36160
36161
36162
36163
36164
36165
36166
36167
36168
36169
36170
36171
36172
36173
36174
36175
36176
36177
36178
36179
36180
36181
36182
36183
36184
36185
36186
36187
36188
36189
36190
36191
36192
36193
36194
36195
36196
36197
36198
36199
36200
36201
36202
36203
36204
36205
36206
36207
36208
36209
36210
36211
36212
36213
36214
36215
36216
36217
36218
36219
36220
36221
36222
36223
36224
36225
36226
36227
36228
36229
36230
36231
36232
36233
36234
36235
36236
36237
36238
36239
36240
36241
36242
36243
36244
36245
36246
36247
36248
36249
36250
36251
36252
36253
36254
36255
36256
36257
36258
36259
36260
36261
36262
36263
36264
36265
36266
36267
36268
36269
36270
36271
36272
36273
36274
36275
36276
36277
36278
36279
36280
36281
36282
36283
36284
36285
36286
36287
36288
36289
36290
36291
36292
36293
36294
36295
36296
36297
36298
36299
36300
36301
36302
36303
36304
36305
36306
36307
36308
36309
36310
36311
36312
36313
36314
36315
36316
36317
36318
36319
36320
36321
36322
36323
36324
36325
36326
36327
36328
36329
36330
36331
36332
36333
36334
36335
36336
36337
36338
36339
36340
36341
36342
36343
36344
36345
36346
36347
36348
36349
36350
36351
36352
36353
36354
36355
36356
36357
36358
36359
36360
36361
36362
36363
36364
36365
36366
36367
36368
36369
36370
36371
36372
36373
36374
36375
36376
36377
36378
36379
36380
36381
36382
36383
36384
36385
36386
36387
36388
36389
36390
36391
36392
36393
36394
36395
36396
36397
36398
36399
36400
36401
36402
36403
36404
36405
36406
36407
36408
36409
36410
36411
36412
36413
36414
36415
36416
36417
36418
36419
36420
36421
36422
36423
36424
36425
36426
36427
36428
36429
36430
36431
36432
36433
36434
36435
36436
36437
36438
36439
36440
36441
36442
36443
36444
36445
36446
36447
36448
36449
36450
36451
36452
36453
36454
36455
36456
36457
36458
36459
36460
36461
36462
36463
36464
36465
36466
36467
36468
36469
36470
36471
36472
36473
36474
36475
36476
36477
36478
36479
36480
36481
36482
36483
36484
36485
36486
36487
36488
36489
36490
36491
36492
36493
36494
36495
36496
36497
36498
36499
36500
36501
36502
36503
36504
36505
36506
36507
36508
36509
36510
36511
36512
36513
36514
36515
36516
36517
36518
36519
36520
36521
36522
36523
36524
36525
36526
36527
36528
36529
36530
36531
36532
36533
36534
36535
36536
36537
36538
36539
36540
36541
36542
36543
36544
36545
36546
36547
36548
36549
36550
36551
36552
36553
36554
36555
36556
36557
36558
36559
36560
36561
36562
36563
36564
36565
36566
36567
36568
36569
36570
36571
36572
36573
36574
36575
36576
36577
36578
36579
36580
36581
36582
36583
36584
36585
36586
36587
36588
36589
36590
36591
36592
36593
36594
36595
36596
36597
36598
36599
36600
36601
36602
36603
36604
36605
36606
36607
36608
36609
36610
36611
36612
36613
36614
36615
36616
36617
36618
36619
36620
36621
36622
36623
36624
36625
36626
36627
36628
36629
36630
36631
36632
36633
36634
36635
36636
36637
36638
36639
36640
36641
36642
36643
36644
36645
36646
36647
36648
36649
36650
36651
36652
36653
36654
36655
36656
36657
36658
36659
36660
36661
36662
36663
36664
36665
36666
36667
36668
36669
36670
36671
36672
36673
36674
36675
36676
36677
36678
36679
36680
36681
36682
36683
36684
36685
36686
36687
36688
36689
36690
36691
36692
36693
36694
36695
36696
36697
36698
36699
36700
36701
36702
36703
36704
36705
36706
36707
36708
36709
36710
36711
36712
36713
36714
36715
36716
36717
36718
36719
36720
36721
36722
36723
36724
36725
36726
36727
36728
36729
36730
36731
36732
36733
36734
36735
36736
36737
36738
36739
36740
36741
36742
36743
36744
36745
36746
36747
36748
36749
36750
36751
36752
36753
36754
36755
36756
36757
36758
36759
36760
36761
36762
36763
36764
36765
36766
36767
36768
36769
36770
36771
36772
36773
36774
36775
36776
36777
36778
36779
36780
36781
36782
36783
36784
36785
36786
36787
36788
36789
36790
36791
36792
36793
36794
36795
36796
36797
36798
36799
36800
36801
36802
36803
36804
36805
36806
36807
36808
36809
36810
36811
36812
36813
36814
36815
36816
36817
36818
36819
36820
36821
36822
36823
36824
36825
36826
36827
36828
36829
36830
36831
36832
36833
36834
36835
36836
36837
36838
36839
36840
36841
36842
36843
36844
36845
36846
36847
36848
36849
36850
36851
36852
36853
36854
36855
36856
36857
36858
36859
36860
36861
36862
36863
36864
36865
36866
36867
36868
36869
36870
36871
36872
36873
36874
36875
36876
36877
36878
36879
36880
36881
36882
36883
36884
36885
36886
36887
36888
36889
36890
36891
36892
36893
36894
36895
36896
36897
36898
36899
36900
36901
36902
36903
36904
36905
36906
36907
36908
36909
36910
36911
36912
36913
36914
36915
36916
36917
36918
36919
36920
36921
36922
36923
36924
36925
36926
36927
36928
36929
36930
36931
36932
36933
36934
36935
36936
36937
36938
36939
36940
36941
36942
36943
36944
36945
36946
36947
36948
36949
36950
36951
36952
36953
36954
36955
36956
36957
36958
36959
36960
36961
36962
36963
36964
36965
36966
36967
36968
36969
36970
36971
36972
36973
36974
36975
36976
36977
36978
36979
36980
36981
36982
36983
36984
36985
36986
36987
36988
36989
36990
36991
36992
36993
36994
36995
36996
36997
36998
36999
37000
37001
37002
37003
37004
37005
37006
37007
37008
37009
37010
37011
37012
37013
37014
37015
37016
37017
37018
37019
37020
37021
37022
37023
37024
37025
37026
37027
37028
37029
37030
37031
37032
37033
37034
37035
37036
37037
37038
37039
37040
37041
37042
37043
37044
37045
37046
37047
37048
37049
37050
37051
37052
37053
37054
37055
37056
37057
37058
37059
37060
37061
37062
37063
37064
37065
37066
37067
37068
37069
37070
37071
37072
37073
37074
37075
37076
37077
37078
37079
37080
37081
37082
37083
37084
37085
37086
37087
37088
37089
37090
37091
37092
37093
37094
37095
37096
37097
37098
37099
37100
37101
37102
37103
37104
37105
37106
37107
37108
37109
37110
37111
37112
37113
37114
37115
37116
37117
37118
37119
37120
37121
37122
37123
37124
37125
37126
37127
37128
37129
37130
37131
37132
37133
37134
37135
37136
37137
37138
37139
37140
37141
37142
37143
37144
37145
37146
37147
37148
37149
37150
37151
37152
37153
37154
37155
37156
37157
37158
37159
37160
37161
37162
37163
37164
37165
37166
37167
37168
37169
37170
37171
37172
37173
37174
37175
37176
37177
37178
37179
37180
37181
37182
37183
37184
37185
37186
37187
37188
37189
37190
37191
37192
37193
37194
37195
37196
37197
37198
37199
37200
37201
37202
37203
37204
37205
37206
37207
37208
37209
37210
37211
37212
37213
37214
37215
37216
37217
37218
37219
37220
37221
37222
37223
37224
37225
37226
37227
37228
37229
37230
37231
37232
37233
37234
37235
37236
37237
37238
37239
37240
37241
37242
37243
37244
37245
37246
37247
37248
37249
37250
37251
37252
37253
37254
37255
37256
37257
37258
37259
37260
37261
37262
37263
37264
37265
37266
37267
37268
37269
37270
37271
37272
37273
37274
37275
37276
37277
37278
37279
37280
37281
37282
37283
37284
37285
37286
37287
37288
37289
37290
37291
37292
37293
37294
37295
37296
37297
37298
37299
37300
37301
37302
37303
37304
37305
37306
37307
37308
37309
37310
37311
37312
37313
37314
37315
37316
37317
37318
37319
37320
37321
37322
37323
37324
37325
37326
37327
37328
37329
37330
37331
37332
37333
37334
37335
37336
37337
37338
37339
37340
37341
37342
37343
37344
37345
37346
37347
37348
37349
37350
37351
37352
37353
37354
37355
37356
37357
37358
37359
37360
37361
37362
37363
37364
37365
37366
37367
37368
37369
37370
37371
37372
37373
37374
37375
37376
37377
37378
37379
37380
37381
37382
37383
37384
37385
37386
37387
37388
37389
37390
37391
37392
37393
37394
37395
37396
37397
37398
37399
37400
37401
37402
37403
37404
37405
37406
37407
37408
37409
37410
37411
37412
37413
37414
37415
37416
37417
37418
37419
37420
37421
37422
37423
37424
37425
37426
37427
37428
37429
37430
37431
37432
37433
37434
37435
37436
37437
37438
37439
37440
37441
37442
37443
37444
37445
37446
37447
37448
37449
37450
37451
37452
37453
37454
37455
37456
37457
37458
37459
37460
37461
37462
37463
37464
37465
37466
37467
37468
37469
37470
37471
37472
37473
37474
37475
37476
37477
37478
37479
37480
37481
37482
37483
37484
37485
37486
37487
37488
37489
37490
37491
37492
37493
37494
37495
37496
37497
37498
37499
37500
37501
37502
37503
37504
37505
37506
37507
37508
37509
37510
37511
37512
37513
37514
37515
37516
37517
37518
37519
37520
37521
37522
37523
37524
37525
37526
37527
37528
37529
37530
37531
37532
37533
37534
37535
37536
37537
37538
37539
37540
37541
37542
37543
37544
37545
37546
37547
37548
37549
37550
37551
37552
37553
37554
37555
37556
37557
37558
37559
37560
37561
37562
37563
37564
37565
37566
37567
37568
37569
37570
37571
37572
37573
37574
37575
37576
37577
37578
37579
37580
37581
37582
37583
37584
37585
37586
37587
37588
37589
37590
37591
37592
37593
37594
37595
37596
37597
37598
37599
37600
37601
37602
37603
37604
37605
37606
37607
37608
37609
37610
37611
37612
37613
37614
37615
37616
37617
37618
37619
37620
37621
37622
37623
37624
37625
37626
37627
37628
37629
37630
37631
37632
37633
37634
37635
37636
37637
37638
37639
37640
37641
37642
37643
37644
37645
37646
37647
37648
37649
37650
37651
37652
37653
37654
37655
37656
37657
37658
37659
37660
37661
37662
37663
37664
37665
37666
37667
37668
37669
37670
37671
37672
37673
37674
37675
37676
37677
37678
37679
37680
37681
37682
37683
37684
37685
37686
37687
37688
37689
37690
37691
37692
37693
37694
37695
37696
37697
37698
37699
37700
37701
37702
37703
37704
37705
37706
37707
37708
37709
37710
37711
37712
37713
37714
37715
37716
37717
37718
37719
37720
37721
37722
37723
37724
37725
37726
37727
37728
37729
37730
37731
37732
37733
37734
37735
37736
37737
37738
37739
37740
37741
37742
37743
37744
37745
37746
37747
37748
37749
37750
37751
37752
37753
37754
37755
37756
37757
37758
37759
37760
37761
37762
37763
37764
37765
37766
37767
37768
37769
37770
37771
37772
37773
37774
37775
37776
37777
37778
37779
37780
37781
37782
37783
37784
37785
37786
37787
37788
37789
37790
37791
37792
37793
37794
37795
37796
37797
37798
37799
37800
37801
37802
37803
37804
37805
37806
37807
37808
37809
37810
37811
37812
37813
37814
37815
37816
37817
37818
37819
37820
37821
37822
37823
37824
37825
37826
37827
37828
37829
37830
37831
37832
37833
37834
37835
37836
37837
37838
37839
37840
37841
37842
37843
37844
37845
37846
37847
37848
37849
37850
37851
37852
37853
37854
37855
37856
37857
37858
37859
37860
37861
37862
37863
37864
37865
37866
37867
37868
37869
37870
37871
37872
37873
37874
37875
37876
37877
37878
37879
37880
37881
37882
37883
37884
37885
37886
37887
37888
37889
37890
37891
37892
37893
37894
37895
37896
37897
37898
37899
37900
37901
37902
37903
37904
37905
37906
37907
37908
37909
37910
37911
37912
37913
37914
37915
37916
37917
37918
37919
37920
37921
37922
37923
37924
37925
37926
37927
37928
37929
37930
37931
37932
37933
37934
37935
37936
37937
37938
37939
37940
37941
37942
37943
37944
37945
37946
37947
37948
37949
37950
37951
37952
37953
37954
37955
37956
37957
37958
37959
37960
37961
37962
37963
37964
37965
37966
37967
37968
37969
37970
37971
37972
37973
37974
37975
37976
37977
37978
37979
37980
37981
37982
37983
37984
37985
37986
37987
37988
37989
37990
37991
37992
37993
37994
37995
37996
37997
37998
37999
38000
38001
38002
38003
38004
38005
38006
38007
38008
38009
38010
38011
38012
38013
38014
38015
38016
38017
38018
38019
38020
38021
38022
38023
38024
38025
38026
38027
38028
38029
38030
38031
38032
38033
38034
38035
38036
38037
38038
38039
38040
38041
38042
38043
38044
38045
38046
38047
38048
38049
38050
38051
38052
38053
38054
38055
38056
38057
38058
38059
38060
38061
38062
38063
38064
38065
38066
38067
38068
38069
38070
38071
38072
38073
38074
38075
38076
38077
38078
38079
38080
38081
38082
38083
38084
38085
38086
38087
38088
38089
38090
38091
38092
38093
38094
38095
38096
38097
38098
38099
38100
38101
38102
38103
38104
38105
38106
38107
38108
38109
38110
38111
38112
38113
38114
38115
38116
38117
38118
38119
38120
38121
38122
38123
38124
38125
38126
38127
38128
38129
38130
38131
38132
38133
38134
38135
38136
38137
38138
38139
38140
38141
38142
38143
38144
38145
38146
38147
38148
38149
38150
38151
38152
38153
38154
38155
38156
38157
38158
38159
38160
38161
38162
38163
38164
38165
38166
38167
38168
38169
38170
38171
38172
38173
38174
38175
38176
38177
38178
38179
38180
38181
38182
38183
38184
38185
38186
38187
38188
38189
38190
38191
38192
38193
38194
38195
38196
38197
38198
38199
38200
38201
38202
38203
38204
38205
38206
38207
38208
38209
38210
38211
38212
38213
38214
38215
38216
38217
38218
38219
38220
38221
38222
38223
38224
38225
38226
38227
38228
38229
38230
38231
38232
38233
38234
38235
38236
38237
38238
38239
38240
38241
38242
38243
38244
38245
38246
38247
38248
38249
38250
38251
38252
38253
38254
38255
38256
38257
38258
38259
38260
38261
38262
38263
38264
38265
38266
38267
38268
38269
38270
38271
38272
38273
38274
38275
38276
38277
38278
38279
38280
38281
38282
38283
38284
38285
38286
38287
38288
38289
38290
38291
38292
38293
38294
38295
38296
38297
38298
38299
38300
38301
38302
38303
38304
38305
38306
38307
38308
38309
38310
38311
38312
38313
38314
38315
38316
38317
38318
38319
38320
38321
38322
38323
38324
38325
38326
38327
38328
38329
38330
38331
38332
38333
38334
38335
38336
38337
38338
38339
38340
38341
38342
38343
38344
38345
38346
38347
38348
38349
38350
38351
38352
38353
38354
38355
38356
38357
38358
38359
38360
38361
38362
38363
38364
38365
38366
38367
38368
38369
38370
38371
38372
38373
38374
38375
38376
38377
38378
38379
38380
38381
38382
38383
38384
38385
38386
38387
38388
38389
38390
38391
38392
38393
38394
38395
38396
38397
38398
38399
38400
38401
38402
38403
38404
38405
38406
38407
38408
38409
38410
38411
38412
38413
38414
38415
38416
38417
38418
38419
38420
38421
38422
38423
38424
38425
38426
38427
38428
38429
38430
38431
38432
38433
38434
38435
38436
38437
38438
38439
38440
38441
38442
38443
38444
38445
38446
38447
38448
38449
38450
38451
38452
38453
38454
38455
38456
38457
38458
38459
38460
38461
38462
38463
38464
38465
38466
38467
38468
38469
38470
38471
38472
38473
38474
38475
38476
38477
38478
38479
38480
38481
38482
38483
38484
38485
38486
38487
38488
38489
38490
38491
38492
38493
38494
38495
38496
38497
38498
38499
38500
38501
38502
38503
38504
38505
38506
38507
38508
38509
38510
38511
38512
38513
38514
38515
38516
38517
38518
38519
38520
38521
38522
38523
38524
38525
38526
38527
38528
38529
38530
38531
38532
38533
38534
38535
38536
38537
38538
38539
38540
38541
38542
38543
38544
38545
38546
38547
38548
38549
38550
38551
38552
38553
38554
38555
38556
38557
38558
38559
38560
38561
38562
38563
38564
38565
38566
38567
38568
38569
38570
38571
38572
38573
38574
38575
38576
38577
38578
38579
38580
38581
38582
38583
38584
38585
38586
38587
38588
38589
38590
38591
38592
38593
38594
38595
38596
38597
38598
38599
38600
38601
38602
38603
38604
38605
38606
38607
38608
38609
38610
38611
38612
38613
38614
38615
38616
38617
38618
38619
38620
38621
38622
38623
38624
38625
38626
38627
38628
38629
38630
38631
38632
38633
38634
38635
38636
38637
38638
38639
38640
38641
38642
38643
38644
38645
38646
38647
38648
38649
38650
38651
38652
38653
38654
38655
38656
38657
38658
38659
38660
38661
38662
38663
38664
38665
38666
38667
38668
38669
38670
38671
38672
38673
38674
38675
38676
38677
38678
38679
38680
38681
38682
38683
38684
38685
38686
38687
38688
38689
38690
38691
38692
38693
38694
38695
38696
38697
38698
38699
38700
38701
38702
38703
38704
38705
38706
38707
38708
38709
38710
38711
38712
38713
38714
38715
38716
38717
38718
38719
38720
38721
38722
38723
38724
38725
38726
38727
38728
38729
38730
38731
38732
38733
38734
38735
38736
38737
38738
38739
38740
38741
38742
38743
38744
38745
38746
38747
38748
38749
38750
38751
38752
38753
38754
38755
38756
38757
38758
38759
38760
38761
38762
38763
38764
38765
38766
38767
38768
38769
38770
38771
38772
38773
38774
38775
38776
38777
38778
38779
38780
38781
38782
38783
38784
38785
38786
38787
38788
38789
38790
38791
38792
38793
38794
38795
38796
38797
38798
38799
38800
38801
38802
38803
38804
38805
38806
38807
38808
38809
38810
38811
38812
38813
38814
38815
38816
38817
38818
38819
38820
38821
38822
38823
38824
38825
38826
38827
38828
38829
38830
38831
38832
38833
38834
38835
38836
38837
38838
38839
38840
38841
38842
38843
38844
38845
38846
38847
38848
38849
38850
38851
38852
38853
38854
38855
38856
38857
38858
38859
38860
38861
38862
38863
38864
38865
38866
38867
38868
38869
38870
38871
38872
38873
38874
38875
38876
38877
38878
38879
38880
38881
38882
38883
38884
38885
38886
38887
38888
38889
38890
38891
38892
38893
38894
38895
38896
38897
38898
38899
38900
38901
38902
38903
38904
38905
38906
38907
38908
38909
38910
38911
38912
38913
38914
38915
38916
38917
38918
38919
38920
38921
38922
38923
38924
38925
38926
38927
38928
38929
38930
38931
38932
38933
38934
38935
38936
38937
38938
38939
38940
38941
38942
38943
38944
38945
38946
38947
38948
38949
38950
38951
38952
38953
38954
38955
38956
38957
38958
38959
38960
38961
38962
38963
38964
38965
38966
38967
38968
38969
38970
38971
38972
38973
38974
38975
38976
38977
38978
38979
38980
38981
38982
38983
38984
38985
38986
38987
38988
38989
38990
38991
38992
38993
38994
38995
38996
38997
38998
38999
39000
39001
39002
39003
39004
39005
39006
39007
39008
39009
39010
39011
39012
39013
39014
39015
39016
39017
39018
39019
39020
39021
39022
39023
39024
39025
39026
39027
39028
39029
39030
39031
39032
39033
39034
39035
39036
39037
39038
39039
39040
39041
39042
39043
39044
39045
39046
39047
39048
39049
39050
39051
39052
39053
39054
39055
39056
39057
39058
39059
39060
39061
39062
39063
39064
39065
39066
39067
39068
39069
39070
39071
39072
39073
39074
39075
39076
39077
39078
39079
39080
39081
39082
39083
39084
39085
39086
39087
39088
39089
39090
39091
39092
39093
39094
39095
39096
39097
39098
39099
39100
39101
39102
39103
39104
39105
39106
39107
39108
39109
39110
39111
39112
39113
39114
39115
39116
39117
39118
39119
39120
39121
39122
39123
39124
39125
39126
39127
39128
39129
39130
39131
39132
39133
39134
39135
39136
39137
39138
39139
39140
39141
39142
39143
39144
39145
39146
39147
39148
39149
39150
39151
39152
39153
39154
39155
39156
39157
39158
39159
39160
39161
39162
39163
39164
39165
39166
39167
39168
39169
39170
39171
39172
39173
39174
39175
39176
39177
39178
39179
39180
39181
39182
39183
39184
39185
39186
39187
39188
39189
39190
39191
39192
39193
39194
39195
39196
39197
39198
39199
39200
39201
39202
39203
39204
39205
39206
39207
39208
39209
39210
39211
39212
39213
39214
39215
39216
39217
39218
39219
39220
39221
39222
39223
39224
39225
39226
39227
39228
39229
39230
39231
39232
39233
39234
39235
39236
39237
39238
39239
39240
39241
39242
39243
39244
39245
39246
39247
39248
39249
39250
39251
39252
39253
39254
39255
39256
39257
39258
39259
39260
39261
39262
39263
39264
39265
39266
39267
39268
39269
39270
39271
39272
39273
39274
39275
39276
39277
39278
39279
39280
39281
39282
39283
39284
39285
39286
39287
39288
39289
39290
39291
39292
39293
39294
39295
39296
39297
39298
39299
39300
39301
39302
39303
39304
39305
39306
39307
39308
39309
39310
39311
39312
39313
39314
39315
39316
39317
39318
39319
39320
39321
39322
39323
39324
39325
39326
39327
39328
39329
39330
39331
39332
39333
39334
39335
39336
39337
39338
39339
39340
39341
39342
39343
39344
39345
39346
39347
39348
39349
39350
39351
39352
39353
39354
39355
39356
39357
39358
39359
39360
39361
39362
39363
39364
39365
39366
39367
39368
39369
39370
39371
39372
39373
39374
39375
39376
39377
39378
39379
39380
39381
39382
39383
39384
39385
39386
39387
39388
39389
39390
39391
39392
39393
39394
39395
39396
39397
39398
39399
39400
39401
39402
39403
39404
39405
39406
39407
39408
39409
39410
39411
39412
39413
39414
39415
39416
39417
39418
39419
39420
39421
39422
39423
39424
39425
39426
39427
39428
39429
39430
39431
39432
39433
39434
39435
39436
39437
39438
39439
39440
39441
39442
39443
39444
39445
39446
39447
39448
39449
39450
39451
39452
39453
39454
39455
39456
39457
39458
39459
39460
39461
39462
39463
39464
39465
39466
39467
39468
39469
39470
39471
39472
39473
39474
39475
39476
39477
39478
39479
39480
39481
39482
39483
39484
39485
39486
39487
39488
39489
39490
39491
39492
39493
39494
39495
39496
39497
39498
39499
39500
39501
39502
39503
39504
39505
39506
39507
39508
39509
39510
39511
39512
39513
39514
39515
39516
39517
39518
39519
39520
39521
39522
39523
39524
39525
39526
39527
39528
39529
39530
39531
39532
39533
39534
39535
39536
39537
39538
39539
39540
39541
39542
39543
39544
39545
39546
39547
39548
39549
39550
39551
39552
39553
39554
39555
39556
39557
39558
39559
39560
39561
39562
39563
39564
39565
39566
39567
39568
39569
39570
39571
39572
39573
39574
39575
39576
39577
39578
39579
39580
39581
39582
39583
39584
39585
39586
39587
39588
39589
39590
39591
39592
39593
39594
39595
39596
39597
39598
39599
39600
39601
39602
39603
39604
39605
39606
39607
39608
39609
39610
39611
39612
39613
39614
39615
39616
39617
39618
39619
39620
39621
39622
39623
39624
39625
39626
39627
39628
39629
39630
39631
39632
39633
39634
39635
39636
39637
39638
39639
39640
39641
39642
39643
39644
39645
39646
39647
39648
39649
39650
39651
39652
39653
39654
39655
39656
39657
39658
39659
39660
39661
39662
39663
39664
39665
39666
39667
39668
39669
39670
39671
39672
39673
39674
39675
39676
39677
39678
39679
39680
39681
39682
39683
39684
39685
39686
39687
39688
39689
39690
39691
39692
39693
39694
39695
39696
39697
39698
39699
39700
39701
39702
39703
39704
39705
39706
39707
39708
39709
39710
39711
39712
39713
39714
39715
39716
39717
39718
39719
39720
39721
39722
39723
39724
39725
39726
39727
39728
39729
39730
39731
39732
39733
39734
39735
39736
39737
39738
39739
39740
39741
39742
39743
39744
39745
39746
39747
39748
39749
39750
39751
39752
39753
39754
39755
39756
39757
39758
39759
39760
39761
39762
39763
39764
39765
39766
39767
39768
39769
39770
39771
39772
39773
39774
39775
39776
39777
39778
39779
39780
39781
39782
39783
39784
39785
39786
39787
39788
39789
39790
39791
39792
39793
39794
39795
39796
39797
39798
39799
39800
39801
39802
39803
39804
39805
39806
39807
39808
39809
39810
39811
39812
39813
39814
39815
39816
39817
39818
39819
39820
39821
39822
39823
39824
39825
39826
39827
39828
39829
39830
39831
39832
39833
39834
39835
39836
39837
39838
39839
39840
39841
39842
39843
39844
39845
39846
39847
39848
39849
39850
39851
39852
39853
39854
39855
39856
39857
39858
39859
39860
39861
39862
39863
39864
39865
39866
39867
39868
39869
39870
39871
39872
39873
39874
39875
39876
39877
39878
39879
39880
39881
39882
39883
39884
39885
39886
39887
39888
39889
39890
39891
39892
39893
39894
39895
39896
39897
39898
39899
39900
39901
39902
39903
39904
39905
39906
39907
39908
39909
39910
39911
39912
39913
39914
39915
39916
39917
39918
39919
39920
39921
39922
39923
39924
39925
39926
39927
39928
39929
39930
39931
39932
39933
39934
39935
39936
39937
39938
39939
39940
39941
39942
39943
39944
39945
39946
39947
39948
39949
39950
39951
39952
39953
39954
39955
39956
39957
39958
39959
39960
39961
39962
39963
39964
39965
39966
39967
39968
39969
39970
39971
39972
39973
39974
39975
39976
39977
39978
39979
39980
39981
39982
39983
39984
39985
39986
39987
39988
39989
39990
39991
39992
39993
39994
39995
39996
39997
39998
39999
40000
40001
40002
40003
40004
40005
40006
40007
40008
40009
40010
40011
40012
40013
40014
40015
40016
40017
40018
40019
40020
40021
40022
40023
40024
40025
40026
40027
40028
40029
40030
40031
40032
40033
40034
40035
40036
40037
40038
40039
40040
40041
40042
40043
40044
40045
40046
40047
40048
40049
40050
40051
40052
40053
40054
40055
40056
40057
40058
40059
40060
40061
40062
40063
40064
40065
40066
40067
40068
40069
40070
40071
40072
40073
40074
40075
40076
40077
40078
40079
40080
40081
40082
40083
40084
40085
40086
40087
40088
40089
40090
40091
40092
40093
40094
40095
40096
40097
40098
40099
40100
40101
40102
40103
40104
40105
40106
40107
40108
40109
40110
40111
40112
40113
40114
40115
40116
40117
40118
40119
40120
40121
40122
40123
40124
40125
40126
40127
40128
40129
40130
40131
40132
40133
40134
40135
40136
40137
40138
40139
40140
40141
40142
40143
40144
40145
40146
40147
40148
40149
40150
40151
40152
40153
40154
40155
40156
40157
40158
40159
40160
40161
40162
40163
40164
40165
40166
40167
40168
40169
40170
40171
40172
40173
40174
40175
40176
40177
40178
40179
40180
40181
40182
40183
40184
40185
40186
40187
40188
40189
40190
40191
40192
40193
40194
40195
40196
40197
40198
40199
40200
40201
40202
40203
40204
40205
40206
40207
40208
40209
40210
40211
40212
40213
40214
40215
40216
40217
40218
40219
40220
40221
40222
40223
40224
40225
40226
40227
40228
40229
40230
40231
40232
40233
40234
40235
40236
40237
40238
40239
40240
40241
40242
40243
40244
40245
40246
40247
40248
40249
40250
40251
40252
40253
40254
40255
40256
40257
40258
40259
40260
40261
40262
40263
40264
40265
40266
40267
40268
40269
40270
40271
40272
40273
40274
40275
40276
40277
40278
40279
40280
40281
40282
40283
40284
40285
40286
40287
40288
40289
40290
40291
40292
40293
40294
40295
40296
40297
40298
40299
40300
40301
40302
40303
40304
40305
40306
40307
40308
40309
40310
40311
40312
40313
40314
40315
40316
40317
40318
40319
40320
40321
40322
40323
40324
40325
40326
40327
40328
40329
40330
40331
40332
40333
40334
40335
40336
40337
40338
40339
40340
40341
40342
40343
40344
40345
40346
40347
40348
40349
40350
40351
40352
40353
40354
40355
40356
40357
40358
40359
40360
40361
40362
40363
40364
40365
40366
40367
40368
40369
40370
40371
40372
40373
40374
40375
40376
40377
40378
40379
40380
40381
40382
40383
40384
40385
40386
40387
40388
40389
40390
40391
40392
40393
40394
40395
40396
40397
40398
40399
40400
40401
40402
40403
40404
40405
40406
40407
40408
40409
40410
40411
40412
40413
40414
40415
40416
40417
40418
40419
40420
40421
40422
40423
40424
40425
40426
40427
40428
40429
40430
40431
40432
40433
40434
40435
40436
40437
40438
40439
40440
40441
40442
40443
40444
40445
40446
40447
40448
40449
40450
40451
40452
40453
40454
40455
40456
40457
40458
40459
40460
40461
40462
40463
40464
40465
40466
40467
40468
40469
40470
40471
40472
40473
40474
40475
40476
40477
40478
40479
40480
40481
40482
40483
40484
40485
40486
40487
40488
40489
40490
40491
40492
40493
40494
40495
40496
40497
40498
40499
40500
40501
40502
40503
40504
40505
40506
40507
40508
40509
40510
40511
40512
40513
40514
40515
40516
40517
40518
40519
40520
40521
40522
40523
40524
40525
40526
40527
40528
40529
40530
40531
40532
40533
40534
40535
40536
40537
40538
40539
40540
40541
40542
40543
40544
40545
40546
40547
40548
40549
40550
40551
40552
40553
40554
40555
40556
40557
40558
40559
40560
40561
40562
40563
40564
40565
40566
40567
40568
40569
40570
40571
40572
40573
40574
40575
40576
40577
40578
40579
40580
40581
40582
40583
40584
40585
40586
40587
40588
40589
40590
40591
40592
40593
40594
40595
40596
40597
40598
40599
40600
40601
40602
40603
40604
40605
40606
40607
40608
40609
40610
40611
40612
40613
40614
40615
40616
40617
40618
40619
40620
40621
40622
40623
40624
40625
40626
40627
40628
40629
40630
40631
40632
40633
40634
40635
40636
40637
40638
40639
40640
40641
40642
40643
40644
40645
40646
40647
40648
40649
40650
40651
40652
40653
40654
40655
40656
40657
40658
40659
40660
40661
40662
40663
40664
40665
40666
40667
40668
40669
40670
40671
40672
40673
40674
40675
40676
40677
40678
40679
40680
40681
40682
40683
40684
40685
40686
40687
40688
40689
40690
40691
40692
40693
40694
40695
40696
40697
40698
40699
40700
40701
40702
40703
40704
40705
40706
40707
40708
40709
40710
40711
40712
40713
40714
40715
40716
40717
40718
40719
40720
40721
40722
40723
40724
40725
40726
40727
40728
40729
40730
40731
40732
40733
40734
40735
40736
40737
40738
40739
40740
40741
40742
40743
40744
40745
40746
40747
40748
40749
40750
40751
40752
40753
40754
40755
40756
40757
40758
40759
40760
40761
40762
40763
40764
40765
40766
40767
40768
40769
40770
40771
40772
40773
40774
40775
40776
40777
40778
40779
40780
40781
40782
40783
40784
40785
40786
40787
40788
40789
40790
40791
40792
40793
40794
40795
40796
40797
40798
40799
40800
40801
40802
40803
40804
40805
40806
40807
40808
40809
40810
40811
40812
40813
40814
40815
40816
40817
40818
40819
40820
40821
40822
40823
40824
40825
40826
40827
40828
40829
40830
40831
40832
40833
40834
40835
40836
40837
40838
40839
40840
40841
40842
40843
40844
40845
40846
40847
40848
40849
40850
40851
40852
40853
40854
40855
40856
40857
40858
40859
40860
40861
40862
40863
40864
40865
40866
40867
40868
40869
40870
40871
40872
40873
40874
40875
40876
40877
40878
40879
40880
40881
40882
40883
40884
40885
40886
40887
40888
40889
40890
40891
40892
40893
40894
40895
40896
40897
40898
40899
40900
40901
40902
40903
40904
40905
40906
40907
40908
40909
40910
40911
40912
40913
40914
40915
40916
40917
40918
40919
40920
40921
40922
40923
40924
40925
40926
40927
40928
40929
40930
40931
40932
40933
40934
40935
40936
40937
40938
40939
40940
40941
40942
40943
40944
40945
40946
40947
40948
40949
40950
40951
40952
40953
40954
40955
40956
40957
40958
40959
40960
40961
40962
40963
40964
40965
40966
40967
40968
40969
40970
40971
40972
40973
40974
40975
40976
40977
40978
40979
40980
40981
40982
40983
40984
40985
40986
40987
40988
40989
40990
40991
40992
40993
40994
40995
40996
40997
40998
40999
41000
41001
41002
41003
41004
41005
41006
41007
41008
41009
41010
41011
41012
41013
41014
41015
41016
41017
41018
41019
41020
41021
41022
41023
41024
41025
41026
41027
41028
41029
41030
41031
41032
41033
41034
41035
41036
41037
41038
41039
41040
41041
41042
41043
41044
41045
41046
41047
41048
41049
41050
41051
41052
41053
41054
41055
41056
41057
41058
41059
41060
41061
41062
41063
41064
41065
41066
41067
41068
41069
41070
41071
41072
41073
41074
41075
41076
41077
41078
41079
41080
41081
41082
41083
41084
41085
41086
41087
41088
41089
41090
41091
41092
41093
41094
41095
41096
41097
41098
41099
41100
41101
41102
41103
41104
41105
41106
41107
41108
41109
41110
41111
41112
41113
41114
41115
41116
41117
41118
41119
41120
41121
41122
41123
41124
41125
41126
41127
41128
41129
41130
41131
41132
41133
41134
41135
41136
41137
41138
41139
41140
41141
41142
41143
41144
41145
41146
41147
41148
41149
41150
41151
41152
41153
41154
41155
41156
41157
41158
41159
41160
41161
41162
41163
41164
41165
41166
41167
41168
41169
41170
41171
41172
41173
41174
41175
41176
41177
41178
41179
41180
41181
41182
41183
41184
41185
41186
41187
41188
41189
41190
41191
41192
41193
41194
41195
41196
41197
41198
41199
41200
41201
41202
41203
41204
41205
41206
41207
41208
41209
41210
41211
41212
41213
41214
41215
41216
41217
41218
41219
41220
41221
41222
41223
41224
41225
41226
41227
41228
41229
41230
41231
41232
41233
41234
41235
41236
41237
41238
41239
41240
41241
41242
41243
41244
41245
41246
41247
41248
41249
41250
41251
41252
41253
41254
41255
41256
41257
41258
41259
41260
41261
41262
41263
41264
41265
41266
41267
41268
41269
41270
41271
41272
41273
41274
41275
41276
41277
41278
41279
41280
41281
41282
41283
41284
41285
41286
41287
41288
41289
41290
41291
41292
41293
41294
41295
41296
41297
41298
41299
41300
41301
41302
41303
41304
41305
41306
41307
41308
41309
41310
41311
41312
41313
41314
41315
41316
41317
41318
41319
41320
41321
41322
41323
41324
41325
41326
41327
41328
41329
41330
41331
41332
41333
41334
41335
41336
41337
41338
41339
41340
41341
41342
41343
41344
41345
41346
41347
41348
41349
41350
41351
41352
41353
41354
41355
41356
41357
41358
41359
41360
41361
41362
41363
41364
41365
41366
41367
41368
41369
41370
41371
41372
41373
41374
41375
41376
41377
41378
41379
41380
41381
41382
41383
41384
41385
41386
41387
41388
41389
41390
41391
41392
41393
41394
41395
41396
41397
41398
41399
41400
41401
41402
41403
41404
41405
41406
41407
41408
41409
41410
41411
41412
41413
41414
41415
41416
41417
41418
41419
41420
41421
41422
41423
41424
41425
41426
41427
41428
41429
41430
41431
41432
41433
41434
41435
41436
41437
41438
41439
41440
41441
41442
41443
41444
41445
41446
41447
41448
41449
41450
41451
41452
41453
41454
41455
41456
41457
41458
41459
41460
41461
41462
41463
41464
41465
41466
41467
41468
41469
41470
41471
41472
41473
41474
41475
41476
41477
41478
41479
41480
41481
41482
41483
41484
41485
41486
41487
41488
41489
41490
41491
41492
41493
41494
41495
41496
41497
41498
41499
41500
41501
41502
41503
41504
41505
41506
41507
41508
41509
41510
41511
41512
41513
41514
41515
41516
41517
41518
41519
41520
41521
41522
41523
41524
41525
41526
41527
41528
41529
41530
41531
41532
41533
41534
41535
41536
41537
41538
41539
41540
41541
41542
41543
41544
41545
41546
41547
41548
41549
41550
41551
41552
41553
41554
41555
41556
41557
41558
41559
41560
41561
41562
41563
41564
41565
41566
41567
41568
41569
41570
41571
41572
41573
41574
41575
41576
41577
41578
41579
41580
41581
41582
41583
41584
41585
41586
41587
41588
41589
41590
41591
41592
41593
41594
41595
41596
41597
41598
41599
41600
41601
41602
41603
41604
41605
41606
41607
41608
41609
41610
41611
41612
41613
41614
41615
41616
41617
41618
41619
41620
41621
41622
41623
41624
41625
41626
41627
41628
41629
41630
41631
41632
41633
41634
41635
41636
41637
41638
41639
41640
41641
41642
41643
41644
41645
41646
41647
41648
41649
41650
41651
41652
41653
41654
41655
41656
41657
41658
41659
41660
41661
41662
41663
41664
41665
41666
41667
41668
41669
41670
41671
41672
41673
41674
41675
41676
41677
41678
41679
41680
41681
41682
41683
41684
41685
41686
41687
41688
41689
41690
41691
41692
41693
41694
41695
41696
41697
41698
41699
41700
41701
41702
41703
41704
41705
41706
41707
41708
41709
41710
41711
41712
41713
41714
41715
41716
41717
41718
41719
41720
41721
41722
41723
41724
41725
41726
41727
41728
41729
41730
41731
41732
41733
41734
41735
41736
41737
41738
41739
41740
41741
41742
41743
41744
41745
41746
41747
41748
41749
41750
41751
41752
41753
41754
41755
41756
41757
41758
41759
41760
41761
41762
41763
41764
41765
41766
41767
41768
41769
41770
41771
41772
41773
41774
41775
41776
41777
41778
41779
41780
41781
41782
41783
41784
41785
41786
41787
41788
41789
41790
41791
41792
41793
41794
41795
41796
41797
41798
41799
41800
41801
41802
41803
41804
41805
41806
41807
41808
41809
41810
41811
41812
41813
41814
41815
41816
41817
41818
41819
41820
41821
41822
41823
41824
41825
41826
41827
41828
41829
41830
41831
41832
41833
41834
41835
41836
41837
41838
41839
41840
41841
41842
41843
41844
41845
41846
41847
41848
41849
41850
41851
41852
41853
41854
41855
41856
41857
41858
41859
41860
41861
41862
41863
41864
41865
41866
41867
41868
41869
41870
41871
41872
41873
41874
41875
41876
41877
41878
41879
41880
41881
41882
41883
41884
41885
41886
41887
41888
41889
41890
41891
41892
41893
41894
41895
41896
41897
41898
41899
41900
41901
41902
41903
41904
41905
41906
41907
41908
41909
41910
41911
41912
41913
41914
41915
41916
41917
41918
41919
41920
41921
41922
41923
41924
41925
41926
41927
41928
41929
41930
41931
41932
41933
41934
41935
41936
41937
41938
41939
41940
41941
41942
41943
41944
41945
41946
41947
41948
41949
41950
41951
41952
41953
41954
41955
41956
41957
41958
41959
41960
41961
41962
41963
41964
41965
41966
41967
41968
41969
41970
41971
41972
41973
41974
41975
41976
41977
41978
41979
41980
41981
41982
41983
41984
41985
41986
41987
41988
41989
41990
41991
41992
41993
41994
41995
41996
41997
41998
41999
42000
42001
42002
42003
42004
42005
42006
42007
42008
42009
42010
42011
42012
42013
42014
42015
42016
42017
42018
42019
42020
42021
42022
42023
42024
42025
42026
42027
42028
42029
42030
42031
42032
42033
42034
42035
42036
42037
42038
42039
42040
42041
42042
42043
42044
42045
42046
42047
42048
42049
42050
42051
42052
42053
42054
42055
42056
42057
42058
42059
42060
42061
42062
42063
42064
42065
42066
42067
42068
42069
42070
42071
42072
42073
42074
42075
42076
42077
42078
42079
42080
42081
42082
42083
42084
42085
42086
42087
42088
42089
42090
42091
42092
42093
42094
42095
42096
42097
42098
42099
42100
42101
42102
42103
42104
42105
42106
42107
42108
42109
42110
42111
42112
42113
42114
42115
42116
42117
42118
42119
42120
42121
42122
42123
42124
42125
42126
42127
42128
42129
42130
42131
42132
42133
42134
42135
42136
42137
42138
42139
42140
42141
42142
42143
42144
42145
42146
42147
42148
42149
42150
42151
42152
42153
42154
42155
42156
42157
42158
42159
42160
42161
42162
42163
42164
42165
42166
42167
42168
42169
42170
42171
42172
42173
42174
42175
42176
42177
42178
42179
42180
42181
42182
42183
42184
42185
42186
42187
42188
42189
42190
42191
42192
42193
42194
42195
42196
42197
42198
42199
42200
42201
42202
42203
42204
42205
42206
42207
42208
42209
42210
42211
42212
42213
42214
42215
42216
42217
42218
42219
42220
42221
42222
42223
42224
42225
42226
42227
42228
42229
42230
42231
42232
42233
42234
42235
42236
42237
42238
42239
42240
42241
42242
42243
42244
42245
42246
42247
42248
42249
42250
42251
42252
42253
42254
42255
42256
42257
42258
42259
42260
42261
42262
42263
42264
42265
42266
42267
42268
42269
42270
42271
42272
42273
42274
42275
42276
42277
42278
42279
42280
42281
42282
42283
42284
42285
42286
42287
42288
42289
42290
42291
42292
42293
42294
42295
42296
42297
42298
42299
42300
42301
42302
42303
42304
42305
42306
42307
42308
42309
42310
42311
42312
42313
42314
42315
42316
42317
42318
42319
42320
42321
42322
42323
42324
42325
42326
42327
42328
42329
42330
42331
42332
42333
42334
42335
42336
42337
42338
42339
42340
42341
42342
42343
42344
42345
42346
42347
42348
42349
42350
42351
42352
42353
42354
42355
42356
42357
42358
42359
42360
42361
42362
42363
42364
42365
42366
42367
42368
42369
42370
42371
42372
42373
42374
42375
42376
42377
42378
42379
42380
42381
42382
42383
42384
42385
42386
42387
42388
42389
42390
42391
42392
42393
42394
42395
42396
42397
42398
42399
42400
42401
42402
42403
42404
42405
42406
42407
42408
42409
42410
42411
42412
42413
42414
42415
42416
42417
42418
42419
42420
42421
42422
42423
42424
42425
42426
42427
42428
42429
42430
42431
42432
42433
42434
42435
42436
42437
42438
42439
42440
42441
42442
42443
42444
42445
42446
42447
42448
42449
42450
42451
42452
42453
42454
42455
42456
42457
42458
42459
42460
42461
42462
42463
42464
42465
42466
42467
42468
42469
42470
42471
42472
42473
42474
42475
42476
42477
42478
42479
42480
42481
42482
42483
42484
42485
42486
42487
42488
42489
42490
42491
42492
42493
42494
42495
42496
42497
42498
42499
42500
42501
42502
42503
42504
42505
42506
42507
42508
42509
42510
42511
42512
42513
42514
42515
42516
42517
42518
42519
42520
42521
42522
42523
42524
42525
42526
42527
42528
42529
42530
42531
42532
42533
42534
42535
42536
42537
42538
42539
42540
42541
42542
42543
42544
42545
42546
42547
42548
42549
42550
42551
42552
42553
42554
42555
42556
42557
42558
42559
42560
42561
42562
42563
42564
42565
42566
42567
42568
42569
42570
42571
42572
42573
42574
42575
42576
42577
42578
42579
42580
42581
42582
42583
42584
42585
42586
42587
42588
42589
42590
42591
42592
42593
42594
42595
42596
42597
42598
42599
42600
42601
42602
42603
42604
42605
42606
42607
42608
42609
42610
42611
42612
42613
42614
42615
42616
42617
42618
42619
42620
42621
42622
42623
42624
42625
42626
42627
42628
42629
42630
42631
42632
42633
42634
42635
42636
42637
42638
42639
42640
42641
42642
42643
42644
42645
42646
42647
42648
42649
42650
42651
42652
42653
42654
42655
42656
42657
42658
42659
42660
42661
42662
42663
42664
42665
42666
42667
42668
42669
42670
42671
42672
42673
42674
42675
42676
42677
42678
42679
42680
42681
42682
42683
42684
42685
42686
42687
42688
42689
42690
42691
42692
42693
42694
42695
42696
42697
42698
42699
42700
42701
42702
42703
42704
42705
42706
42707
42708
42709
42710
42711
42712
42713
42714
42715
42716
42717
42718
42719
42720
42721
42722
42723
42724
42725
42726
42727
42728
42729
42730
42731
42732
42733
42734
42735
42736
42737
42738
42739
42740
42741
42742
42743
42744
42745
42746
42747
42748
42749
42750
42751
42752
42753
42754
42755
42756
42757
42758
42759
42760
42761
42762
42763
42764
42765
42766
42767
42768
42769
42770
42771
42772
42773
42774
42775
42776
42777
42778
42779
42780
42781
42782
42783
42784
42785
42786
42787
42788
42789
42790
42791
42792
42793
42794
42795
42796
42797
42798
42799
42800
42801
42802
42803
42804
42805
42806
42807
42808
42809
42810
42811
42812
42813
42814
42815
42816
42817
42818
42819
42820
42821
42822
42823
42824
42825
42826
42827
42828
42829
42830
42831
42832
42833
42834
42835
42836
42837
42838
42839
42840
42841
42842
42843
42844
42845
42846
42847
42848
42849
42850
42851
42852
42853
42854
42855
42856
42857
42858
42859
42860
42861
42862
42863
42864
42865
42866
42867
42868
42869
42870
42871
42872
42873
42874
42875
42876
42877
42878
42879
42880
42881
42882
42883
42884
42885
42886
42887
42888
42889
42890
42891
42892
42893
42894
42895
42896
42897
42898
42899
42900
42901
42902
42903
42904
42905
42906
42907
42908
42909
42910
42911
42912
42913
42914
42915
42916
42917
42918
42919
42920
42921
42922
42923
42924
42925
42926
42927
42928
42929
42930
42931
42932
42933
42934
42935
42936
42937
42938
42939
42940
42941
42942
42943
42944
42945
42946
42947
42948
42949
42950
42951
42952
42953
42954
42955
42956
42957
42958
42959
42960
42961
42962
42963
42964
42965
42966
42967
42968
42969
42970
42971
42972
42973
42974
42975
42976
42977
42978
42979
42980
42981
42982
42983
42984
42985
42986
42987
42988
42989
42990
42991
42992
42993
42994
42995
42996
42997
42998
42999
43000
43001
43002
43003
43004
43005
43006
43007
43008
43009
43010
43011
43012
43013
43014
43015
43016
43017
43018
43019
43020
43021
43022
43023
43024
43025
43026
43027
43028
43029
43030
43031
43032
43033
43034
43035
43036
43037
43038
43039
43040
43041
43042
43043
43044
43045
43046
43047
43048
43049
43050
43051
43052
43053
43054
43055
43056
43057
43058
43059
43060
43061
43062
43063
43064
43065
43066
43067
43068
43069
43070
43071
43072
43073
43074
43075
43076
43077
43078
43079
43080
43081
43082
43083
43084
43085
43086
43087
43088
43089
43090
43091
43092
43093
43094
43095
43096
43097
43098
43099
43100
43101
43102
43103
43104
43105
43106
43107
43108
43109
43110
43111
43112
43113
43114
43115
43116
43117
43118
43119
43120
43121
43122
43123
43124
43125
43126
43127
43128
43129
43130
43131
43132
43133
43134
43135
43136
43137
43138
43139
43140
43141
43142
43143
43144
43145
43146
43147
43148
43149
43150
43151
43152
43153
43154
43155
43156
43157
43158
43159
43160
43161
43162
43163
43164
43165
43166
43167
43168
43169
43170
43171
43172
43173
43174
43175
43176
43177
43178
43179
43180
43181
43182
43183
43184
43185
43186
43187
43188
43189
43190
43191
43192
43193
43194
43195
43196
43197
43198
43199
43200
43201
43202
43203
43204
43205
43206
43207
43208
43209
43210
43211
43212
43213
43214
43215
43216
43217
43218
43219
43220
43221
43222
43223
43224
43225
43226
43227
43228
43229
43230
43231
43232
43233
43234
43235
43236
43237
43238
43239
43240
43241
43242
43243
43244
43245
43246
43247
43248
43249
43250
43251
43252
43253
43254
43255
43256
43257
43258
43259
43260
43261
43262
43263
43264
43265
43266
43267
43268
43269
43270
43271
43272
43273
43274
43275
43276
43277
43278
43279
43280
43281
43282
43283
43284
43285
43286
43287
43288
43289
43290
43291
43292
43293
43294
43295
43296
43297
43298
43299
43300
43301
43302
43303
43304
43305
43306
43307
43308
43309
43310
43311
43312
43313
43314
43315
43316
43317
43318
43319
43320
43321
43322
43323
43324
43325
43326
43327
43328
43329
43330
43331
43332
43333
43334
43335
43336
43337
43338
43339
43340
43341
43342
43343
43344
43345
43346
43347
43348
43349
43350
43351
43352
43353
43354
43355
43356
43357
43358
43359
43360
43361
43362
43363
43364
43365
43366
43367
43368
43369
43370
43371
43372
43373
43374
43375
43376
43377
43378
43379
43380
43381
43382
43383
43384
43385
43386
43387
43388
43389
43390
43391
43392
43393
43394
43395
43396
43397
43398
43399
43400
43401
43402
43403
43404
43405
43406
43407
43408
43409
43410
43411
43412
43413
43414
43415
43416
43417
43418
43419
43420
43421
43422
43423
43424
43425
43426
43427
43428
43429
43430
43431
43432
43433
43434
43435
43436
43437
43438
43439
43440
43441
43442
43443
43444
43445
43446
43447
43448
43449
43450
43451
43452
43453
43454
43455
43456
43457
43458
43459
43460
43461
43462
43463
43464
43465
43466
43467
43468
43469
43470
43471
43472
43473
43474
43475
43476
43477
43478
43479
43480
43481
43482
43483
43484
43485
43486
43487
43488
43489
43490
43491
43492
43493
43494
43495
43496
43497
43498
43499
43500
43501
43502
43503
43504
43505
43506
43507
43508
43509
43510
43511
43512
43513
43514
43515
43516
43517
43518
43519
43520
43521
43522
43523
43524
43525
43526
43527
43528
43529
43530
43531
43532
43533
43534
43535
43536
43537
43538
43539
43540
43541
43542
43543
43544
43545
43546
43547
43548
43549
43550
43551
43552
43553
43554
43555
43556
43557
43558
43559
43560
43561
43562
43563
43564
43565
43566
43567
43568
43569
43570
43571
43572
43573
43574
43575
43576
43577
43578
43579
43580
43581
43582
43583
43584
43585
43586
43587
43588
43589
43590
43591
43592
43593
43594
43595
43596
43597
43598
43599
43600
43601
43602
43603
43604
43605
43606
43607
43608
43609
43610
43611
43612
43613
43614
43615
43616
43617
43618
43619
43620
43621
43622
43623
43624
43625
43626
43627
43628
43629
43630
43631
43632
43633
43634
43635
43636
43637
43638
43639
43640
43641
43642
43643
43644
43645
43646
43647
43648
43649
43650
43651
43652
43653
43654
43655
43656
43657
43658
43659
43660
43661
43662
43663
43664
43665
43666
43667
43668
43669
43670
43671
43672
43673
43674
43675
43676
43677
43678
43679
43680
43681
43682
43683
43684
43685
43686
43687
43688
43689
43690
43691
43692
43693
43694
43695
43696
43697
43698
43699
43700
43701
43702
43703
43704
43705
43706
43707
43708
43709
43710
43711
43712
43713
43714
43715
43716
43717
43718
43719
43720
43721
43722
43723
43724
43725
43726
43727
43728
43729
43730
43731
43732
43733
43734
43735
43736
43737
43738
43739
43740
43741
43742
43743
43744
43745
43746
43747
43748
43749
43750
43751
43752
43753
43754
43755
43756
43757
43758
43759
43760
43761
43762
43763
43764
43765
43766
43767
43768
43769
43770
43771
43772
43773
43774
43775
43776
43777
43778
43779
43780
43781
43782
43783
43784
43785
43786
43787
43788
43789
43790
43791
43792
43793
43794
43795
43796
43797
43798
43799
43800
43801
43802
43803
43804
43805
43806
43807
43808
43809
43810
43811
43812
43813
43814
43815
43816
43817
43818
43819
43820
43821
43822
43823
43824
43825
43826
43827
43828
43829
43830
43831
43832
43833
43834
43835
43836
43837
43838
43839
43840
43841
43842
43843
43844
43845
43846
43847
43848
43849
43850
43851
43852
43853
43854
43855
43856
43857
43858
43859
43860
43861
43862
43863
43864
43865
43866
43867
43868
43869
43870
43871
43872
43873
43874
43875
43876
43877
43878
43879
43880
43881
43882
43883
43884
43885
43886
43887
43888
43889
43890
43891
43892
43893
43894
43895
43896
43897
43898
43899
43900
43901
43902
43903
43904
43905
43906
43907
43908
43909
43910
43911
43912
43913
43914
43915
43916
43917
43918
43919
43920
43921
43922
43923
43924
43925
43926
43927
43928
43929
43930
43931
43932
43933
43934
43935
43936
43937
43938
43939
43940
43941
43942
43943
43944
43945
43946
43947
43948
43949
43950
43951
43952
43953
43954
43955
43956
43957
43958
43959
43960
43961
43962
43963
43964
43965
43966
43967
43968
43969
43970
43971
43972
43973
43974
43975
43976
43977
43978
43979
43980
43981
43982
43983
43984
43985
43986
43987
43988
43989
43990
43991
43992
43993
43994
43995
43996
43997
43998
43999
44000
44001
44002
44003
44004
44005
44006
44007
44008
44009
44010
44011
44012
44013
44014
44015
44016
44017
44018
44019
44020
44021
44022
44023
44024
44025
44026
44027
44028
44029
44030
44031
44032
44033
44034
44035
44036
44037
44038
44039
44040
44041
44042
44043
44044
44045
44046
44047
44048
44049
44050
44051
44052
44053
44054
44055
44056
44057
44058
44059
44060
44061
44062
44063
44064
44065
44066
44067
44068
44069
44070
44071
44072
44073
44074
44075
44076
44077
44078
44079
44080
44081
44082
44083
44084
44085
44086
44087
44088
44089
44090
44091
44092
44093
44094
44095
44096
44097
44098
44099
44100
44101
44102
44103
44104
44105
44106
44107
44108
44109
44110
44111
44112
44113
44114
44115
44116
44117
44118
44119
44120
44121
44122
44123
44124
44125
44126
44127
44128
44129
44130
44131
44132
44133
44134
44135
44136
44137
44138
44139
44140
44141
44142
44143
44144
44145
44146
44147
44148
44149
44150
44151
44152
44153
44154
44155
44156
44157
44158
44159
44160
44161
44162
44163
44164
44165
44166
44167
44168
44169
44170
44171
44172
44173
44174
44175
44176
44177
44178
44179
44180
44181
44182
44183
44184
44185
44186
44187
44188
44189
44190
44191
44192
44193
44194
44195
44196
44197
44198
44199
44200
44201
44202
44203
44204
44205
44206
44207
44208
44209
44210
44211
44212
44213
44214
44215
44216
44217
44218
44219
44220
44221
44222
44223
44224
44225
44226
44227
44228
44229
44230
44231
44232
44233
44234
44235
44236
44237
44238
44239
44240
44241
44242
44243
44244
44245
44246
44247
44248
44249
44250
44251
44252
44253
44254
44255
44256
44257
44258
44259
44260
44261
44262
44263
44264
44265
44266
44267
44268
44269
44270
44271
44272
44273
44274
44275
44276
44277
44278
44279
44280
44281
44282
44283
44284
44285
44286
44287
44288
44289
44290
44291
44292
44293
44294
44295
44296
44297
44298
44299
44300
44301
44302
44303
44304
44305
44306
44307
44308
44309
44310
44311
44312
44313
44314
44315
44316
44317
44318
44319
44320
44321
44322
44323
44324
44325
44326
44327
44328
44329
44330
44331
44332
44333
44334
44335
44336
44337
44338
44339
44340
44341
44342
44343
44344
44345
44346
44347
44348
44349
44350
44351
44352
44353
44354
44355
44356
44357
44358
44359
44360
44361
44362
44363
44364
44365
44366
44367
44368
44369
44370
44371
44372
44373
44374
44375
44376
44377
44378
44379
44380
44381
44382
44383
44384
44385
44386
44387
44388
44389
44390
44391
44392
44393
44394
44395
44396
44397
44398
44399
44400
44401
44402
44403
44404
44405
44406
44407
44408
44409
44410
44411
44412
44413
44414
44415
44416
44417
44418
44419
44420
44421
44422
44423
44424
44425
44426
44427
44428
44429
44430
44431
44432
44433
44434
44435
44436
44437
44438
44439
44440
44441
44442
44443
44444
44445
44446
44447
44448
44449
44450
44451
44452
44453
44454
44455
44456
44457
44458
44459
44460
44461
44462
44463
44464
44465
44466
44467
44468
44469
44470
44471
44472
44473
44474
44475
44476
44477
44478
44479
44480
44481
44482
44483
44484
44485
44486
44487
44488
44489
44490
44491
44492
44493
44494
44495
44496
44497
44498
44499
44500
44501
44502
44503
44504
44505
44506
44507
44508
44509
44510
44511
44512
44513
44514
44515
44516
44517
44518
44519
44520
44521
44522
44523
44524
44525
44526
44527
44528
44529
44530
44531
44532
44533
44534
44535
44536
44537
44538
44539
44540
44541
44542
44543
44544
44545
44546
44547
44548
44549
44550
44551
44552
44553
44554
44555
44556
44557
44558
44559
44560
44561
44562
44563
44564
44565
44566
44567
44568
44569
44570
44571
44572
44573
44574
44575
44576
44577
44578
44579
44580
44581
44582
44583
44584
44585
44586
44587
44588
44589
44590
44591
44592
44593
44594
44595
44596
44597
44598
44599
44600
44601
44602
44603
44604
44605
44606
44607
44608
44609
44610
44611
44612
44613
44614
44615
44616
44617
44618
44619
44620
44621
44622
44623
44624
44625
44626
44627
44628
44629
44630
44631
44632
44633
44634
44635
44636
44637
44638
44639
44640
44641
44642
44643
44644
44645
44646
44647
44648
44649
44650
44651
44652
44653
44654
44655
44656
44657
44658
44659
44660
44661
44662
44663
44664
44665
44666
44667
44668
44669
44670
44671
44672
44673
44674
44675
44676
44677
44678
44679
44680
44681
44682
44683
44684
44685
44686
44687
44688
44689
44690
44691
44692
44693
44694
44695
44696
44697
44698
44699
44700
44701
44702
44703
44704
44705
44706
44707
44708
44709
44710
44711
44712
44713
44714
44715
44716
44717
44718
44719
44720
44721
44722
44723
44724
44725
44726
44727
44728
44729
44730
44731
44732
44733
44734
44735
44736
44737
44738
44739
44740
44741
44742
44743
44744
44745
44746
44747
44748
44749
44750
44751
44752
44753
44754
44755
44756
44757
44758
44759
44760
44761
44762
44763
44764
44765
44766
44767
44768
44769
44770
44771
44772
44773
44774
44775
44776
44777
44778
44779
44780
44781
44782
44783
44784
44785
44786
44787
44788
44789
44790
44791
44792
44793
44794
44795
44796
44797
44798
44799
44800
44801
44802
44803
44804
44805
44806
44807
44808
44809
44810
44811
44812
44813
44814
44815
44816
44817
44818
44819
44820
44821
44822
44823
44824
44825
44826
44827
44828
44829
44830
44831
44832
44833
44834
44835
44836
44837
44838
44839
44840
44841
44842
44843
44844
44845
44846
44847
44848
44849
44850
44851
44852
44853
44854
44855
44856
44857
44858
44859
44860
44861
44862
44863
44864
44865
44866
44867
44868
44869
44870
44871
44872
44873
44874
44875
44876
44877
44878
44879
44880
44881
44882
44883
44884
44885
44886
44887
44888
44889
44890
44891
44892
44893
44894
44895
44896
44897
44898
44899
44900
44901
44902
44903
44904
44905
44906
44907
44908
44909
44910
44911
44912
44913
44914
44915
44916
44917
44918
44919
44920
44921
44922
44923
44924
44925
44926
44927
44928
44929
44930
44931
44932
44933
44934
44935
44936
44937
44938
44939
44940
44941
44942
44943
44944
44945
44946
44947
44948
44949
44950
44951
44952
44953
44954
44955
44956
44957
44958
44959
44960
44961
44962
44963
44964
44965
44966
44967
44968
44969
44970
44971
44972
44973
44974
44975
44976
44977
44978
44979
44980
44981
44982
44983
44984
44985
44986
44987
44988
44989
44990
44991
44992
44993
44994
44995
44996
44997
44998
44999
45000
45001
45002
45003
45004
45005
45006
45007
45008
45009
45010
45011
45012
45013
45014
45015
45016
45017
45018
45019
45020
45021
45022
45023
45024
45025
45026
45027
45028
45029
45030
45031
45032
45033
45034
45035
45036
45037
45038
45039
45040
45041
45042
45043
45044
45045
45046
45047
45048
45049
45050
45051
45052
45053
45054
45055
45056
45057
45058
45059
45060
45061
45062
45063
45064
45065
45066
45067
45068
45069
45070
45071
45072
45073
45074
45075
45076
45077
45078
45079
45080
45081
45082
45083
45084
45085
45086
45087
45088
45089
45090
45091
45092
45093
45094
45095
45096
45097
45098
45099
45100
45101
45102
45103
45104
45105
45106
45107
45108
45109
45110
45111
45112
45113
45114
45115
45116
45117
45118
45119
45120
45121
45122
45123
45124
45125
45126
45127
45128
45129
45130
45131
45132
45133
45134
45135
45136
45137
45138
45139
45140
45141
45142
45143
45144
45145
45146
45147
45148
45149
45150
45151
45152
45153
45154
45155
45156
45157
45158
45159
45160
45161
45162
45163
45164
45165
45166
45167
45168
45169
45170
45171
45172
45173
45174
45175
45176
45177
45178
45179
45180
45181
45182
45183
45184
45185
45186
45187
45188
45189
45190
45191
45192
45193
45194
45195
45196
45197
45198
45199
45200
45201
45202
45203
45204
45205
45206
45207
45208
45209
45210
45211
45212
45213
45214
45215
45216
45217
45218
45219
45220
45221
45222
45223
45224
45225
45226
45227
45228
45229
45230
45231
45232
45233
45234
45235
45236
45237
45238
45239
45240
45241
45242
45243
45244
45245
45246
45247
45248
45249
45250
45251
45252
45253
45254
45255
45256
45257
45258
45259
45260
45261
45262
45263
45264
45265
45266
45267
45268
45269
45270
45271
45272
45273
45274
45275
45276
45277
45278
45279
45280
45281
45282
45283
45284
45285
45286
45287
45288
45289
45290
45291
45292
45293
45294
45295
45296
45297
45298
45299
45300
45301
45302
45303
45304
45305
45306
45307
45308
45309
45310
45311
45312
45313
45314
45315
45316
45317
45318
45319
45320
45321
45322
45323
45324
45325
45326
45327
45328
45329
45330
45331
45332
45333
45334
45335
45336
45337
45338
45339
45340
45341
45342
45343
45344
45345
45346
45347
45348
45349
45350
45351
45352
45353
45354
45355
45356
45357
45358
45359
45360
45361
45362
45363
45364
45365
45366
45367
45368
45369
45370
45371
45372
45373
45374
45375
45376
45377
45378
45379
45380
45381
45382
45383
45384
45385
45386
45387
45388
45389
45390
45391
45392
45393
45394
45395
45396
45397
45398
45399
45400
45401
45402
45403
45404
45405
45406
45407
45408
45409
45410
45411
45412
45413
45414
45415
45416
45417
45418
45419
45420
45421
45422
45423
45424
45425
45426
45427
45428
45429
45430
45431
45432
45433
45434
45435
45436
45437
45438
45439
45440
45441
45442
45443
45444
45445
45446
45447
45448
45449
45450
45451
45452
45453
45454
45455
45456
45457
45458
45459
45460
45461
45462
45463
45464
45465
45466
45467
45468
45469
45470
45471
45472
45473
45474
45475
45476
45477
45478
45479
45480
45481
45482
45483
45484
45485
45486
45487
45488
45489
45490
45491
45492
45493
45494
45495
45496
45497
45498
45499
45500
45501
45502
45503
45504
45505
45506
45507
45508
45509
45510
45511
45512
45513
45514
45515
45516
45517
45518
45519
45520
45521
45522
45523
45524
45525
45526
45527
45528
45529
45530
45531
45532
45533
45534
45535
45536
45537
45538
45539
45540
45541
45542
45543
45544
45545
45546
45547
45548
45549
45550
45551
45552
45553
45554
45555
45556
45557
45558
45559
45560
45561
45562
45563
45564
45565
45566
45567
45568
45569
45570
45571
45572
45573
45574
45575
45576
45577
45578
45579
45580
45581
45582
45583
45584
45585
45586
45587
45588
45589
45590
45591
45592
45593
45594
45595
45596
45597
45598
45599
45600
45601
45602
45603
45604
45605
45606
45607
45608
45609
45610
45611
45612
45613
45614
45615
45616
45617
45618
45619
45620
45621
45622
45623
45624
45625
45626
45627
45628
45629
45630
45631
45632
45633
45634
45635
45636
45637
45638
45639
45640
45641
45642
45643
45644
45645
45646
45647
45648
45649
45650
45651
45652
45653
45654
45655
45656
45657
45658
45659
45660
45661
45662
45663
45664
45665
45666
45667
45668
45669
45670
45671
45672
45673
45674
45675
45676
45677
45678
45679
45680
45681
45682
45683
45684
45685
45686
45687
45688
45689
45690
45691
45692
45693
45694
45695
45696
45697
45698
45699
45700
45701
45702
45703
45704
45705
45706
45707
45708
45709
45710
45711
45712
45713
45714
45715
45716
45717
45718
45719
45720
45721
45722
45723
45724
45725
45726
45727
45728
45729
45730
45731
45732
45733
45734
45735
45736
45737
45738
45739
45740
45741
45742
45743
45744
45745
45746
45747
45748
45749
45750
45751
45752
45753
45754
45755
45756
45757
45758
45759
45760
45761
45762
45763
45764
45765
45766
45767
45768
45769
45770
45771
45772
45773
45774
45775
45776
45777
45778
45779
45780
45781
45782
45783
45784
45785
45786
45787
45788
45789
45790
45791
45792
45793
45794
45795
45796
45797
45798
45799
45800
45801
45802
45803
45804
45805
45806
45807
45808
45809
45810
45811
45812
45813
45814
45815
45816
45817
45818
45819
45820
45821
45822
45823
45824
45825
45826
45827
45828
45829
45830
45831
45832
45833
45834
45835
45836
45837
45838
45839
45840
45841
45842
45843
45844
45845
45846
45847
45848
45849
45850
45851
45852
45853
45854
45855
45856
45857
45858
45859
45860
45861
45862
45863
45864
45865
45866
45867
45868
45869
45870
45871
45872
45873
45874
45875
45876
45877
45878
45879
45880
45881
45882
45883
45884
45885
45886
45887
45888
45889
45890
45891
45892
45893
45894
45895
45896
45897
45898
45899
45900
45901
45902
45903
45904
45905
45906
45907
45908
45909
45910
45911
45912
45913
45914
45915
45916
45917
45918
45919
45920
45921
45922
45923
45924
45925
45926
45927
45928
45929
45930
45931
45932
45933
45934
45935
45936
45937
45938
45939
45940
45941
45942
45943
45944
45945
45946
45947
45948
45949
45950
45951
45952
45953
45954
45955
45956
45957
45958
45959
45960
45961
45962
45963
45964
45965
45966
45967
45968
45969
45970
45971
45972
45973
45974
45975
45976
45977
45978
45979
45980
45981
45982
45983
45984
45985
45986
45987
45988
45989
45990
45991
45992
45993
45994
45995
45996
45997
45998
45999
46000
46001
46002
46003
46004
46005
46006
46007
46008
46009
46010
46011
46012
46013
46014
46015
46016
46017
46018
46019
46020
46021
46022
46023
46024
46025
46026
46027
46028
46029
46030
46031
46032
46033
46034
46035
46036
46037
46038
46039
46040
46041
46042
46043
46044
46045
46046
46047
46048
46049
46050
46051
46052
46053
46054
46055
46056
46057
46058
46059
46060
46061
46062
46063
46064
46065
46066
46067
46068
46069
46070
46071
46072
46073
46074
46075
46076
46077
46078
46079
46080
46081
46082
46083
46084
46085
46086
46087
46088
46089
46090
46091
46092
46093
46094
46095
46096
46097
46098
46099
46100
46101
46102
46103
46104
46105
46106
46107
46108
46109
46110
46111
46112
46113
46114
46115
46116
46117
46118
46119
46120
46121
46122
46123
46124
46125
46126
46127
46128
46129
46130
46131
46132
46133
46134
46135
46136
46137
46138
46139
46140
46141
46142
46143
46144
46145
46146
46147
46148
46149
46150
46151
46152
46153
46154
46155
46156
46157
46158
46159
46160
46161
46162
46163
46164
46165
46166
46167
46168
46169
46170
46171
46172
46173
46174
46175
46176
46177
46178
46179
46180
46181
46182
46183
46184
46185
46186
46187
46188
46189
46190
46191
46192
46193
46194
46195
46196
46197
46198
46199
46200
46201
46202
46203
46204
46205
46206
46207
46208
46209
46210
46211
46212
46213
46214
46215
46216
46217
46218
46219
46220
46221
46222
46223
46224
46225
46226
46227
46228
46229
46230
46231
46232
46233
46234
46235
46236
46237
46238
46239
46240
46241
46242
46243
46244
46245
46246
46247
46248
46249
46250
46251
46252
46253
46254
46255
46256
46257
46258
46259
46260
46261
46262
46263
46264
46265
46266
46267
46268
46269
46270
46271
46272
46273
46274
46275
46276
46277
46278
46279
46280
46281
46282
46283
46284
46285
46286
46287
46288
46289
46290
46291
46292
46293
46294
46295
46296
46297
46298
46299
46300
46301
46302
46303
46304
46305
46306
46307
46308
46309
46310
46311
46312
46313
46314
46315
46316
46317
46318
46319
46320
46321
46322
46323
46324
46325
46326
46327
46328
46329
46330
46331
46332
46333
46334
46335
46336
46337
46338
46339
46340
46341
46342
46343
46344
46345
46346
46347
46348
46349
46350
46351
46352
46353
46354
46355
46356
46357
46358
46359
46360
46361
46362
46363
46364
46365
46366
46367
46368
46369
46370
46371
46372
46373
46374
46375
46376
46377
46378
46379
46380
46381
46382
46383
46384
46385
46386
46387
46388
46389
46390
46391
46392
46393
46394
46395
46396
46397
46398
46399
46400
46401
46402
46403
46404
46405
46406
46407
46408
46409
46410
46411
46412
46413
46414
46415
46416
46417
46418
46419
46420
46421
46422
46423
46424
46425
46426
46427
46428
46429
46430
46431
46432
46433
46434
46435
46436
46437
46438
46439
46440
46441
46442
46443
46444
46445
46446
46447
46448
46449
46450
46451
46452
46453
46454
46455
46456
46457
46458
46459
46460
46461
46462
46463
46464
46465
46466
46467
46468
46469
46470
46471
46472
46473
46474
46475
46476
46477
46478
46479
46480
46481
46482
46483
46484
46485
46486
46487
46488
46489
46490
46491
46492
46493
46494
46495
46496
46497
46498
46499
46500
46501
46502
46503
46504
46505
46506
46507
46508
46509
46510
46511
46512
46513
46514
46515
46516
46517
46518
46519
46520
46521
46522
46523
46524
46525
46526
46527
46528
46529
46530
46531
46532
46533
46534
46535
46536
46537
46538
46539
46540
46541
46542
46543
46544
46545
46546
46547
46548
46549
46550
46551
46552
46553
46554
46555
46556
46557
46558
46559
46560
46561
46562
46563
46564
46565
46566
46567
46568
46569
46570
46571
46572
46573
46574
46575
46576
46577
46578
46579
46580
46581
46582
46583
46584
46585
46586
46587
46588
46589
46590
46591
46592
46593
46594
46595
46596
46597
46598
46599
46600
46601
46602
46603
46604
46605
46606
46607
46608
46609
46610
46611
46612
46613
46614
46615
46616
46617
46618
46619
46620
46621
46622
46623
46624
46625
46626
46627
46628
46629
46630
46631
46632
46633
46634
46635
46636
46637
46638
46639
46640
46641
46642
46643
46644
46645
46646
46647
46648
46649
46650
46651
46652
46653
46654
46655
46656
46657
46658
46659
46660
46661
46662
46663
46664
46665
46666
46667
46668
46669
46670
46671
46672
46673
46674
46675
46676
46677
46678
46679
46680
46681
46682
46683
46684
46685
46686
46687
46688
46689
46690
46691
46692
46693
46694
46695
46696
46697
46698
46699
46700
46701
46702
46703
46704
46705
46706
46707
46708
46709
46710
46711
46712
46713
46714
46715
46716
46717
46718
46719
46720
46721
46722
46723
46724
46725
46726
46727
46728
46729
46730
46731
46732
46733
46734
46735
46736
46737
46738
46739
46740
46741
46742
46743
46744
46745
46746
46747
46748
46749
46750
46751
46752
46753
46754
46755
46756
46757
46758
46759
46760
46761
46762
46763
46764
46765
46766
46767
46768
46769
46770
46771
46772
46773
46774
46775
46776
46777
46778
46779
46780
46781
46782
46783
46784
46785
46786
46787
46788
46789
46790
46791
46792
46793
46794
46795
46796
46797
46798
46799
46800
46801
46802
46803
46804
46805
46806
46807
46808
46809
46810
46811
46812
46813
46814
46815
46816
46817
46818
46819
46820
46821
46822
46823
46824
46825
46826
46827
46828
46829
46830
46831
46832
46833
46834
46835
46836
46837
46838
46839
46840
46841
46842
46843
46844
46845
46846
46847
46848
46849
46850
46851
46852
46853
46854
46855
46856
46857
46858
46859
46860
46861
46862
46863
46864
46865
46866
46867
46868
46869
46870
46871
46872
46873
46874
46875
46876
46877
46878
46879
46880
46881
46882
46883
46884
46885
46886
46887
46888
46889
46890
46891
46892
46893
46894
46895
46896
46897
46898
46899
46900
46901
46902
46903
46904
46905
46906
46907
46908
46909
46910
46911
46912
46913
46914
46915
46916
46917
46918
46919
46920
46921
46922
46923
46924
46925
46926
46927
46928
46929
46930
46931
46932
46933
46934
46935
46936
46937
46938
46939
46940
46941
46942
46943
46944
46945
46946
46947
46948
46949
46950
46951
46952
46953
46954
46955
46956
46957
46958
46959
46960
46961
46962
46963
46964
46965
46966
46967
46968
46969
46970
46971
46972
46973
46974
46975
46976
46977
46978
46979
46980
46981
46982
46983
46984
46985
46986
46987
46988
46989
46990
46991
46992
46993
46994
46995
46996
46997
46998
46999
47000
47001
47002
47003
47004
47005
47006
47007
47008
47009
47010
47011
47012
47013
47014
47015
47016
47017
47018
47019
47020
47021
47022
47023
47024
47025
47026
47027
47028
47029
47030
47031
47032
47033
47034
47035
47036
47037
47038
47039
47040
47041
47042
47043
47044
47045
47046
47047
47048
47049
47050
47051
47052
47053
47054
47055
47056
47057
47058
47059
47060
47061
47062
47063
47064
47065
47066
47067
47068
47069
47070
47071
47072
47073
47074
47075
47076
47077
47078
47079
47080
47081
47082
47083
47084
47085
47086
47087
47088
47089
47090
47091
47092
47093
47094
47095
47096
47097
47098
47099
47100
47101
47102
47103
47104
47105
47106
47107
47108
47109
47110
47111
47112
47113
47114
47115
47116
47117
47118
47119
47120
47121
47122
47123
47124
47125
47126
47127
47128
47129
47130
47131
47132
47133
47134
47135
47136
47137
47138
47139
47140
47141
47142
47143
47144
47145
47146
47147
47148
47149
47150
47151
47152
47153
47154
47155
47156
47157
47158
47159
47160
47161
47162
47163
47164
47165
47166
47167
47168
47169
47170
47171
47172
47173
47174
47175
47176
47177
47178
47179
47180
47181
47182
47183
47184
47185
47186
47187
47188
47189
47190
47191
47192
47193
47194
47195
47196
47197
47198
47199
47200
47201
47202
47203
47204
47205
47206
47207
47208
47209
47210
47211
47212
47213
47214
47215
47216
47217
47218
47219
47220
47221
47222
47223
47224
47225
47226
47227
47228
47229
47230
47231
47232
47233
47234
47235
47236
47237
47238
47239
47240
47241
47242
47243
47244
47245
47246
47247
47248
47249
47250
47251
47252
47253
47254
47255
47256
47257
47258
47259
47260
47261
47262
47263
47264
47265
47266
47267
47268
47269
47270
47271
47272
47273
47274
47275
47276
47277
47278
47279
47280
47281
47282
47283
47284
47285
47286
47287
47288
47289
47290
47291
47292
47293
47294
47295
47296
47297
47298
47299
47300
47301
47302
47303
47304
47305
47306
47307
47308
47309
47310
47311
47312
47313
47314
47315
47316
47317
47318
47319
47320
47321
47322
47323
47324
47325
47326
47327
47328
47329
47330
47331
47332
47333
47334
47335
47336
47337
47338
47339
47340
47341
47342
47343
47344
47345
47346
47347
47348
47349
47350
47351
47352
47353
47354
47355
47356
47357
47358
47359
47360
47361
47362
47363
47364
47365
47366
47367
47368
47369
47370
47371
47372
47373
47374
47375
47376
47377
47378
47379
47380
47381
47382
47383
47384
47385
47386
47387
47388
47389
47390
47391
47392
47393
47394
47395
47396
47397
47398
47399
47400
47401
47402
47403
47404
47405
47406
47407
47408
47409
47410
47411
47412
47413
47414
47415
47416
47417
47418
47419
47420
47421
47422
47423
47424
47425
47426
47427
47428
47429
47430
47431
47432
47433
47434
47435
47436
47437
47438
47439
47440
47441
47442
47443
47444
47445
47446
47447
47448
47449
47450
47451
47452
47453
47454
47455
47456
47457
47458
47459
47460
47461
47462
47463
47464
47465
47466
47467
47468
47469
47470
47471
47472
47473
47474
47475
47476
47477
47478
47479
47480
47481
47482
47483
47484
47485
47486
47487
47488
47489
47490
47491
47492
47493
47494
47495
47496
47497
47498
47499
47500
47501
47502
47503
47504
47505
47506
47507
47508
47509
47510
47511
47512
47513
47514
47515
47516
47517
47518
47519
47520
47521
47522
47523
47524
47525
47526
47527
47528
47529
47530
47531
47532
47533
47534
47535
47536
47537
47538
47539
47540
47541
47542
47543
47544
47545
47546
47547
47548
47549
47550
47551
47552
47553
47554
47555
47556
47557
47558
47559
47560
47561
47562
47563
47564
47565
47566
47567
47568
47569
47570
47571
47572
47573
47574
47575
47576
47577
47578
47579
47580
47581
47582
47583
47584
47585
47586
47587
47588
47589
47590
47591
47592
47593
47594
47595
47596
47597
47598
47599
47600
47601
47602
47603
47604
47605
47606
47607
47608
47609
47610
47611
47612
47613
47614
47615
47616
47617
47618
47619
47620
47621
47622
47623
47624
47625
47626
47627
47628
47629
47630
47631
47632
47633
47634
47635
47636
47637
47638
47639
47640
47641
47642
47643
47644
47645
47646
47647
47648
47649
47650
47651
47652
47653
47654
47655
47656
47657
47658
47659
47660
47661
47662
47663
47664
47665
47666
47667
47668
47669
47670
47671
47672
47673
47674
47675
47676
47677
47678
47679
47680
47681
47682
47683
47684
47685
47686
47687
47688
47689
47690
47691
47692
47693
47694
47695
47696
47697
47698
47699
47700
47701
47702
47703
47704
47705
47706
47707
47708
47709
47710
47711
47712
47713
47714
47715
47716
47717
47718
47719
47720
47721
47722
47723
47724
47725
47726
47727
47728
47729
47730
47731
47732
47733
47734
47735
47736
47737
47738
47739
47740
47741
47742
47743
47744
47745
47746
47747
47748
47749
47750
47751
47752
47753
47754
47755
47756
47757
47758
47759
47760
47761
47762
47763
47764
47765
47766
47767
47768
47769
47770
47771
47772
47773
47774
47775
47776
47777
47778
47779
47780
47781
47782
47783
47784
47785
47786
47787
47788
47789
47790
47791
47792
47793
47794
47795
47796
47797
47798
47799
47800
47801
47802
47803
47804
47805
47806
47807
47808
47809
47810
47811
47812
47813
47814
47815
47816
47817
47818
47819
47820
47821
47822
47823
47824
47825
47826
47827
47828
47829
47830
47831
47832
47833
47834
47835
47836
47837
47838
47839
47840
47841
47842
47843
47844
47845
47846
47847
47848
47849
47850
47851
47852
47853
47854
47855
47856
47857
47858
47859
47860
47861
47862
47863
47864
47865
47866
47867
47868
47869
47870
47871
47872
47873
47874
47875
47876
47877
47878
47879
47880
47881
47882
47883
47884
47885
47886
47887
47888
47889
47890
47891
47892
47893
47894
47895
47896
47897
47898
47899
47900
47901
47902
47903
47904
47905
47906
47907
47908
47909
47910
47911
47912
47913
47914
47915
47916
47917
47918
47919
47920
47921
47922
47923
47924
47925
47926
47927
47928
47929
47930
47931
47932
47933
47934
47935
47936
47937
47938
47939
47940
47941
47942
47943
47944
47945
47946
47947
47948
47949
47950
47951
47952
47953
47954
47955
47956
47957
47958
47959
47960
47961
47962
47963
47964
47965
47966
47967
47968
47969
47970
47971
47972
47973
47974
47975
47976
47977
47978
47979
47980
47981
47982
47983
47984
47985
47986
47987
47988
47989
47990
47991
47992
47993
47994
47995
47996
47997
47998
47999
48000
48001
48002
48003
48004
48005
48006
48007
48008
48009
48010
48011
48012
48013
48014
48015
48016
48017
48018
48019
48020
48021
48022
48023
48024
48025
48026
48027
48028
48029
48030
48031
48032
48033
48034
48035
48036
48037
48038
48039
48040
48041
48042
48043
48044
48045
48046
48047
48048
48049
48050
48051
48052
48053
48054
48055
48056
48057
48058
48059
48060
48061
48062
48063
48064
48065
48066
48067
48068
48069
48070
48071
48072
48073
48074
48075
48076
48077
48078
48079
48080
48081
48082
48083
48084
48085
48086
48087
48088
48089
48090
48091
48092
48093
48094
48095
48096
48097
48098
48099
48100
48101
48102
48103
48104
48105
48106
48107
48108
48109
48110
48111
48112
48113
48114
48115
48116
48117
48118
48119
48120
48121
48122
48123
48124
48125
48126
48127
48128
48129
48130
48131
48132
48133
48134
48135
48136
48137
48138
48139
48140
48141
48142
48143
48144
48145
48146
48147
48148
48149
48150
48151
48152
48153
48154
48155
48156
48157
48158
48159
48160
48161
48162
48163
48164
48165
48166
48167
48168
48169
48170
48171
48172
48173
48174
48175
48176
48177
48178
48179
48180
48181
48182
48183
48184
48185
48186
48187
48188
48189
48190
48191
48192
48193
48194
48195
48196
48197
48198
48199
48200
48201
48202
48203
48204
48205
48206
48207
48208
48209
48210
48211
48212
48213
48214
48215
48216
48217
48218
48219
48220
48221
48222
48223
48224
48225
48226
48227
48228
48229
48230
48231
48232
48233
48234
48235
48236
48237
48238
48239
48240
48241
48242
48243
48244
48245
48246
48247
48248
48249
48250
48251
48252
48253
48254
48255
48256
48257
48258
48259
48260
48261
48262
48263
48264
48265
48266
48267
48268
48269
48270
48271
48272
48273
48274
48275
48276
48277
48278
48279
48280
48281
48282
48283
48284
48285
48286
48287
48288
48289
48290
48291
48292
48293
48294
48295
48296
48297
48298
48299
48300
48301
48302
48303
48304
48305
48306
48307
48308
48309
48310
48311
48312
48313
48314
48315
48316
48317
48318
48319
48320
48321
48322
48323
48324
48325
48326
48327
48328
48329
48330
48331
48332
48333
48334
48335
48336
48337
48338
48339
48340
48341
48342
48343
48344
48345
48346
48347
48348
48349
48350
48351
48352
48353
48354
48355
48356
48357
48358
48359
48360
48361
48362
48363
48364
48365
48366
48367
48368
48369
48370
48371
48372
48373
48374
48375
48376
48377
48378
48379
48380
48381
48382
48383
48384
48385
48386
48387
48388
48389
48390
48391
48392
48393
48394
48395
48396
48397
48398
48399
48400
48401
48402
48403
48404
48405
48406
48407
48408
48409
48410
48411
48412
48413
48414
48415
48416
48417
48418
48419
48420
48421
48422
48423
48424
48425
48426
48427
48428
48429
48430
48431
48432
48433
48434
48435
48436
48437
48438
48439
48440
48441
48442
48443
48444
48445
48446
48447
48448
48449
48450
48451
48452
48453
48454
48455
48456
48457
48458
48459
48460
48461
48462
48463
48464
48465
48466
48467
48468
48469
48470
48471
48472
48473
48474
48475
48476
48477
48478
48479
48480
48481
48482
48483
48484
48485
48486
48487
48488
48489
48490
48491
48492
48493
48494
48495
48496
48497
48498
48499
48500
48501
48502
48503
48504
48505
48506
48507
48508
48509
48510
48511
48512
48513
48514
48515
48516
48517
48518
48519
48520
48521
48522
48523
48524
48525
48526
48527
48528
48529
48530
48531
48532
48533
48534
48535
48536
48537
48538
48539
48540
48541
48542
48543
48544
48545
48546
48547
48548
48549
48550
48551
48552
48553
48554
48555
48556
48557
48558
48559
48560
48561
48562
48563
48564
48565
48566
48567
48568
48569
48570
48571
48572
48573
48574
48575
48576
48577
48578
48579
48580
48581
48582
48583
48584
48585
48586
48587
48588
48589
48590
48591
48592
48593
48594
48595
48596
48597
48598
48599
48600
48601
48602
48603
48604
48605
48606
48607
48608
48609
48610
48611
48612
48613
48614
48615
48616
48617
48618
48619
48620
48621
48622
48623
48624
48625
48626
48627
48628
48629
48630
48631
48632
48633
48634
48635
48636
48637
48638
48639
48640
48641
48642
48643
48644
48645
48646
48647
48648
48649
48650
48651
48652
48653
48654
48655
48656
48657
48658
48659
48660
48661
48662
48663
48664
48665
48666
48667
48668
48669
48670
48671
48672
48673
48674
48675
48676
48677
48678
48679
48680
48681
48682
48683
48684
48685
48686
48687
48688
48689
48690
48691
48692
48693
48694
48695
48696
48697
48698
48699
48700
48701
48702
48703
48704
48705
48706
48707
48708
48709
48710
48711
48712
48713
48714
48715
48716
48717
48718
48719
48720
48721
48722
48723
48724
48725
48726
48727
48728
48729
48730
48731
48732
48733
48734
48735
48736
48737
48738
48739
48740
48741
48742
48743
48744
48745
48746
48747
48748
48749
48750
48751
48752
48753
48754
48755
48756
48757
48758
48759
48760
48761
48762
48763
48764
48765
48766
48767
48768
48769
48770
48771
48772
48773
48774
48775
48776
48777
48778
48779
48780
48781
48782
48783
48784
48785
48786
48787
48788
48789
48790
48791
48792
48793
48794
48795
48796
48797
48798
48799
48800
48801
48802
48803
48804
48805
48806
48807
48808
48809
48810
48811
48812
48813
48814
48815
48816
48817
48818
48819
48820
48821
48822
48823
48824
48825
48826
48827
48828
48829
48830
48831
48832
48833
48834
48835
48836
48837
48838
48839
48840
48841
48842
48843
48844
48845
48846
48847
48848
48849
48850
48851
48852
48853
48854
48855
48856
48857
48858
48859
48860
48861
48862
48863
48864
48865
48866
48867
48868
48869
48870
48871
48872
48873
48874
48875
48876
48877
48878
48879
48880
48881
48882
48883
48884
48885
48886
48887
48888
48889
48890
48891
48892
48893
48894
48895
48896
48897
48898
48899
48900
48901
48902
48903
48904
48905
48906
48907
48908
48909
48910
48911
48912
48913
48914
48915
48916
48917
48918
48919
48920
48921
48922
48923
48924
48925
48926
48927
48928
48929
48930
48931
48932
48933
48934
48935
48936
48937
48938
48939
48940
48941
48942
48943
48944
48945
48946
48947
48948
48949
48950
48951
48952
48953
48954
48955
48956
48957
48958
48959
48960
48961
48962
48963
48964
48965
48966
48967
48968
48969
48970
48971
48972
48973
48974
48975
48976
48977
48978
48979
48980
48981
48982
48983
48984
48985
48986
48987
48988
48989
48990
48991
48992
48993
48994
48995
48996
48997
48998
48999
49000
49001
49002
49003
49004
49005
49006
49007
49008
49009
49010
49011
49012
49013
49014
49015
49016
49017
49018
49019
49020
49021
49022
49023
49024
49025
49026
49027
49028
49029
49030
49031
49032
49033
49034
49035
49036
49037
49038
49039
49040
49041
49042
49043
49044
49045
49046
49047
49048
49049
49050
49051
49052
49053
49054
49055
49056
49057
49058
49059
49060
49061
49062
49063
49064
49065
49066
49067
49068
49069
49070
49071
49072
49073
49074
49075
49076
49077
49078
49079
49080
49081
49082
49083
49084
49085
49086
49087
49088
49089
49090
49091
49092
49093
49094
49095
49096
49097
49098
49099
49100
49101
49102
49103
49104
49105
49106
49107
49108
49109
49110
49111
49112
49113
49114
49115
49116
49117
49118
49119
49120
49121
49122
49123
49124
49125
49126
49127
49128
49129
49130
49131
49132
49133
49134
49135
49136
49137
49138
49139
49140
49141
49142
49143
49144
49145
49146
49147
49148
49149
49150
49151
49152
49153
49154
49155
49156
49157
49158
49159
49160
49161
49162
49163
49164
49165
49166
49167
49168
49169
49170
49171
49172
49173
49174
49175
49176
49177
49178
49179
49180
49181
49182
49183
49184
49185
49186
49187
49188
49189
49190
49191
49192
49193
49194
49195
49196
49197
49198
49199
49200
49201
49202
49203
49204
49205
49206
49207
49208
49209
49210
49211
49212
49213
49214
49215
49216
49217
49218
49219
49220
49221
49222
49223
49224
49225
49226
49227
49228
49229
49230
49231
49232
49233
49234
49235
49236
49237
49238
49239
49240
49241
49242
49243
49244
49245
49246
49247
49248
49249
49250
49251
49252
49253
49254
49255
49256
49257
49258
49259
49260
49261
49262
49263
49264
49265
49266
49267
49268
49269
49270
49271
49272
49273
49274
49275
49276
49277
49278
49279
49280
49281
49282
49283
49284
49285
49286
49287
49288
49289
49290
49291
49292
49293
49294
49295
49296
49297
49298
49299
49300
49301
49302
49303
49304
49305
49306
49307
49308
49309
49310
49311
49312
49313
49314
49315
49316
49317
49318
49319
49320
49321
49322
49323
49324
49325
49326
49327
49328
49329
49330
49331
49332
49333
49334
49335
49336
49337
49338
49339
49340
49341
49342
49343
49344
49345
49346
49347
49348
49349
49350
49351
49352
49353
49354
49355
49356
49357
49358
49359
49360
49361
49362
49363
49364
49365
49366
49367
49368
49369
49370
49371
49372
49373
49374
49375
49376
49377
49378
49379
49380
49381
49382
49383
49384
49385
49386
49387
49388
49389
49390
49391
49392
49393
49394
49395
49396
49397
49398
49399
49400
49401
49402
49403
49404
49405
49406
49407
49408
49409
49410
49411
49412
49413
49414
49415
49416
49417
49418
49419
49420
49421
49422
49423
49424
49425
49426
49427
49428
49429
49430
49431
49432
49433
49434
49435
49436
49437
49438
49439
49440
49441
49442
49443
49444
49445
49446
49447
49448
49449
49450
49451
49452
49453
49454
49455
49456
49457
49458
49459
49460
49461
49462
49463
49464
49465
49466
49467
49468
49469
49470
49471
49472
49473
49474
49475
49476
49477
49478
49479
49480
49481
49482
49483
49484
49485
49486
49487
49488
49489
49490
49491
49492
49493
49494
49495
49496
49497
49498
49499
49500
49501
49502
49503
49504
49505
49506
49507
49508
49509
49510
49511
49512
49513
49514
49515
49516
49517
49518
49519
49520
49521
49522
49523
49524
49525
49526
49527
49528
49529
49530
49531
49532
49533
49534
49535
49536
49537
49538
49539
49540
49541
49542
49543
49544
49545
49546
49547
49548
49549
49550
49551
49552
49553
49554
49555
49556
49557
49558
49559
49560
49561
49562
49563
49564
49565
49566
49567
49568
49569
49570
49571
49572
49573
49574
49575
49576
49577
49578
49579
49580
49581
49582
49583
49584
49585
49586
49587
49588
49589
49590
49591
49592
49593
49594
49595
49596
49597
49598
49599
49600
49601
49602
49603
49604
49605
49606
49607
49608
49609
49610
49611
49612
49613
49614
49615
49616
49617
49618
49619
49620
49621
49622
49623
49624
49625
49626
49627
49628
49629
49630
49631
49632
49633
49634
49635
49636
49637
49638
49639
49640
49641
49642
49643
49644
49645
49646
49647
49648
49649
49650
49651
49652
49653
49654
49655
49656
49657
49658
49659
49660
49661
49662
49663
49664
49665
49666
49667
49668
49669
49670
49671
49672
49673
49674
49675
49676
49677
49678
49679
49680
49681
49682
49683
49684
49685
49686
49687
49688
49689
49690
49691
49692
49693
49694
49695
49696
49697
49698
49699
49700
49701
49702
49703
49704
49705
49706
49707
49708
49709
49710
49711
49712
49713
49714
49715
49716
49717
49718
49719
49720
49721
49722
49723
49724
49725
49726
49727
49728
49729
49730
49731
49732
49733
49734
49735
49736
49737
49738
49739
49740
49741
49742
49743
49744
49745
49746
49747
49748
49749
49750
49751
49752
49753
49754
49755
49756
49757
49758
49759
49760
49761
49762
49763
49764
49765
49766
49767
49768
49769
49770
49771
49772
49773
49774
49775
49776
49777
49778
49779
49780
49781
49782
49783
49784
49785
49786
49787
49788
49789
49790
49791
49792
49793
49794
49795
49796
49797
49798
49799
49800
49801
49802
49803
49804
49805
49806
49807
49808
49809
49810
49811
49812
49813
49814
49815
49816
49817
49818
49819
49820
49821
49822
49823
49824
49825
49826
49827
49828
49829
49830
49831
49832
49833
49834
49835
49836
49837
49838
49839
49840
49841
49842
49843
49844
49845
49846
49847
49848
49849
49850
49851
49852
49853
49854
49855
49856
49857
49858
49859
49860
49861
49862
49863
49864
49865
49866
49867
49868
49869
49870
49871
49872
49873
49874
49875
49876
49877
49878
49879
49880
49881
49882
49883
49884
49885
49886
49887
49888
49889
49890
49891
49892
49893
49894
49895
49896
49897
49898
49899
49900
49901
49902
49903
49904
49905
49906
49907
49908
49909
49910
49911
49912
49913
49914
49915
49916
49917
49918
49919
49920
49921
49922
49923
49924
49925
49926
49927
49928
49929
49930
49931
49932
49933
49934
49935
49936
49937
49938
49939
49940
49941
49942
49943
49944
49945
49946
49947
49948
49949
49950
49951
49952
49953
49954
49955
49956
49957
49958
49959
49960
49961
49962
49963
49964
49965
49966
49967
49968
49969
49970
49971
49972
49973
49974
49975
49976
49977
49978
49979
49980
49981
49982
49983
49984
49985
49986
49987
49988
49989
49990
49991
49992
49993
49994
49995
49996
49997
49998
49999
50000
50001
50002
50003
50004
50005
50006
50007
50008
50009
50010
50011
50012
50013
50014
50015
50016
50017
50018
50019
50020
50021
50022
50023
50024
50025
50026
50027
50028
50029
50030
50031
50032
50033
50034
50035
50036
50037
50038
50039
50040
50041
50042
50043
50044
50045
50046
50047
50048
50049
50050
50051
50052
50053
50054
50055
50056
50057
50058
50059
50060
50061
50062
50063
50064
50065
50066
50067
50068
50069
50070
50071
50072
50073
50074
50075
50076
50077
50078
50079
50080
50081
50082
50083
50084
50085
50086
50087
50088
50089
50090
50091
50092
50093
50094
50095
50096
50097
50098
50099
50100
50101
50102
50103
50104
50105
50106
50107
50108
50109
50110
50111
50112
50113
50114
50115
50116
50117
50118
50119
50120
50121
50122
50123
50124
50125
50126
50127
50128
50129
50130
50131
50132
50133
50134
50135
50136
50137
50138
50139
50140
50141
50142
50143
50144
50145
50146
50147
50148
50149
50150
50151
50152
50153
50154
50155
50156
50157
50158
50159
50160
50161
50162
50163
50164
50165
50166
50167
50168
50169
50170
50171
50172
50173
50174
50175
50176
50177
50178
50179
50180
50181
50182
50183
50184
50185
50186
50187
50188
50189
50190
50191
50192
50193
50194
50195
50196
50197
50198
50199
50200
50201
50202
50203
50204
50205
50206
50207
50208
50209
50210
50211
50212
50213
50214
50215
50216
50217
50218
50219
50220
50221
50222
50223
50224
50225
50226
50227
50228
50229
50230
50231
50232
50233
50234
50235
50236
50237
50238
50239
50240
50241
50242
50243
50244
50245
50246
50247
50248
50249
50250
50251
50252
50253
50254
50255
50256
50257
50258
50259
50260
50261
50262
50263
50264
50265
50266
50267
50268
50269
50270
50271
50272
50273
50274
50275
50276
50277
50278
50279
50280
50281
50282
50283
50284
50285
50286
50287
50288
50289
50290
50291
50292
50293
50294
50295
50296
50297
50298
50299
50300
50301
50302
50303
50304
50305
50306
50307
50308
50309
50310
50311
50312
50313
50314
50315
50316
50317
50318
50319
50320
50321
50322
50323
50324
50325
50326
50327
50328
50329
50330
50331
50332
50333
50334
50335
50336
50337
50338
50339
50340
50341
50342
50343
50344
50345
50346
50347
50348
50349
50350
50351
50352
50353
50354
50355
50356
50357
50358
50359
50360
50361
50362
50363
50364
50365
50366
50367
50368
50369
50370
50371
50372
50373
50374
50375
50376
50377
50378
50379
50380
50381
50382
50383
50384
50385
50386
50387
50388
50389
50390
50391
50392
50393
50394
50395
50396
50397
50398
50399
50400
50401
50402
50403
50404
50405
50406
50407
50408
50409
50410
50411
50412
50413
50414
50415
50416
50417
50418
50419
50420
50421
50422
50423
50424
50425
50426
50427
50428
50429
50430
50431
50432
50433
50434
50435
50436
50437
50438
50439
50440
50441
50442
50443
50444
50445
50446
50447
50448
50449
50450
50451
50452
50453
50454
50455
50456
50457
50458
50459
50460
50461
50462
50463
50464
50465
50466
50467
50468
50469
50470
50471
50472
50473
50474
50475
50476
50477
50478
50479
50480
50481
50482
50483
50484
50485
50486
50487
50488
50489
50490
50491
50492
50493
50494
50495
50496
50497
50498
50499
50500
50501
50502
50503
50504
50505
50506
50507
50508
50509
50510
50511
50512
50513
50514
50515
50516
50517
50518
50519
50520
50521
50522
50523
50524
50525
50526
50527
50528
50529
50530
50531
50532
50533
50534
50535
50536
50537
50538
50539
50540
50541
50542
50543
50544
50545
50546
50547
50548
50549
50550
50551
50552
50553
50554
50555
50556
50557
50558
50559
50560
50561
50562
50563
50564
50565
50566
50567
50568
50569
50570
50571
50572
50573
50574
50575
50576
50577
50578
50579
50580
50581
50582
50583
50584
50585
50586
50587
50588
50589
50590
50591
50592
50593
50594
50595
50596
50597
50598
50599
50600
50601
50602
50603
50604
50605
50606
50607
50608
50609
50610
50611
50612
50613
50614
50615
50616
50617
50618
50619
50620
50621
50622
50623
50624
50625
50626
50627
50628
50629
50630
50631
50632
50633
50634
50635
50636
50637
50638
50639
50640
50641
50642
50643
50644
50645
50646
50647
50648
50649
50650
50651
50652
50653
50654
50655
50656
50657
50658
50659
50660
50661
50662
50663
50664
50665
50666
50667
50668
50669
50670
50671
50672
50673
50674
50675
50676
50677
50678
50679
50680
50681
50682
50683
50684
50685
50686
50687
50688
50689
50690
50691
50692
50693
50694
50695
50696
50697
50698
50699
50700
50701
50702
50703
50704
50705
50706
50707
50708
50709
50710
50711
50712
50713
50714
50715
50716
50717
50718
50719
50720
50721
50722
50723
50724
50725
50726
50727
50728
50729
50730
50731
50732
50733
50734
50735
50736
50737
50738
50739
50740
50741
50742
50743
50744
50745
50746
50747
50748
50749
50750
50751
50752
50753
50754
50755
50756
50757
50758
50759
50760
50761
50762
50763
50764
50765
50766
50767
50768
50769
50770
50771
50772
50773
50774
50775
50776
50777
50778
50779
50780
50781
50782
50783
50784
50785
50786
50787
50788
50789
50790
50791
50792
50793
50794
50795
50796
50797
50798
50799
50800
50801
50802
50803
50804
50805
50806
50807
50808
50809
50810
50811
50812
50813
50814
50815
50816
50817
50818
50819
50820
50821
50822
50823
50824
50825
50826
50827
50828
50829
50830
50831
50832
50833
50834
50835
50836
50837
50838
50839
50840
50841
50842
50843
50844
50845
50846
50847
50848
50849
50850
50851
50852
50853
50854
50855
50856
50857
50858
50859
50860
50861
50862
50863
50864
50865
50866
50867
50868
50869
50870
50871
50872
50873
50874
50875
50876
50877
50878
50879
50880
50881
50882
50883
50884
50885
50886
50887
50888
50889
50890
50891
50892
50893
50894
50895
50896
50897
50898
50899
50900
50901
50902
50903
50904
50905
50906
50907
50908
50909
50910
50911
50912
50913
50914
50915
50916
50917
50918
50919
50920
50921
50922
50923
50924
50925
50926
50927
50928
50929
50930
50931
50932
50933
50934
50935
50936
50937
50938
50939
50940
50941
50942
50943
50944
50945
50946
50947
50948
50949
50950
50951
50952
50953
50954
50955
50956
50957
50958
50959
50960
50961
50962
50963
50964
50965
50966
50967
50968
50969
50970
50971
50972
50973
50974
50975
50976
50977
50978
50979
50980
50981
50982
50983
50984
50985
50986
50987
50988
50989
50990
50991
50992
50993
50994
50995
50996
50997
50998
50999
51000
51001
51002
51003
51004
51005
51006
51007
51008
51009
51010
51011
51012
51013
51014
51015
51016
51017
51018
51019
51020
51021
51022
51023
51024
51025
51026
51027
51028
51029
51030
51031
51032
51033
51034
51035
51036
51037
51038
51039
51040
51041
51042
51043
51044
51045
51046
51047
51048
51049
51050
51051
51052
51053
51054
51055
51056
51057
51058
51059
51060
51061
51062
51063
51064
51065
51066
51067
51068
51069
51070
51071
51072
51073
51074
51075
51076
51077
51078
51079
51080
51081
51082
51083
51084
51085
51086
51087
51088
51089
51090
51091
51092
51093
51094
51095
51096
51097
51098
51099
51100
51101
51102
51103
51104
51105
51106
51107
51108
51109
51110
51111
51112
51113
51114
51115
51116
51117
51118
51119
51120
51121
51122
51123
51124
51125
51126
51127
51128
51129
51130
51131
51132
51133
51134
51135
51136
51137
51138
51139
51140
51141
51142
51143
51144
51145
51146
51147
51148
51149
51150
51151
51152
51153
51154
51155
51156
51157
51158
51159
51160
51161
51162
51163
51164
51165
51166
51167
51168
51169
51170
51171
51172
51173
51174
51175
51176
51177
51178
51179
51180
51181
51182
51183
51184
51185
51186
51187
51188
51189
51190
51191
51192
51193
51194
51195
51196
51197
51198
51199
51200
51201
51202
51203
51204
51205
51206
51207
51208
51209
51210
51211
51212
51213
51214
51215
51216
51217
51218
51219
51220
51221
51222
51223
51224
51225
51226
51227
51228
51229
51230
51231
51232
51233
51234
51235
51236
51237
51238
51239
51240
51241
51242
51243
51244
51245
51246
51247
51248
51249
51250
51251
51252
51253
51254
51255
51256
51257
51258
51259
51260
51261
51262
51263
51264
51265
51266
51267
51268
51269
51270
51271
51272
51273
51274
51275
51276
51277
51278
51279
51280
51281
51282
51283
51284
51285
51286
51287
51288
51289
51290
51291
51292
51293
51294
51295
51296
51297
51298
51299
51300
51301
51302
51303
51304
51305
51306
51307
51308
51309
51310
51311
51312
51313
51314
51315
51316
51317
51318
51319
51320
51321
51322
51323
51324
51325
51326
51327
51328
51329
51330
51331
51332
51333
51334
51335
51336
51337
51338
51339
51340
51341
51342
51343
51344
51345
51346
51347
51348
51349
51350
51351
51352
51353
51354
51355
51356
51357
51358
51359
51360
51361
51362
51363
51364
51365
51366
51367
51368
51369
51370
51371
51372
51373
51374
51375
51376
51377
51378
51379
51380
51381
51382
51383
51384
51385
51386
51387
51388
51389
51390
51391
51392
51393
51394
51395
51396
51397
51398
51399
51400
51401
51402
51403
51404
51405
51406
51407
51408
51409
51410
51411
51412
51413
51414
51415
51416
51417
51418
51419
51420
51421
51422
51423
51424
51425
51426
51427
51428
51429
51430
51431
51432
51433
51434
51435
51436
51437
51438
51439
51440
51441
51442
51443
51444
51445
51446
51447
51448
51449
51450
51451
51452
51453
51454
51455
51456
51457
51458
51459
51460
51461
51462
51463
51464
51465
51466
51467
51468
51469
51470
51471
51472
51473
51474
51475
51476
51477
51478
51479
51480
51481
51482
51483
51484
51485
51486
51487
51488
51489
51490
51491
51492
51493
51494
51495
51496
51497
51498
51499
51500
51501
51502
51503
51504
51505
51506
51507
51508
51509
51510
51511
51512
51513
51514
51515
51516
51517
51518
51519
51520
51521
51522
51523
51524
51525
51526
51527
51528
51529
51530
51531
51532
51533
51534
51535
51536
51537
51538
51539
51540
51541
51542
51543
51544
51545
51546
51547
51548
51549
51550
51551
51552
51553
51554
51555
51556
51557
51558
51559
51560
51561
51562
51563
51564
51565
51566
51567
51568
51569
51570
51571
51572
51573
51574
51575
51576
51577
51578
51579
51580
51581
51582
51583
51584
51585
51586
51587
51588
51589
51590
51591
51592
51593
51594
51595
51596
51597
51598
51599
51600
51601
51602
51603
51604
51605
51606
51607
51608
51609
51610
51611
51612
51613
51614
51615
51616
51617
51618
51619
51620
51621
51622
51623
51624
51625
51626
51627
51628
51629
51630
51631
51632
51633
51634
51635
51636
51637
51638
51639
51640
51641
51642
51643
51644
51645
51646
51647
51648
51649
51650
51651
51652
51653
51654
51655
51656
51657
51658
51659
51660
51661
51662
51663
51664
51665
51666
51667
51668
51669
51670
51671
51672
51673
51674
51675
51676
51677
51678
51679
51680
51681
51682
51683
51684
51685
51686
51687
51688
51689
51690
51691
51692
51693
51694
51695
51696
51697
51698
51699
51700
51701
51702
51703
51704
51705
51706
51707
51708
51709
51710
51711
51712
51713
51714
51715
51716
51717
51718
51719
51720
51721
51722
51723
51724
51725
51726
51727
51728
51729
51730
51731
51732
51733
51734
51735
51736
51737
51738
51739
51740
51741
51742
51743
51744
51745
51746
51747
51748
51749
51750
51751
51752
51753
51754
51755
51756
51757
51758
51759
51760
51761
51762
51763
51764
51765
51766
51767
51768
51769
51770
51771
51772
51773
51774
51775
51776
51777
51778
51779
51780
51781
51782
51783
51784
51785
51786
51787
51788
51789
51790
51791
51792
51793
51794
51795
51796
51797
51798
51799
51800
51801
51802
51803
51804
51805
51806
51807
51808
51809
51810
51811
51812
51813
51814
51815
51816
51817
51818
51819
51820
51821
51822
51823
51824
51825
51826
51827
51828
51829
51830
51831
51832
51833
51834
51835
51836
51837
51838
51839
51840
51841
51842
51843
51844
51845
51846
51847
51848
51849
51850
51851
51852
51853
51854
51855
51856
51857
51858
51859
51860
51861
51862
51863
51864
51865
51866
51867
51868
51869
51870
51871
51872
51873
51874
51875
51876
51877
51878
51879
51880
51881
51882
51883
51884
51885
51886
51887
51888
51889
51890
51891
51892
51893
51894
51895
51896
51897
51898
51899
51900
51901
51902
51903
51904
51905
51906
51907
51908
51909
51910
51911
51912
51913
51914
51915
51916
51917
51918
51919
51920
51921
51922
51923
51924
51925
51926
51927
51928
51929
51930
51931
51932
51933
51934
51935
51936
51937
51938
51939
51940
51941
51942
51943
51944
51945
51946
51947
51948
51949
51950
51951
51952
51953
51954
51955
51956
51957
51958
51959
51960
51961
51962
51963
51964
51965
51966
51967
51968
51969
51970
51971
51972
51973
51974
51975
51976
51977
51978
51979
51980
51981
51982
51983
51984
51985
51986
51987
51988
51989
51990
51991
51992
51993
51994
51995
51996
51997
51998
51999
52000
52001
52002
52003
52004
52005
52006
52007
52008
52009
52010
52011
52012
52013
52014
52015
52016
52017
52018
52019
52020
52021
52022
52023
52024
52025
52026
52027
52028
52029
52030
52031
52032
52033
52034
52035
52036
52037
52038
52039
52040
52041
52042
52043
52044
52045
52046
52047
52048
52049
52050
52051
52052
52053
52054
52055
52056
52057
52058
52059
52060
52061
52062
52063
52064
52065
52066
52067
52068
52069
52070
52071
52072
52073
52074
52075
52076
52077
52078
52079
52080
52081
52082
52083
52084
52085
52086
52087
52088
52089
52090
52091
52092
52093
52094
52095
52096
52097
52098
52099
52100
52101
52102
52103
52104
52105
52106
52107
52108
52109
52110
52111
52112
52113
52114
52115
52116
52117
52118
52119
52120
52121
52122
52123
52124
52125
52126
52127
52128
52129
52130
52131
52132
52133
52134
52135
52136
52137
52138
52139
52140
52141
52142
52143
52144
52145
52146
52147
52148
52149
52150
52151
52152
52153
52154
52155
52156
52157
52158
52159
52160
52161
52162
52163
52164
52165
52166
52167
52168
52169
52170
52171
52172
52173
52174
52175
52176
52177
52178
52179
52180
52181
52182
52183
52184
52185
52186
52187
52188
52189
52190
52191
52192
52193
52194
52195
52196
52197
52198
52199
52200
52201
52202
52203
52204
52205
52206
52207
52208
52209
52210
52211
52212
52213
52214
52215
52216
52217
52218
52219
52220
52221
52222
52223
52224
52225
52226
52227
52228
52229
52230
52231
52232
52233
52234
52235
52236
52237
52238
52239
52240
52241
52242
52243
52244
52245
52246
52247
52248
52249
52250
52251
52252
52253
52254
52255
52256
52257
52258
52259
52260
52261
52262
52263
52264
52265
52266
52267
52268
52269
52270
52271
52272
52273
52274
52275
52276
52277
52278
52279
52280
52281
52282
52283
52284
52285
52286
52287
52288
52289
52290
52291
52292
52293
52294
52295
52296
52297
52298
52299
52300
52301
52302
52303
52304
52305
52306
52307
52308
52309
52310
52311
52312
52313
52314
52315
52316
52317
52318
52319
52320
52321
52322
52323
52324
52325
52326
52327
52328
52329
52330
52331
52332
52333
52334
52335
52336
52337
52338
52339
52340
52341
52342
52343
52344
52345
52346
52347
52348
52349
52350
52351
52352
52353
52354
52355
52356
52357
52358
52359
52360
52361
52362
52363
52364
52365
52366
52367
52368
52369
52370
52371
52372
52373
52374
52375
52376
52377
52378
52379
52380
52381
52382
52383
52384
52385
52386
52387
52388
52389
52390
52391
52392
52393
52394
52395
52396
52397
52398
52399
52400
52401
52402
52403
52404
52405
52406
52407
52408
52409
52410
52411
52412
52413
52414
52415
52416
52417
52418
52419
52420
52421
52422
52423
52424
52425
52426
52427
52428
52429
52430
52431
52432
52433
52434
52435
52436
52437
52438
52439
52440
52441
52442
52443
52444
52445
52446
52447
52448
52449
52450
52451
52452
52453
52454
52455
52456
52457
52458
52459
52460
52461
52462
52463
52464
52465
52466
52467
52468
52469
52470
52471
52472
52473
52474
52475
52476
52477
52478
52479
52480
52481
52482
52483
52484
52485
52486
52487
52488
52489
52490
52491
52492
52493
52494
52495
52496
52497
52498
52499
52500
52501
52502
52503
52504
52505
52506
52507
52508
52509
52510
52511
52512
52513
52514
52515
52516
52517
52518
52519
52520
52521
52522
52523
52524
52525
52526
52527
52528
52529
52530
52531
52532
52533
52534
52535
52536
52537
52538
52539
52540
52541
52542
52543
52544
52545
52546
52547
52548
52549
52550
52551
52552
52553
52554
52555
52556
52557
52558
52559
52560
52561
52562
52563
52564
52565
52566
52567
52568
52569
52570
52571
52572
52573
52574
52575
52576
52577
52578
52579
52580
52581
52582
52583
52584
52585
52586
52587
52588
52589
52590
52591
52592
52593
52594
52595
52596
52597
52598
52599
52600
52601
52602
52603
52604
52605
52606
52607
52608
52609
52610
52611
52612
52613
52614
52615
52616
52617
52618
52619
52620
52621
52622
52623
52624
52625
52626
52627
52628
52629
52630
52631
52632
52633
52634
52635
52636
52637
52638
52639
52640
52641
52642
52643
52644
52645
52646
52647
52648
52649
52650
52651
52652
52653
52654
52655
52656
52657
52658
52659
52660
52661
52662
52663
52664
52665
52666
52667
52668
52669
52670
52671
52672
52673
52674
52675
52676
52677
52678
52679
52680
52681
52682
52683
52684
52685
52686
52687
52688
52689
52690
52691
52692
52693
52694
52695
52696
52697
52698
52699
52700
52701
52702
52703
52704
52705
52706
52707
52708
52709
52710
52711
52712
52713
52714
52715
52716
52717
52718
52719
52720
52721
52722
52723
52724
52725
52726
52727
52728
52729
52730
52731
52732
52733
52734
52735
52736
52737
52738
52739
52740
52741
52742
52743
52744
52745
52746
52747
52748
52749
52750
52751
52752
52753
52754
52755
52756
52757
52758
52759
52760
52761
52762
52763
52764
52765
52766
52767
52768
52769
52770
52771
52772
52773
52774
52775
52776
52777
52778
52779
52780
52781
52782
52783
52784
52785
52786
52787
52788
52789
52790
52791
52792
52793
52794
52795
52796
52797
52798
52799
52800
52801
52802
52803
52804
52805
52806
52807
52808
52809
52810
52811
52812
52813
52814
52815
52816
52817
52818
52819
52820
52821
52822
52823
52824
52825
52826
52827
52828
52829
52830
52831
52832
52833
52834
52835
52836
52837
52838
52839
52840
52841
52842
52843
52844
52845
52846
52847
52848
52849
52850
52851
52852
52853
52854
52855
52856
52857
52858
52859
52860
52861
52862
52863
52864
52865
52866
52867
52868
52869
52870
52871
52872
52873
52874
52875
52876
52877
52878
52879
52880
52881
52882
52883
52884
52885
52886
52887
52888
52889
52890
52891
52892
52893
52894
52895
52896
52897
52898
52899
52900
52901
52902
52903
52904
52905
52906
52907
52908
52909
52910
52911
52912
52913
52914
52915
52916
52917
52918
52919
52920
52921
52922
52923
52924
52925
52926
52927
52928
52929
52930
52931
52932
52933
52934
52935
52936
52937
52938
52939
52940
52941
52942
52943
52944
52945
52946
52947
52948
52949
52950
52951
52952
52953
52954
52955
52956
52957
52958
52959
52960
52961
52962
52963
52964
52965
52966
52967
52968
52969
52970
52971
52972
52973
52974
52975
52976
52977
52978
52979
52980
52981
52982
52983
52984
52985
52986
52987
52988
52989
52990
52991
52992
52993
52994
52995
52996
52997
52998
52999
53000
53001
53002
53003
53004
53005
53006
53007
53008
53009
53010
53011
53012
53013
53014
53015
53016
53017
53018
53019
53020
53021
53022
53023
53024
53025
53026
53027
53028
53029
53030
53031
53032
53033
53034
53035
53036
53037
53038
53039
53040
53041
53042
53043
53044
53045
53046
53047
53048
53049
53050
53051
53052
53053
53054
53055
53056
53057
53058
53059
53060
53061
53062
53063
53064
53065
53066
53067
53068
53069
53070
53071
53072
53073
53074
53075
53076
53077
53078
53079
53080
53081
53082
53083
53084
53085
53086
53087
53088
53089
53090
53091
53092
53093
53094
53095
53096
53097
53098
53099
53100
53101
53102
53103
53104
53105
53106
53107
53108
53109
53110
53111
53112
53113
53114
53115
53116
53117
53118
53119
53120
53121
53122
53123
53124
53125
53126
53127
53128
53129
53130
53131
53132
53133
53134
53135
53136
53137
53138
53139
53140
53141
53142
53143
53144
53145
53146
53147
53148
53149
53150
53151
53152
53153
53154
53155
53156
53157
53158
53159
53160
53161
53162
53163
53164
53165
53166
53167
53168
53169
53170
53171
53172
53173
53174
53175
53176
53177
53178
53179
53180
53181
53182
53183
53184
53185
53186
53187
53188
53189
53190
53191
53192
53193
53194
53195
53196
53197
53198
53199
53200
53201
53202
53203
53204
53205
53206
53207
53208
53209
53210
53211
53212
53213
53214
53215
53216
53217
53218
53219
53220
53221
53222
53223
53224
53225
53226
53227
53228
53229
53230
53231
53232
53233
53234
53235
53236
53237
53238
53239
53240
53241
53242
53243
53244
53245
53246
53247
53248
53249
53250
53251
53252
53253
53254
53255
53256
53257
53258
53259
53260
53261
53262
53263
53264
53265
53266
53267
53268
53269
53270
53271
53272
53273
53274
53275
53276
53277
53278
53279
53280
53281
53282
53283
53284
53285
53286
53287
53288
53289
53290
53291
53292
53293
53294
53295
53296
53297
53298
53299
53300
53301
53302
53303
53304
53305
53306
53307
53308
53309
53310
53311
53312
53313
53314
53315
53316
53317
53318
53319
53320
53321
53322
53323
53324
53325
53326
53327
53328
53329
53330
53331
53332
53333
53334
53335
53336
53337
53338
53339
53340
53341
53342
53343
53344
53345
53346
53347
53348
53349
53350
53351
53352
53353
53354
53355
53356
53357
53358
53359
53360
53361
53362
53363
53364
53365
53366
53367
53368
53369
53370
53371
53372
53373
53374
53375
53376
53377
53378
53379
53380
53381
53382
53383
53384
53385
53386
53387
53388
53389
53390
53391
53392
53393
53394
53395
53396
53397
53398
53399
53400
53401
53402
53403
53404
53405
53406
53407
53408
53409
53410
53411
53412
53413
53414
53415
53416
53417
53418
53419
53420
53421
53422
53423
53424
53425
53426
53427
53428
53429
53430
53431
53432
53433
53434
53435
53436
53437
53438
53439
53440
53441
53442
53443
53444
53445
53446
53447
53448
53449
53450
53451
53452
53453
53454
53455
53456
53457
53458
53459
53460
53461
53462
53463
53464
53465
53466
53467
53468
53469
53470
53471
53472
53473
53474
53475
53476
53477
53478
53479
53480
53481
53482
53483
53484
53485
53486
53487
53488
53489
53490
53491
53492
53493
53494
53495
53496
53497
53498
53499
53500
53501
53502
53503
53504
53505
53506
53507
53508
53509
53510
53511
53512
53513
53514
53515
53516
53517
53518
53519
53520
53521
53522
53523
53524
53525
53526
53527
53528
53529
53530
53531
53532
53533
53534
53535
53536
53537
53538
53539
53540
53541
53542
53543
53544
53545
53546
53547
53548
53549
53550
53551
53552
53553
53554
53555
53556
53557
53558
53559
53560
53561
53562
53563
53564
53565
53566
53567
53568
53569
53570
53571
53572
53573
53574
53575
53576
53577
53578
53579
53580
53581
53582
53583
53584
53585
53586
53587
53588
53589
53590
53591
53592
53593
53594
53595
53596
53597
53598
53599
53600
53601
53602
53603
53604
53605
53606
53607
53608
53609
53610
53611
53612
53613
53614
53615
53616
53617
53618
53619
53620
53621
53622
53623
53624
53625
53626
53627
53628
53629
53630
53631
53632
53633
53634
53635
53636
53637
53638
53639
53640
53641
53642
53643
53644
53645
53646
53647
53648
53649
53650
53651
53652
53653
53654
53655
53656
53657
53658
53659
53660
53661
53662
53663
53664
53665
53666
53667
53668
53669
53670
53671
53672
53673
53674
53675
53676
53677
53678
53679
53680
53681
53682
53683
53684
53685
53686
53687
53688
53689
53690
53691
53692
53693
53694
53695
53696
53697
53698
53699
53700
53701
53702
53703
53704
53705
53706
53707
53708
53709
53710
53711
53712
53713
53714
53715
53716
53717
53718
53719
53720
53721
53722
53723
53724
53725
53726
53727
53728
53729
53730
53731
53732
53733
53734
53735
53736
53737
53738
53739
53740
53741
53742
53743
53744
53745
53746
53747
53748
53749
53750
53751
53752
53753
53754
53755
53756
53757
53758
53759
53760
53761
53762
53763
53764
53765
53766
53767
53768
53769
53770
53771
53772
53773
53774
53775
53776
53777
53778
53779
53780
53781
53782
53783
53784
53785
53786
53787
53788
53789
53790
53791
53792
53793
53794
53795
53796
53797
53798
53799
53800
53801
53802
53803
53804
53805
53806
53807
53808
53809
53810
53811
53812
53813
53814
53815
53816
53817
53818
53819
53820
53821
53822
53823
53824
53825
53826
53827
53828
53829
53830
53831
53832
53833
53834
53835
53836
53837
53838
53839
53840
53841
53842
53843
53844
53845
53846
53847
53848
53849
53850
53851
53852
53853
53854
53855
53856
53857
53858
53859
53860
53861
53862
53863
53864
53865
53866
53867
53868
53869
53870
53871
53872
53873
53874
53875
53876
53877
53878
53879
53880
53881
53882
53883
53884
53885
53886
53887
53888
53889
53890
53891
53892
53893
53894
53895
53896
53897
53898
53899
53900
53901
53902
53903
53904
53905
53906
53907
53908
53909
53910
53911
53912
53913
53914
53915
53916
53917
53918
53919
53920
53921
53922
53923
53924
53925
53926
53927
53928
53929
53930
53931
53932
53933
53934
53935
53936
53937
53938
53939
53940
53941
53942
53943
53944
53945
53946
53947
53948
53949
53950
53951
53952
53953
53954
53955
53956
53957
53958
53959
53960
53961
53962
53963
53964
53965
53966
53967
53968
53969
53970
53971
53972
53973
53974
53975
53976
53977
53978
53979
53980
53981
53982
53983
53984
53985
53986
53987
53988
53989
53990
53991
53992
53993
53994
53995
53996
53997
53998
53999
54000
54001
54002
54003
54004
54005
54006
54007
54008
54009
54010
54011
54012
54013
54014
54015
54016
54017
54018
54019
54020
54021
54022
54023
54024
54025
54026
54027
54028
54029
54030
54031
54032
54033
54034
54035
54036
54037
54038
54039
54040
54041
54042
54043
54044
54045
54046
54047
54048
54049
54050
54051
54052
54053
54054
54055
54056
54057
54058
54059
54060
54061
54062
54063
54064
54065
54066
54067
54068
54069
54070
54071
54072
54073
54074
54075
54076
54077
54078
54079
54080
54081
54082
54083
54084
54085
54086
54087
54088
54089
54090
54091
54092
54093
54094
54095
54096
54097
54098
54099
54100
54101
54102
54103
54104
54105
54106
54107
54108
54109
54110
54111
54112
54113
54114
54115
54116
54117
54118
54119
54120
54121
54122
54123
54124
54125
54126
54127
54128
54129
54130
54131
54132
54133
54134
54135
54136
54137
54138
54139
54140
54141
54142
54143
54144
54145
54146
54147
54148
54149
54150
54151
54152
54153
54154
54155
54156
54157
54158
54159
54160
54161
54162
54163
54164
54165
54166
54167
54168
54169
54170
54171
54172
54173
54174
54175
54176
54177
54178
54179
54180
54181
54182
54183
54184
54185
54186
54187
54188
54189
54190
54191
54192
54193
54194
54195
54196
54197
54198
54199
54200
54201
54202
54203
54204
54205
54206
54207
54208
54209
54210
54211
54212
54213
54214
54215
54216
54217
54218
54219
54220
54221
54222
54223
54224
54225
54226
54227
54228
54229
54230
54231
54232
54233
54234
54235
54236
54237
54238
54239
54240
54241
54242
54243
54244
54245
54246
54247
54248
54249
54250
54251
54252
54253
54254
54255
54256
54257
54258
54259
54260
54261
54262
54263
54264
54265
54266
54267
54268
54269
54270
54271
54272
54273
54274
54275
54276
54277
54278
54279
54280
54281
54282
54283
54284
54285
54286
54287
54288
54289
54290
54291
54292
54293
54294
54295
54296
54297
54298
54299
54300
54301
54302
54303
54304
54305
54306
54307
54308
54309
54310
54311
54312
54313
54314
54315
54316
54317
54318
54319
54320
54321
54322
54323
54324
54325
54326
54327
54328
54329
54330
54331
54332
54333
54334
54335
54336
54337
54338
54339
54340
54341
54342
54343
54344
54345
54346
54347
54348
54349
54350
54351
54352
54353
54354
54355
54356
54357
54358
54359
54360
54361
54362
54363
54364
54365
54366
54367
54368
54369
54370
54371
54372
54373
54374
54375
54376
54377
54378
54379
54380
54381
54382
54383
54384
54385
54386
54387
54388
54389
54390
54391
54392
54393
54394
54395
54396
54397
54398
54399
54400
54401
54402
54403
54404
54405
54406
54407
54408
54409
54410
54411
54412
54413
54414
54415
54416
54417
54418
54419
54420
54421
54422
54423
54424
54425
54426
54427
54428
54429
54430
54431
54432
54433
54434
54435
54436
54437
54438
54439
54440
54441
54442
54443
54444
54445
54446
54447
54448
54449
54450
54451
54452
54453
54454
54455
54456
54457
54458
54459
54460
54461
54462
54463
54464
54465
54466
54467
54468
54469
54470
54471
54472
54473
54474
54475
54476
54477
54478
54479
54480
54481
54482
54483
54484
54485
54486
54487
54488
54489
54490
54491
54492
54493
54494
54495
54496
54497
54498
54499
54500
54501
54502
54503
54504
54505
54506
54507
54508
54509
54510
54511
54512
54513
54514
54515
54516
54517
54518
54519
54520
54521
54522
54523
54524
54525
54526
54527
54528
54529
54530
54531
54532
54533
54534
54535
54536
54537
54538
54539
54540
54541
54542
54543
54544
54545
54546
54547
54548
54549
54550
54551
54552
54553
54554
54555
54556
54557
54558
54559
54560
54561
54562
54563
54564
54565
54566
54567
54568
54569
54570
54571
54572
54573
54574
54575
54576
54577
54578
54579
54580
54581
54582
54583
54584
54585
54586
54587
54588
54589
54590
54591
54592
54593
54594
54595
54596
54597
54598
54599
54600
54601
54602
54603
54604
54605
54606
54607
54608
54609
54610
54611
54612
54613
54614
54615
54616
54617
54618
54619
54620
54621
54622
54623
54624
54625
54626
54627
54628
54629
54630
54631
54632
54633
54634
54635
54636
54637
54638
54639
54640
54641
54642
54643
54644
54645
54646
54647
54648
54649
54650
54651
54652
54653
54654
54655
54656
54657
54658
54659
54660
54661
54662
54663
54664
54665
54666
54667
54668
54669
54670
54671
54672
54673
54674
54675
54676
54677
54678
54679
54680
54681
54682
54683
54684
54685
54686
54687
54688
54689
54690
54691
54692
54693
54694
54695
54696
54697
54698
54699
54700
54701
54702
54703
54704
54705
54706
54707
54708
54709
54710
54711
54712
54713
54714
54715
54716
54717
54718
54719
54720
54721
54722
54723
54724
54725
54726
54727
54728
54729
54730
54731
54732
54733
54734
54735
54736
54737
54738
54739
54740
54741
54742
54743
54744
54745
54746
54747
54748
54749
54750
54751
54752
54753
54754
54755
54756
54757
54758
54759
54760
54761
54762
54763
54764
54765
54766
54767
54768
54769
54770
54771
54772
54773
54774
54775
54776
54777
54778
54779
54780
54781
54782
54783
54784
54785
54786
54787
54788
54789
54790
54791
54792
54793
54794
54795
54796
54797
54798
54799
54800
54801
54802
54803
54804
54805
54806
54807
54808
54809
54810
54811
54812
54813
54814
54815
54816
54817
54818
54819
54820
54821
54822
54823
54824
54825
54826
54827
54828
54829
54830
54831
54832
54833
54834
54835
54836
54837
54838
54839
54840
54841
54842
54843
54844
54845
54846
54847
54848
54849
54850
54851
54852
54853
54854
54855
54856
54857
54858
54859
54860
54861
54862
54863
54864
54865
54866
54867
54868
54869
54870
54871
54872
54873
54874
54875
54876
54877
54878
54879
54880
54881
54882
54883
54884
54885
54886
54887
54888
54889
54890
54891
54892
54893
54894
54895
54896
54897
54898
54899
54900
54901
54902
54903
54904
54905
54906
54907
54908
54909
54910
54911
54912
54913
54914
54915
54916
54917
54918
54919
54920
54921
54922
54923
54924
54925
54926
54927
54928
54929
54930
54931
54932
54933
54934
54935
54936
54937
54938
54939
54940
54941
54942
54943
54944
54945
54946
54947
54948
54949
54950
54951
54952
54953
54954
54955
54956
54957
54958
54959
54960
54961
54962
54963
54964
54965
54966
54967
54968
54969
54970
54971
54972
54973
54974
54975
54976
54977
54978
54979
54980
54981
54982
54983
54984
54985
54986
54987
54988
54989
54990
54991
54992
54993
54994
54995
54996
54997
54998
54999
55000
55001
55002
55003
55004
55005
55006
55007
55008
55009
55010
55011
55012
55013
55014
55015
55016
55017
55018
55019
55020
55021
55022
55023
55024
55025
55026
55027
55028
55029
55030
55031
55032
55033
55034
55035
55036
55037
55038
55039
55040
55041
55042
55043
55044
55045
55046
55047
55048
55049
55050
55051
55052
55053
55054
55055
55056
55057
55058
55059
55060
55061
55062
55063
55064
55065
55066
55067
55068
55069
55070
55071
55072
55073
55074
55075
55076
55077
55078
55079
55080
55081
55082
55083
55084
55085
55086
55087
55088
55089
55090
55091
55092
55093
55094
55095
55096
55097
55098
55099
55100
55101
55102
55103
55104
55105
55106
55107
55108
55109
55110
55111
55112
55113
55114
55115
55116
55117
55118
55119
55120
55121
55122
55123
55124
55125
55126
55127
55128
55129
55130
55131
55132
55133
55134
55135
55136
55137
55138
55139
55140
55141
55142
55143
55144
55145
55146
55147
55148
55149
55150
55151
55152
55153
55154
55155
55156
55157
55158
55159
55160
55161
55162
55163
55164
55165
55166
55167
55168
55169
55170
55171
55172
55173
55174
55175
55176
55177
55178
55179
55180
55181
55182
55183
55184
55185
55186
55187
55188
55189
55190
55191
55192
55193
55194
55195
55196
55197
55198
55199
55200
55201
55202
55203
55204
55205
55206
55207
55208
55209
55210
55211
55212
55213
55214
55215
55216
55217
55218
55219
55220
55221
55222
55223
55224
55225
55226
55227
55228
55229
55230
55231
55232
55233
55234
55235
55236
55237
55238
55239
55240
55241
55242
55243
55244
55245
55246
55247
55248
55249
55250
55251
55252
55253
55254
55255
55256
55257
55258
55259
55260
55261
55262
55263
55264
55265
55266
55267
55268
55269
55270
55271
55272
55273
55274
55275
55276
55277
55278
55279
55280
55281
55282
55283
55284
55285
55286
55287
55288
55289
55290
55291
55292
55293
55294
55295
55296
55297
55298
55299
55300
55301
55302
55303
55304
55305
55306
55307
55308
55309
55310
55311
55312
55313
55314
55315
55316
55317
55318
55319
55320
55321
55322
55323
55324
55325
55326
55327
55328
55329
55330
55331
55332
55333
55334
55335
55336
55337
55338
55339
55340
55341
55342
55343
55344
55345
55346
55347
55348
55349
55350
55351
55352
55353
55354
55355
55356
55357
55358
55359
55360
55361
55362
55363
55364
55365
55366
55367
55368
55369
55370
55371
55372
55373
55374
55375
55376
55377
55378
55379
55380
55381
55382
55383
55384
55385
55386
55387
55388
55389
55390
55391
55392
55393
55394
55395
55396
55397
55398
55399
55400
55401
55402
55403
55404
55405
55406
55407
55408
55409
55410
55411
55412
55413
55414
55415
55416
55417
55418
55419
55420
55421
55422
55423
55424
55425
55426
55427
55428
55429
55430
55431
55432
55433
55434
55435
55436
55437
55438
55439
55440
55441
55442
55443
55444
55445
55446
55447
55448
55449
55450
55451
55452
55453
55454
55455
55456
55457
55458
55459
55460
55461
55462
55463
55464
55465
55466
55467
55468
55469
55470
55471
55472
55473
55474
55475
55476
55477
55478
55479
55480
55481
55482
55483
55484
55485
55486
55487
55488
55489
55490
55491
55492
55493
55494
55495
55496
55497
55498
55499
55500
55501
55502
55503
55504
55505
55506
55507
55508
55509
55510
55511
55512
55513
55514
55515
55516
55517
55518
55519
55520
55521
55522
55523
55524
55525
55526
55527
55528
55529
55530
55531
55532
55533
55534
55535
55536
55537
55538
55539
55540
55541
55542
55543
55544
55545
55546
55547
55548
55549
55550
55551
55552
55553
55554
55555
55556
55557
55558
55559
55560
55561
55562
55563
55564
55565
55566
55567
55568
55569
55570
55571
55572
55573
55574
55575
55576
55577
55578
55579
55580
55581
55582
55583
55584
55585
55586
55587
55588
55589
55590
55591
55592
55593
55594
55595
55596
55597
55598
55599
55600
55601
55602
55603
55604
55605
55606
55607
55608
55609
55610
55611
55612
55613
55614
55615
55616
55617
55618
55619
55620
55621
55622
55623
55624
55625
55626
55627
55628
55629
55630
55631
55632
55633
55634
55635
55636
55637
55638
55639
55640
55641
55642
55643
55644
55645
55646
55647
55648
55649
55650
55651
55652
55653
55654
55655
55656
55657
55658
55659
55660
55661
55662
55663
55664
55665
55666
55667
55668
55669
55670
55671
55672
55673
55674
55675
55676
55677
55678
55679
55680
55681
55682
55683
55684
55685
55686
55687
55688
55689
55690
55691
55692
55693
55694
55695
55696
55697
55698
55699
55700
55701
55702
55703
55704
55705
55706
55707
55708
55709
55710
55711
55712
55713
55714
55715
55716
55717
55718
55719
55720
55721
55722
55723
55724
55725
55726
55727
55728
55729
55730
55731
55732
55733
55734
55735
55736
55737
55738
55739
55740
55741
55742
55743
55744
55745
55746
55747
55748
55749
55750
55751
55752
55753
55754
55755
55756
55757
55758
55759
55760
55761
55762
55763
55764
55765
55766
55767
55768
55769
55770
55771
55772
55773
55774
55775
55776
55777
55778
55779
55780
55781
55782
55783
55784
55785
55786
55787
55788
55789
55790
55791
55792
55793
55794
55795
55796
55797
55798
55799
55800
55801
55802
55803
55804
55805
55806
55807
55808
55809
55810
55811
55812
55813
55814
55815
55816
55817
55818
55819
55820
55821
55822
55823
55824
55825
55826
55827
55828
55829
55830
55831
55832
55833
55834
55835
55836
55837
55838
55839
55840
55841
55842
55843
55844
55845
55846
55847
55848
55849
55850
55851
55852
55853
55854
55855
55856
55857
55858
55859
55860
55861
55862
55863
55864
55865
55866
55867
55868
55869
55870
55871
55872
55873
55874
55875
55876
55877
55878
55879
55880
55881
55882
55883
55884
55885
55886
55887
55888
55889
55890
55891
55892
55893
55894
55895
55896
55897
55898
55899
55900
55901
55902
55903
55904
55905
55906
55907
55908
55909
55910
55911
55912
55913
55914
55915
55916
55917
55918
55919
55920
55921
55922
55923
55924
55925
55926
55927
55928
55929
55930
55931
55932
55933
55934
55935
55936
55937
55938
55939
55940
55941
55942
55943
55944
55945
55946
55947
55948
55949
55950
55951
55952
55953
55954
55955
55956
55957
55958
55959
55960
55961
55962
55963
55964
55965
55966
55967
55968
55969
55970
55971
55972
55973
55974
55975
55976
55977
55978
55979
55980
55981
55982
55983
55984
55985
55986
55987
55988
55989
55990
55991
55992
55993
55994
55995
55996
55997
55998
55999
56000
56001
56002
56003
56004
56005
56006
56007
56008
56009
56010
56011
56012
56013
56014
56015
56016
56017
56018
56019
56020
56021
56022
56023
56024
56025
56026
56027
56028
56029
56030
56031
56032
56033
56034
56035
56036
56037
56038
56039
56040
56041
56042
56043
56044
56045
56046
56047
56048
56049
56050
56051
56052
56053
56054
56055
56056
56057
56058
56059
56060
56061
56062
56063
56064
56065
56066
56067
56068
56069
56070
56071
56072
56073
56074
56075
56076
56077
56078
56079
56080
56081
56082
56083
56084
56085
56086
56087
56088
56089
56090
56091
56092
56093
56094
56095
56096
56097
56098
56099
56100
56101
56102
56103
56104
56105
56106
56107
56108
56109
56110
56111
56112
56113
56114
56115
56116
56117
56118
56119
56120
56121
56122
56123
56124
56125
56126
56127
56128
56129
56130
56131
56132
56133
56134
56135
56136
56137
56138
56139
56140
56141
56142
56143
56144
56145
56146
56147
56148
56149
56150
56151
56152
56153
56154
56155
56156
56157
56158
56159
56160
56161
56162
56163
56164
56165
56166
56167
56168
56169
56170
56171
56172
56173
56174
56175
56176
56177
56178
56179
56180
56181
56182
56183
56184
56185
56186
56187
56188
56189
56190
56191
56192
56193
56194
56195
56196
56197
56198
56199
56200
56201
56202
56203
56204
56205
56206
56207
56208
56209
56210
56211
56212
56213
56214
56215
56216
56217
56218
56219
56220
56221
56222
56223
56224
56225
56226
56227
56228
56229
56230
56231
56232
56233
56234
56235
56236
56237
56238
56239
56240
56241
56242
56243
56244
56245
56246
56247
56248
56249
56250
56251
56252
56253
56254
56255
56256
56257
56258
56259
56260
56261
56262
56263
56264
56265
56266
56267
56268
56269
56270
56271
56272
56273
56274
56275
56276
56277
56278
56279
56280
56281
56282
56283
56284
56285
56286
56287
56288
56289
56290
56291
56292
56293
56294
56295
56296
56297
56298
56299
56300
56301
56302
56303
56304
56305
56306
56307
56308
56309
56310
56311
56312
56313
56314
56315
56316
56317
56318
56319
56320
56321
56322
56323
56324
56325
56326
56327
56328
56329
56330
56331
56332
56333
56334
56335
56336
56337
56338
56339
56340
56341
56342
56343
56344
56345
56346
56347
56348
56349
56350
56351
56352
56353
56354
56355
56356
56357
56358
56359
56360
56361
56362
56363
56364
56365
56366
56367
56368
56369
56370
56371
56372
56373
56374
56375
56376
56377
56378
56379
56380
56381
56382
56383
56384
56385
56386
56387
56388
56389
56390
56391
56392
56393
56394
56395
56396
56397
56398
56399
56400
56401
56402
56403
56404
56405
56406
56407
56408
56409
56410
56411
56412
56413
56414
56415
56416
56417
56418
56419
56420
56421
56422
56423
56424
56425
56426
56427
56428
56429
56430
56431
56432
56433
56434
56435
56436
56437
56438
56439
56440
56441
56442
56443
56444
56445
56446
56447
56448
56449
56450
56451
56452
56453
56454
56455
56456
56457
56458
56459
56460
56461
56462
56463
56464
56465
56466
56467
56468
56469
56470
56471
56472
56473
56474
56475
56476
56477
56478
56479
56480
56481
56482
56483
56484
56485
56486
56487
56488
56489
56490
56491
56492
56493
56494
56495
56496
56497
56498
56499
56500
56501
56502
56503
56504
56505
56506
56507
56508
56509
56510
56511
56512
56513
56514
56515
56516
56517
56518
56519
56520
56521
56522
56523
56524
56525
56526
56527
56528
56529
56530
56531
56532
56533
56534
56535
56536
56537
56538
56539
56540
56541
56542
56543
56544
56545
56546
56547
56548
56549
56550
56551
56552
56553
56554
56555
56556
56557
56558
56559
56560
56561
56562
56563
56564
56565
56566
56567
56568
56569
56570
56571
56572
56573
56574
56575
56576
56577
56578
56579
56580
56581
56582
56583
56584
56585
56586
56587
56588
56589
56590
56591
56592
56593
56594
56595
56596
56597
56598
56599
56600
56601
56602
56603
56604
56605
56606
56607
56608
56609
56610
56611
56612
56613
56614
56615
56616
56617
56618
56619
56620
56621
56622
56623
56624
56625
56626
56627
56628
56629
56630
56631
56632
56633
56634
56635
56636
56637
56638
56639
56640
56641
56642
56643
56644
56645
56646
56647
56648
56649
56650
56651
56652
56653
56654
56655
56656
56657
56658
56659
56660
56661
56662
56663
56664
56665
56666
56667
56668
56669
56670
56671
56672
56673
56674
56675
56676
56677
56678
56679
56680
56681
56682
56683
56684
56685
56686
56687
56688
56689
56690
56691
56692
56693
56694
56695
56696
56697
56698
56699
56700
56701
56702
56703
56704
56705
56706
56707
56708
56709
56710
56711
56712
56713
56714
56715
56716
56717
56718
56719
56720
56721
56722
56723
56724
56725
56726
56727
56728
56729
56730
56731
56732
56733
56734
56735
56736
56737
56738
56739
56740
56741
56742
56743
56744
56745
56746
56747
56748
56749
56750
56751
56752
56753
56754
56755
56756
56757
56758
56759
56760
56761
56762
56763
56764
56765
56766
56767
56768
56769
56770
56771
56772
56773
56774
56775
56776
56777
56778
56779
56780
56781
56782
56783
56784
56785
56786
56787
56788
56789
56790
56791
56792
56793
56794
56795
56796
56797
56798
56799
56800
56801
56802
56803
56804
56805
56806
56807
56808
56809
56810
56811
56812
56813
56814
56815
56816
56817
56818
56819
56820
56821
56822
56823
56824
56825
56826
56827
56828
56829
56830
56831
56832
56833
56834
56835
56836
56837
56838
56839
56840
56841
56842
56843
56844
56845
56846
56847
56848
56849
56850
56851
56852
56853
56854
56855
56856
56857
56858
56859
56860
56861
56862
56863
56864
56865
56866
56867
56868
56869
56870
56871
56872
56873
56874
56875
56876
56877
56878
56879
56880
56881
56882
56883
56884
56885
56886
56887
56888
56889
56890
56891
56892
56893
56894
56895
56896
56897
56898
56899
56900
56901
56902
56903
56904
56905
56906
56907
56908
56909
56910
56911
56912
56913
56914
56915
56916
56917
56918
56919
56920
56921
56922
56923
56924
56925
56926
56927
56928
56929
56930
56931
56932
56933
56934
56935
56936
56937
56938
56939
56940
56941
56942
56943
56944
56945
56946
56947
56948
56949
56950
56951
56952
56953
56954
56955
56956
56957
56958
56959
56960
56961
56962
56963
56964
56965
56966
56967
56968
56969
56970
56971
56972
56973
56974
56975
56976
56977
56978
56979
56980
56981
56982
56983
56984
56985
56986
56987
56988
56989
56990
56991
56992
56993
56994
56995
56996
56997
56998
56999
57000
57001
57002
57003
57004
57005
57006
57007
57008
57009
57010
57011
57012
57013
57014
57015
57016
57017
57018
57019
57020
57021
57022
57023
57024
57025
57026
57027
57028
57029
57030
57031
57032
57033
57034
57035
57036
57037
57038
57039
57040
57041
57042
57043
57044
57045
57046
57047
57048
57049
57050
57051
57052
57053
57054
57055
57056
57057
57058
57059
57060
57061
57062
57063
57064
57065
57066
57067
57068
57069
57070
57071
57072
57073
57074
57075
57076
57077
57078
57079
57080
57081
57082
57083
57084
57085
57086
57087
57088
57089
57090
57091
57092
57093
57094
57095
57096
57097
57098
57099
57100
57101
57102
57103
57104
57105
57106
57107
57108
57109
57110
57111
57112
57113
57114
57115
57116
57117
57118
57119
57120
57121
57122
57123
57124
57125
57126
57127
57128
57129
57130
57131
57132
57133
57134
57135
57136
57137
57138
57139
57140
57141
57142
57143
57144
57145
57146
57147
57148
57149
57150
57151
57152
57153
57154
57155
57156
57157
57158
57159
57160
57161
57162
57163
57164
57165
57166
57167
57168
57169
57170
57171
57172
57173
57174
57175
57176
57177
57178
57179
57180
57181
57182
57183
57184
57185
57186
57187
57188
57189
57190
57191
57192
57193
57194
57195
57196
57197
57198
57199
57200
57201
57202
57203
57204
57205
57206
57207
57208
57209
57210
57211
57212
57213
57214
57215
57216
57217
57218
57219
57220
57221
57222
57223
57224
57225
57226
57227
57228
57229
57230
57231
57232
57233
57234
57235
57236
57237
57238
57239
57240
57241
57242
57243
57244
57245
57246
57247
57248
57249
57250
57251
57252
57253
57254
57255
57256
57257
57258
57259
57260
57261
57262
57263
57264
57265
57266
57267
57268
57269
57270
57271
57272
57273
57274
57275
57276
57277
57278
57279
57280
57281
57282
57283
57284
57285
57286
57287
57288
57289
57290
57291
57292
57293
57294
57295
57296
57297
57298
57299
57300
57301
57302
57303
57304
57305
57306
57307
57308
57309
57310
57311
57312
57313
57314
57315
57316
57317
57318
57319
57320
57321
57322
57323
57324
57325
57326
57327
57328
57329
57330
57331
57332
57333
57334
57335
57336
57337
57338
57339
57340
57341
57342
57343
57344
57345
57346
57347
57348
57349
57350
57351
57352
57353
57354
57355
57356
57357
57358
57359
57360
57361
57362
57363
57364
57365
57366
57367
57368
57369
57370
57371
57372
57373
57374
57375
57376
57377
57378
57379
57380
57381
57382
57383
57384
57385
57386
57387
57388
57389
57390
57391
57392
57393
57394
57395
57396
57397
57398
57399
57400
57401
57402
57403
57404
57405
57406
57407
57408
57409
57410
57411
57412
57413
57414
57415
57416
57417
57418
57419
57420
57421
57422
57423
57424
57425
57426
57427
57428
57429
57430
57431
57432
57433
57434
57435
57436
57437
57438
57439
57440
57441
57442
57443
57444
57445
57446
57447
57448
57449
57450
57451
57452
57453
57454
57455
57456
57457
57458
57459
57460
57461
57462
57463
57464
57465
57466
57467
57468
57469
57470
57471
57472
57473
57474
57475
57476
57477
57478
57479
57480
57481
57482
57483
57484
57485
57486
57487
57488
57489
57490
57491
57492
57493
57494
57495
57496
57497
57498
57499
57500
57501
57502
57503
57504
57505
57506
57507
57508
57509
57510
57511
57512
57513
57514
57515
57516
57517
57518
57519
57520
57521
57522
57523
57524
57525
57526
57527
57528
57529
57530
57531
57532
57533
57534
57535
57536
57537
57538
57539
57540
57541
57542
57543
57544
57545
57546
57547
57548
57549
57550
57551
57552
57553
57554
57555
57556
57557
57558
57559
57560
57561
57562
57563
57564
57565
57566
57567
57568
57569
57570
57571
57572
57573
57574
57575
57576
57577
57578
57579
57580
57581
57582
57583
57584
57585
57586
57587
57588
57589
57590
57591
57592
57593
57594
57595
57596
57597
57598
57599
57600
57601
57602
57603
57604
57605
57606
57607
57608
57609
57610
57611
57612
57613
57614
57615
57616
57617
57618
57619
57620
57621
57622
57623
57624
57625
57626
57627
57628
57629
57630
57631
57632
57633
57634
57635
57636
57637
57638
57639
57640
57641
57642
57643
57644
57645
57646
57647
57648
57649
57650
57651
57652
57653
57654
57655
57656
57657
57658
57659
57660
57661
57662
57663
57664
57665
57666
57667
57668
57669
57670
57671
57672
57673
57674
57675
57676
57677
57678
57679
57680
57681
57682
//! MCP server implementation for FastMCP.
//!
//! This crate provides the server-side implementation:
//! - Server builder pattern
//! - Tool, resource, and prompt registration
//! - Request routing and dispatching
//! - Session management
//!
//! MCP 2026-07-28 support is under implementation and remains unverified. The
//! public protocol constant is still `2024-11-05`; server source presence is
//! not aggregate conformance or release evidence.
//!
//! # Example
//!
//! ```ignore
//! use asupersync::runtime::{RuntimeBuilder, reactor::create_reactor};
//! use fastmcp_rust::{modern::ServerBuilder, prelude::*};
//!
//! #[tool]
//! async fn greet(ctx: &McpContext, name: String) -> McpResult<String> {
//!     ctx.checkpoint()?;
//!     Ok(format!("Hello, {name}!"))
//! }
//!
//! fn main() {
//!     let runtime = RuntimeBuilder::current_thread()
//!         .with_reactor(create_reactor().expect("create I/O reactor"))
//!         .blocking_threads(0, 16)
//!         .build()
//!         .expect("create application runtime");
//!     runtime.block_on(async {
//!         let cx = Cx::current().expect("application context");
//!         ServerBuilder::new("my-server", "1.0.0")
//!             .tool(Greet)
//!             .build()
//!             .run_stdio_with_cx(&cx)
//!             .await
//!     });
//! }
//! ```
//!
//! # Role in the System
//!
//! `fastmcp-server` is the **execution engine** for MCP servers. It ties
//! together:
//! - Protocol types (`fastmcp-protocol`) for requests and responses
//! - Transports (`fastmcp-transport`) for stdio/SSE/WebSocket/HTTP/memory I/O
//! - Core context + cancellation (`fastmcp-core`) for budgets and checkpoints
//! - Console output (`fastmcp-console`) for human-friendly stderr rendering
//!
//! The façade package `fastmcp-rust` re-exports this API, so most users
//! interact with `Server` via `fastmcp_rust::prelude::*`.
//!
//! # Extension panic-containment boundary
//!
//! Unwinding extension callback panics (including handler, auth, middleware,
//! and lifecycle callbacks) are caught at their framework boundaries.
//! Request-path failures are mapped to a fixed payload-free peer error. FastMCP
//! also installs a redacting panic hook for local diagnostics, but Rust's hook
//! is process-global and replaceable: an embedding application that installs
//! another hook afterward controls subsequent panic diagnostics. Such
//! replacement does not change the fixed peer error, but FastMCP cannot promise
//! payload-free local diagnostics after its hook has been replaced.

// Raised for the trait solver: proving `Send` for the nested async blocks in
// `serve_http_connection` overflows the default limit on newer rustc.
#![recursion_limit = "512"]
#![forbid(unsafe_code)]

// Proc-macros (fastmcp-derive) reference this crate by its external name
// (`fastmcp_server::...`). This alias makes those macros usable inside this crate too
// (including in unit tests).
extern crate self as fastmcp_server;

mod async_stdio;
mod auth;
pub mod bidirectional;
mod builder;
pub mod caching;
// FND-01: Docket/Redis is not part of the FND-01 production surface. Source bytes
// remain on disk (no-deletion) and are package-excluded; do not re-export.
pub mod extensions;
mod handler;
pub mod http_admission;
#[cfg(feature = "legacy-2024-11-05")]
pub mod legacy_2024;
mod middleware;
pub mod oauth;
pub mod oidc;
pub mod providers;
#[cfg(feature = "proxy")]
mod proxy;
pub mod rate_limiting;
mod router;
mod session;
#[cfg(feature = "tasks")]
mod tasks;
pub mod transform;

#[cfg(test)]
mod tests;

pub use auth::{
    AllowAllAuthProvider, AuthProvider, AuthRequest, StaticTokenVerifier, TokenAuthProvider,
    TokenVerifier,
};
pub use builder::{
    RefusedRegistration, RegistrationKind, ServerBuildError, ServerBuilder, ServerLaunchPolicyError,
};
pub use extensions::{
    ExtensionHandler, ExtensionHandlerInvocationError, ExtensionHandlerKey,
    ExtensionHandlerLookupError, ExtensionHandlerRegistrationError, ExtensionHandlerRegistry,
};
pub use fastmcp_console::config::{BannerStyle, ConsoleConfig, TrafficVerbosity};
pub use fastmcp_console::stats::{ServerStats, StatsSnapshot};
use fastmcp_protocol::{
    MAX_CLIENT_REGISTRATION_BYTES, SecurityDocumentKind, admit_security_document,
};
/// Cancellation-aware server-side WebSocket message adapter.
///
/// [`BoundWebSocketServer`] owns the listener and HTTP Upgrade boundary; this
/// lower-level adapter remains available for embedders that already own an
/// upgraded asupersync byte stream.
#[cfg(feature = "websocket")]
pub use fastmcp_transport::websocket::AsyncWsServerTransport;
pub use handler::{
    BidirectionalSenders, BoxFuture, CompletionHandler, FinalElicitation,
    FinalElicitationContextExt, FinalMethodOutcome, FinalResourceReadCacheHintProvenance,
    FinalRoots, FinalRootsContextExt, FinalSampling, FinalSamplingContextExt, FinalToolOutcome,
    FinalToolSchemaAuthority, ProgressNotificationSender, PromptHandler, ResourceHandler,
    ToolErrorKind, ToolExecutionMode, ToolHandler, UriParams, create_context_with_progress,
    create_context_with_progress_and_senders, promote_legacy_prompt_messages,
    promote_legacy_resource_contents, promote_legacy_tool_content,
};
pub use middleware::continuation_replay::{
    ContinuationReplayAuthority, ContinuationReplayLimits, ContinuationReplayMiddleware,
};
pub use middleware::{Middleware, MiddlewareDecision};
use oauth::{
    AuthorizationRequest, CodeChallengeMethod, NativePublicClientRegistrationRequest, OAuthError,
    OAuthHttpRoutes, OAuthParameterAdmission, OAuthParameterEndpoint, OAuthParameterName,
    TokenRequest,
};
#[cfg(feature = "proxy")]
pub use proxy::{
    FinalProgressCallback, ProgressCallback, ProxyAsyncRequest, ProxyBackend, ProxyCatalog,
    ProxyCatalogCacheHint, ProxyClient, ProxyFinalCatalog, ProxyLegacyPeerNotifications,
    ProxyPromptCatalog, ProxyResourceCatalog, ProxyResourceTemplateCatalog, ProxyToolCatalog,
    ProxyTypedCatalog, ProxyUpstreamAdapter, ProxyUpstreamBinding, ProxyUpstreamBindingRegistry,
};
#[cfg(all(feature = "proxy", feature = "tasks"))]
use proxy::{ProxyCatalogListener, ProxyCatalogListenerEvent, ProxyFinalTaskRelay};
#[cfg(all(feature = "proxy", feature = "tasks"))]
pub use proxy::{ProxyFinalTaskListener, ProxyFinalTaskListenerEvent};
pub use router::{
    InboundRequestContext, InboundRequestTransport, ModernConnection, MountResult,
    NotificationSender, Router, TagFilters,
};
use router::{RouterPromptCaller, RouterResourceReader, RouterToolCaller, TransportAuthorization};
pub use session::Session;
#[cfg(feature = "legacy-2024-11-05")]
use session::SessionPrincipalBinding;
use session::{
    InitializationSnapshot, MAX_RESOURCE_SUBSCRIPTION_BYTES_PER_SESSION, SubscriptionAdmission,
    SubscriptionAdmissionError, SubscriptionRemoval, SubscriptionRemovalError,
};
#[cfg(feature = "tasks")]
pub use tasks::{
    ApplicationTaskSupervisor, AuthorizedTaskServiceRunner, DEFAULT_IN_MEMORY_FINAL_TASKS,
    FinalTaskAcceptedInput, FinalTaskExecutionBudget, FinalTaskExecutionLimits,
    FinalTaskInitialWork, FinalTaskNotificationEmitter, FinalTaskRetentionAuthority,
    FinalTaskRetentionDeadline, FinalTaskRuntime, FinalTaskRuntimeConfig, FinalTaskSnapshot,
    FinalTaskStore, FinalTaskSupervisorFuture, FinalTaskSupervisorHandoff, FinalTaskWorkDescriptor,
    InMemoryFinalTaskStore, MAX_IN_MEMORY_FINAL_TASK_INPUT_KEY_BYTES,
    MAX_IN_MEMORY_FINAL_TASK_INPUT_KEYS,
};
#[cfg(all(test, feature = "tasks"))]
pub(crate) use tasks::{SharedTaskManager, TaskManager};

// Re-export bidirectional communication types
pub use bidirectional::{
    PendingRequests, RequestSender, TransportElicitationSender, TransportRootsProvider,
    TransportSamplingSender,
};

use std::any::Any;
use std::cell::Cell;
#[cfg(all(feature = "proxy", feature = "tasks"))]
use std::collections::BTreeSet;
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::future::Future;
use std::io::Write;
use std::net::SocketAddr;
#[cfg(feature = "websocket")]
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex, Once, OnceLock};
#[cfg(feature = "websocket")]
use std::task::{Context, Poll};
use std::time::{Duration, Instant};

#[cfg(feature = "legacy-2024-11-05")]
use fastmcp_transport::http::{
    DualEraHttpEndpoint, DualEraHttpEndpointConfig, DualEraHttpEndpointError,
    DualEraHttpEndpointResponse, DualEraHttpLegacyLifecycle, DualEraHttpLegacySseResponse,
    DualEraHttpSession, DualEraHttpSseResponse, Legacy2024HttpPostEnvelope,
    admit_legacy_2024_http_post,
};
use fastmcp_transport::http::{
    HttpError, HttpHandlerConfig, HttpMethod, HttpRequest, HttpRequestHandler, HttpResponse,
    HttpSessionError, HttpStatus, StreamableHttpRequestCancellation,
    StreamableHttpRequestResponseSender,
};
use fastmcp_transport::sse::SseEvent;
#[cfg(not(feature = "legacy-2024-11-05"))]
use modern_http_only::{
    DualEraHttpEndpoint, DualEraHttpEndpointConfig, DualEraHttpEndpointError,
    DualEraHttpEndpointResponse, DualEraHttpSession, DualEraHttpSseResponse,
};

// The normal no-legacy graph deliberately omits the transport's dual-era
// adapter. The server still needs the modern request-owned HTTP primitives, so
// provide a private modern-only composition with the same internal seam. It
// has no `/sse` or legacy-message admission branch.
#[cfg(not(feature = "legacy-2024-11-05"))]
mod modern_http_only {
    use std::sync::Arc;

    use asupersync::Cx;
    use fastmcp_protocol::{JsonRpcMessage, JsonRpcRequest, JsonRpcResponse, RequestId};
    use fastmcp_transport::http::{
        HttpError, HttpRequest, HttpRequestHandler, HttpResponse, HttpResponseRepresentation,
        HttpStatus, StreamableHttpRequestCancellation, StreamableHttpRequestResponseSender,
        StreamableHttpRequestResponseStream, StreamableHttpResponseStream, StreamableHttpTransport,
    };
    use fastmcp_transport::sse::SseEvent;
    use fastmcp_transport::{Transport, TransportError};

    #[derive(Debug)]
    pub enum DualEraHttpEndpointError {
        InvalidConfiguration(String),
        Http(HttpError),
        Transport(TransportError),
        Closed,
    }

    impl std::fmt::Display for DualEraHttpEndpointError {
        fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            match self {
                Self::InvalidConfiguration(message) => formatter.write_str(message),
                Self::Http(error) => error.fmt(formatter),
                Self::Transport(error) => error.fmt(formatter),
                Self::Closed => formatter.write_str("modern HTTP session is closed"),
            }
        }
    }
    impl std::error::Error for DualEraHttpEndpointError {}
    impl From<HttpError> for DualEraHttpEndpointError {
        fn from(error: HttpError) -> Self {
            Self::Http(error)
        }
    }
    impl From<TransportError> for DualEraHttpEndpointError {
        fn from(error: TransportError) -> Self {
            Self::Transport(error)
        }
    }

    pub struct DualEraHttpEndpointConfig {
        pub request_capacity: usize,
    }
    impl DualEraHttpEndpointConfig {
        pub fn new() -> Self {
            Self {
                request_capacity: 64,
            }
        }
    }

    pub struct DualEraHttpEndpoint {
        handler: Arc<HttpRequestHandler>,
        capacity: usize,
    }
    impl DualEraHttpEndpoint {
        pub fn new(
            handler: HttpRequestHandler,
            config: DualEraHttpEndpointConfig,
        ) -> Result<Self, DualEraHttpEndpointError> {
            if config.request_capacity == 0 {
                return Err(DualEraHttpEndpointError::InvalidConfiguration(
                    "modern HTTP request capacity must be nonzero".to_owned(),
                ));
            }
            Ok(Self {
                handler: Arc::new(handler),
                capacity: config.request_capacity,
            })
        }

        pub fn open_session(&self) -> Result<DualEraHttpSession, DualEraHttpEndpointError> {
            let mut transport = StreamableHttpTransport::with_capacity(self.capacity)?;
            let ingress = transport.request_ingress()?;
            let responses = transport.response_stream()?;
            Ok(DualEraHttpSession {
                handler: Arc::clone(&self.handler),
                transport,
                ingress,
                responses,
                closed: false,
            })
        }
    }

    pub enum DualEraHttpEndpointResponse {
        Immediate(HttpResponse),
        ModernJson(DualEraHttpJsonResponse),
        ModernSse(DualEraHttpSseResponse),
    }

    pub struct DualEraHttpJsonResponse {
        handler: Arc<HttpRequestHandler>,
        responses: StreamableHttpResponseStream,
        request_id: RequestId,
        origin: Option<String>,
    }
    impl DualEraHttpJsonResponse {
        pub fn try_response(&self) -> Result<Option<HttpResponse>, DualEraHttpEndpointError> {
            let Some(response) = self.responses.pop_response(Some(&self.request_id))? else {
                return Ok(None);
            };
            Ok(Some(
                self.handler
                    .try_create_response(&response, self.origin.as_deref())?,
            ))
        }
    }

    pub struct DualEraHttpSseResponse {
        response: HttpResponse,
        body: StreamableHttpRequestResponseStream,
    }
    impl DualEraHttpSseResponse {
        pub fn response(&self) -> &HttpResponse {
            &self.response
        }
        pub fn cancellation(&self) -> StreamableHttpRequestCancellation {
            self.body.cancellation()
        }
        pub fn sender(&self) -> StreamableHttpRequestResponseSender {
            self.body.sender()
        }
        pub fn is_finished(&self) -> bool {
            self.body.is_finished()
        }
        pub fn pop_event(&self) -> Result<Option<SseEvent>, DualEraHttpEndpointError> {
            self.body
                .pop_message()
                .map(|message| message.map(frame_message))
                .map_err(Into::into)
        }
    }

    fn frame_message(
        message: fastmcp_transport::http::StreamableHttpRequestResponseMessage,
    ) -> SseEvent {
        let value = match message {
            fastmcp_transport::http::StreamableHttpRequestResponseMessage::Notification(
                request,
            )
            | fastmcp_transport::http::StreamableHttpRequestResponseMessage::Request(request) => {
                serde_json::to_string(&request)
            }
            fastmcp_transport::http::StreamableHttpRequestResponseMessage::Response(response) => {
                serde_json::to_string(&response)
            }
        }
        .expect("validated JSON-RPC message must serialize for a modern HTTP SSE body");
        SseEvent::message(value)
    }

    pub struct DualEraHttpSession {
        handler: Arc<HttpRequestHandler>,
        transport: StreamableHttpTransport,
        ingress: fastmcp_transport::http::StreamableHttpRequestIngress,
        responses: StreamableHttpResponseStream,
        closed: bool,
    }
    impl DualEraHttpSession {
        pub fn handle(
            &mut self,
            cx: &Cx,
            request: HttpRequest,
        ) -> Result<DualEraHttpEndpointResponse, DualEraHttpEndpointError> {
            if self.closed {
                return Err(DualEraHttpEndpointError::Closed);
            }
            if request.path != self.handler.config().base_path {
                return Ok(DualEraHttpEndpointResponse::Immediate(HttpResponse::new(
                    HttpStatus::NOT_FOUND,
                )));
            }
            let origin = request.header("origin").map(str::to_owned);
            let admission = self.handler.admit_modern_request(&request)?;
            let json_rpc = admission.request().clone();
            match admission.response_representation() {
                HttpResponseRepresentation::Json => {
                    self.ingress.push_request(cx, json_rpc.clone())?;
                    let Some(request_id) = json_rpc.id else {
                        return Ok(DualEraHttpEndpointResponse::Immediate(HttpResponse::new(
                            HttpStatus::ACCEPTED,
                        )));
                    };
                    Ok(DualEraHttpEndpointResponse::ModernJson(
                        DualEraHttpJsonResponse {
                            handler: Arc::clone(&self.handler),
                            responses: self.responses.clone(),
                            request_id,
                            origin,
                        },
                    ))
                }
                HttpResponseRepresentation::Sse => {
                    let body = admission.bind_sse_response_body(&self.responses)?;
                    self.ingress.push_request(cx, json_rpc)?;
                    Ok(DualEraHttpEndpointResponse::ModernSse(
                        DualEraHttpSseResponse {
                            response: HttpResponse::new(HttpStatus::OK)
                                .with_header("content-type", "text/event-stream")
                                .with_header("cache-control", "no-cache")
                                .with_header("connection", "keep-alive")
                                .with_body(Vec::new()),
                            body,
                        },
                    ))
                }
            }
        }
        pub fn recv_modern_request(
            &mut self,
            cx: &Cx,
        ) -> Result<JsonRpcRequest, DualEraHttpEndpointError> {
            match self.transport.recv(cx)? {
                JsonRpcMessage::Request(request) => Ok(request),
                JsonRpcMessage::Response(_) => {
                    Err(DualEraHttpEndpointError::Transport(TransportError::Io(
                        std::io::Error::other("modern HTTP ingress yielded a response"),
                    )))
                }
            }
        }
        pub fn send_modern_json_response(
            &mut self,
            cx: &Cx,
            response: JsonRpcResponse,
        ) -> Result<(), DualEraHttpEndpointError> {
            self.transport
                .send(cx, &JsonRpcMessage::Response(response))?;
            Ok(())
        }
        pub fn send_modern_sse_response(
            &mut self,
            cx: &Cx,
            cancellation: &StreamableHttpRequestCancellation,
            response: JsonRpcResponse,
        ) -> Result<(), DualEraHttpEndpointError> {
            self.transport
                .send_response_for_request(cx, cancellation, response)?;
            Ok(())
        }
        pub fn send_modern_sse_notification(
            &mut self,
            cx: &Cx,
            cancellation: &StreamableHttpRequestCancellation,
            notification: JsonRpcRequest,
        ) -> Result<(), DualEraHttpEndpointError> {
            self.transport
                .send_notification_for_request(cx, cancellation, notification)?;
            Ok(())
        }
        pub fn close(&mut self) {
            if self.closed {
                return;
            }
            self.closed = true;
            self.transport.terminate();
        }
    }

    impl Drop for DualEraHttpSession {
        fn drop(&mut self) {
            self.close();
        }
    }
}

use crate::http_admission::{
    AdmittedModernPost, HttpAdmissionLimits, HttpEndpointConfig, ModernPostRejection,
    ResponseRepresentation, admit_modern_post,
};

use asupersync::bytes::BytesMut;
#[cfg(any(feature = "legacy-2024-11-05", feature = "websocket"))]
use asupersync::channel::mpsc as asupersync_mpsc;
use asupersync::codec::{Decoder, Encoder, Framed};
#[cfg(feature = "legacy-2024-11-05")]
use asupersync::cx::ChildRegionSpec;
use asupersync::http::h1::{
    Http1Codec, HttpError as Http1DecodeError, Method as Http1Method, Response as Http1Response,
};
#[cfg(feature = "websocket")]
use asupersync::io::{AsyncRead, AsyncWrite, ReadBuf};
use asupersync::io::{AsyncReadExt, AsyncWriteExt};
use asupersync::net::{TcpListener as AsyncTcpListener, TcpStream as AsyncTcpStream};
use asupersync::stream::StreamExt;
use asupersync::{Budget, CancelKind, Cx, RegionId, channel::oneshot};
use fastmcp_console::RequestResponseRenderer;
use fastmcp_console::banner::StartupBanner;
use fastmcp_console::console::FastMcpConsole;
use fastmcp_console::logging::RichLoggerBuilder;
#[cfg(test)]
use fastmcp_core::block_on;
use fastmcp_core::logging::{debug, error, info, targets};
use fastmcp_core::{
    AuthContext, ClientCapabilityInfo, McpContext, McpContextLeaseGuard, McpError, McpErrorCode,
    McpLogLevel, McpRequestCancellation, McpResult, ServerCapabilityInfo, SessionState,
    Sha256Digest, sha256_bounded,
};
#[cfg(any(feature = "apps", feature = "tasks"))]
use fastmcp_protocol::ExtensionDescriptorRegistry;
use fastmcp_protocol::common_types::OpenMetadata;
use fastmcp_protocol::common_types::{Implementation, LoggingLevel};
#[cfg(feature = "apps")]
use fastmcp_protocol::extensions::McpAppsNegotiationResolver;
#[cfg(feature = "tasks")]
use fastmcp_protocol::extensions::TasksNegotiationResolver;
use fastmcp_protocol::extensions::{
    ExtensionLocalEnablement, ExtensionNegotiationError, ExtensionSettingsCompatibilityResolver,
    ExtensionSettingsResolution,
};
#[cfg(feature = "legacy-2024-11-05")]
use fastmcp_protocol::methods::decode_legacy_2024_11_05_client_capabilities;
#[cfg(feature = "legacy-2024-11-05")]
use fastmcp_protocol::methods::{
    Legacy2024ListChangedCapability, Legacy2024ResourcesCapability, Legacy2024ServerCapabilities,
};
use fastmcp_protocol::methods::{SUBSCRIPTIONS_LISTEN, final_2026_07_28_method};
use fastmcp_protocol::protocol_policy::{
    LEGACY_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION, ModernVersionSupport, ProtocolEra,
    ProtocolPolicy, StdioEraClassifier, StdioEraDecision, StdioOpeningFrame,
};
#[cfg(feature = "tasks")]
use fastmcp_protocol::task_subscription_ids;
#[cfg(feature = "tasks")]
use fastmcp_protocol::tasks_extension::{
    TaskStatusNotification as FinalTaskStatusNotification, set_task_subscription_ids,
};
use fastmcp_protocol::{
    CallToolParams, CancellationSender, CancellationWireMessage, CancelledParams,
    ClientCapabilities, ClientExtensionDiscovery, ClientNotification, CoreRequest, CoreResult,
    CorrelationKey, DiscoveryCacheHints, ExtensionDescriptor, ExtensionId, ExtensionRegistryError,
    ExtensionRegistryReceipt, ExtensionSettings, FINAL_CLIENT_CAPABILITIES_META_KEY,
    FINAL_SERVER_INFO_META_KEY, FINAL_SUBSCRIPTION_ID_META_KEY, FinalCancelledNotificationParams,
    FinalCoreRequest, FinalCoreResult, FinalLogMessageParams, FinalResultMetadataSeal,
    FinalSubscriptionsAcknowledgedNotificationParams, FinalSubscriptionsListenParams,
    GetPromptParams, InitializeParams, JsonRpcError, JsonRpcMessage, JsonRpcRequest,
    JsonRpcResponse, ListPromptsParams, ListResourceTemplatesParams, ListResourcesParams,
    ListToolsParams, LogLevel, LogMessageParams, MAX_SERVER_INSTRUCTIONS_BYTES,
    MISSING_REQUIRED_CLIENT_CAPABILITY_ERROR_CODE, MissingRequiredClientCapabilityError,
    ProgressMarker, Prompt, ReadResourceParams, RequestId, Resource, ResourceTemplate,
    SERVER_DISCOVER_METHOD, ServerCapabilities, ServerDiscoverCapabilities, ServerDiscoverRequest,
    ServerDiscoverResult, ServerExtensionDiscovery, ServerInfo, ServerInstructions,
    ServerNotification, SetLogLevelParams, SubscribeResourceParams, SubscriptionFilter, Tool,
    UnsubscribeResourceParams,
};
use fastmcp_protocol::{CompleteResult, FinalSubscriptionsListenResult, ResultMeta};
#[cfg(feature = "legacy-2024-11-05")]
use legacy_2024::{
    Legacy2024AdapterError, Legacy2024Handler, Legacy2024HandlerError, Legacy2024Outbound,
    Legacy2024ServerAdapter, Legacy2024ServerConfig, Legacy2024ServerInfo, Legacy2024StateSnapshot,
    LegacyAuthenticatedPeerPartition, LegacyPeerBinding,
};

const REDACTED_EXTENSION_PANIC_INCIDENT: &[u8] =
    b"fastmcp extension callback panicked; panic payload redacted\n";
/// Server-local error code for a bounded resource-subscription admission
/// failure. MCP does not currently assign a standard `ResourceExhausted` code.
const RESOURCE_EXHAUSTED_ERROR_CODE: i32 = -32006;
const RESOURCE_SUBSCRIPTION_CAPACITY_MESSAGE: &str = "Resource subscription capacity exhausted";
const MAX_DISPATCH_QUEUE_DEPTH: usize = 64;
/// Anti-hang watchdog for the test helpers that drive a whole returning
/// transport lifecycle on a blocking thread and wait for its result.
///
/// This is NOT a latency assertion. Nothing about the protocol or the server
/// promises to finish inside it, and no test asserts on it; its only job is to
/// fail loudly instead of hanging the suite when a pump never produces a
/// result. Each per-test assertion on the returned value is unaffected.
///
/// It must therefore be far larger than any legitimate completion, because the
/// bound starts before the pump has been scheduled. `cargo test -p
/// fastmcp-server --lib` discovers 2307 tests and, at default parallelism,
/// leaves hundreds of threads competing for CPU, so a pump can sit runnable
/// while the clock runs. The previous 2-second bound measured that contention
/// rather than the server: it produced a rotating set of ~12 failures across
/// `legacy_application_content_*`, `live_runtime_*` and
/// `public_stdio_legacy_progress_*`, all reporting the same
/// "legacy returning test timed out", while the identical tests passed under
/// `--test-threads=1`. A genuine stall still trips this bound and is still
/// reported as a failure.
#[cfg(test)]
const RETURNING_PUMP_WATCHDOG_NANOS: u64 = 30_000_000_000;
const MAX_DISPATCH_QUEUE_BYTES: usize = 16 * 1024 * 1024;
const DISPATCH_QUEUE_CAPACITY_MESSAGE: &str = "Server request queue capacity exhausted";
const DISCOVERY_CACHE_MAX_AGE_SECONDS: u32 = 60;
const MODERN_ONLY_INITIALIZE_MESSAGE: &str = "Initialization-based MCP is not enabled";
/// Typed refusal for a modern (discovery-era) request on a `LegacyOnly`
/// endpoint. Plan §1.7: a `LegacyOnly` endpoint exposes no modern method, so
/// the JSON-RPC class is `-32601` (method not found), the same admitted
/// legacy-refusal signal the Auto stdio client uses to fall back to the
/// exact 2024-11-05 lifecycle. `-32600` stays reserved for a genuine
/// mid-connection era mismatch on an already negotiated connection.
const LEGACY_ONLY_MODERN_MESSAGE: &str = "Discovery-based MCP is not enabled";
const STDIO_OUTPUT_COMMIT_TIMEOUT: Duration = Duration::from_secs(2);
const DISPATCH_WORKER_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
const HTTP_TERMINAL_DRAIN_TIMEOUT: Duration = Duration::from_secs(2);
/// Wake `accept` often enough that a cancelled listener Cx can leave the
/// loop without waiting for the next inbound connection. Two live SSE
/// listens otherwise keep their writers parked until fixture teardown
/// burns `HTTP_TERMINAL_DRAIN_TIMEOUT`.
const HTTP_ACCEPT_CANCEL_POLL: Duration = Duration::from_millis(20);
/// Default bound on receiving one complete HTTP request (head and body). A
/// peer that connects and then sends nothing, or trickles bytes, would
/// otherwise hold one of the listener's `max_connections` slots forever.
const DEFAULT_HTTP_REQUEST_READ_TIMEOUT: Duration = Duration::from_secs(30);
/// Bound the public HTTP lifecycle's cooperative connection drain.  A
/// synchronous handler which ignores cancellation cannot be preempted, so a
/// timeout returns a caller-owned handle retaining its still-live child.
const HTTP_CONNECTION_SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(500);
/// Maximum time a modern request may retain one coalesced progress update
/// while its handler is still running.
const FINAL_PROGRESS_FLUSH_INTERVAL: Duration = Duration::from_millis(50);
/// The response commit gate is transiently contended by final progress, logs,
/// and the terminal response. Retry that contention, but never spin a server
/// worker forever when a transport cannot make progress.
const MAX_HTTP_SSE_COMMIT_RETRIES: usize = 64;
static INSTALL_EXTENSION_PANIC_HOOK: Once = Once::new();
#[cfg(test)]
static REDACTED_EXTENSION_PANIC_COUNT: AtomicUsize = AtomicUsize::new(0);

#[cfg(test)]
thread_local! {
    /// Test-only fault injection consumed by the public HTTP endpoint path.
    /// Keeping this thread-local prevents an intentionally stalled endpoint
    /// from perturbing unrelated tests running in parallel.
    static FORCED_HTTP_SSE_WOULD_BLOCK_COMMITS: Cell<usize> = const { Cell::new(0) };
}

#[cfg(test)]
fn set_forced_http_sse_would_block_commits(commits: usize) {
    FORCED_HTTP_SSE_WOULD_BLOCK_COMMITS.with(|remaining| remaining.set(commits));
}

#[cfg(test)]
fn take_forced_http_sse_would_block_commit() -> bool {
    FORCED_HTTP_SSE_WOULD_BLOCK_COMMITS.with(|remaining| {
        let commits = remaining.get();
        if commits == 0 {
            false
        } else {
            remaining.set(commits - 1);
            true
        }
    })
}

#[cfg(test)]
fn forced_http_sse_would_block_commits_remaining() -> usize {
    FORCED_HTTP_SSE_WOULD_BLOCK_COMMITS.with(|remaining| remaining.get())
}

#[cfg(test)]
struct StdioProgressCommitInterlock {
    request_id: u64,
    state: Mutex<StdioProgressCommitInterlockState>,
    changed: Condvar,
}

#[cfg(test)]
#[derive(Default)]
struct StdioProgressCommitInterlockState {
    entered: bool,
    released: bool,
}

#[cfg(test)]
impl StdioProgressCommitInterlock {
    fn new(request_id: u64) -> Self {
        Self {
            request_id,
            state: Mutex::new(StdioProgressCommitInterlockState::default()),
            changed: Condvar::new(),
        }
    }

    fn wait_until_entered(&self, timeout: Duration) -> bool {
        let state = self
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let (state, _) = self
            .changed
            .wait_timeout_while(state, timeout, |state| !state.entered)
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        state.entered
    }

    fn release(&self) {
        let mut state = self
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        state.released = true;
        self.changed.notify_all();
    }
}

#[cfg(test)]
static STDIO_PROGRESS_COMMIT_INTERLOCK: std::sync::OnceLock<
    Mutex<Option<Arc<StdioProgressCommitInterlock>>>,
> = std::sync::OnceLock::new();

#[cfg(test)]
fn install_stdio_progress_commit_interlock(request_id: u64) -> Arc<StdioProgressCommitInterlock> {
    let interlock = Arc::new(StdioProgressCommitInterlock::new(request_id));
    let mut installed = STDIO_PROGRESS_COMMIT_INTERLOCK
        .get_or_init(|| Mutex::new(None))
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    assert!(
        installed.is_none(),
        "only one stdio progress interlock may be active"
    );
    *installed = Some(Arc::clone(&interlock));
    interlock
}

#[cfg(test)]
fn release_stdio_progress_commit_interlock() {
    let Some(interlock) = STDIO_PROGRESS_COMMIT_INTERLOCK.get() else {
        return;
    };
    let interlock = interlock
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .take();
    if let Some(interlock) = interlock {
        interlock.release();
    }
}

#[cfg(test)]
fn wait_for_stdio_progress_commit_fence(request_id: u64, notification: &JsonRpcRequest) {
    if notification.method != "notifications/progress" {
        return;
    }
    let Some(interlock) = STDIO_PROGRESS_COMMIT_INTERLOCK.get().and_then(|installed| {
        installed
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .as_ref()
            .filter(|interlock| interlock.request_id == request_id)
            .cloned()
    }) else {
        return;
    };
    // A test that stops before releasing the interlock must fail rather than
    // leave this progress writer blocked for the rest of the process.
    const RELEASE_BOUND: Duration = Duration::from_secs(60);
    let mut state = interlock
        .state
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    state.entered = true;
    interlock.changed.notify_all();
    let (_state, waited) = interlock
        .changed
        .wait_timeout_while(state, RELEASE_BOUND, |state| !state.released)
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    assert!(
        !waited.timed_out(),
        "stdio progress commit interlock was not released within {RELEASE_BOUND:?}; its test stopped before releasing it"
    );
}

/// Failure while installing the server-owned extension registry.
#[derive(Debug)]
pub enum ServerExtensionConfigurationError {
    /// A builder accepts exactly one caller-supplied extension registry.
    AlreadyInstalled,
    /// Final Tasks was configured more than once for the same server.
    FinalTasksAlreadyInstalled,
    /// Official MCP Apps was configured more than once for the same server.
    OfficialMcpAppsAlreadyInstalled,
    /// Caller discovery contradicts descriptor-bound server metadata.
    ConflictingServerMetadata(String),
    /// Discovery attempted to advertise an identifier absent from the registry.
    UnregisteredAdvertisedExtension(String),
    /// The descriptor registry could not be frozen into a canonical receipt.
    Registry(ExtensionRegistryError),
    /// The server could not bind a typed final Tasks handler.
    Handler(ExtensionHandlerRegistrationError),
    /// Builder-time resolver composition found a poisoned resolver lock.
    ResolverPoisoned,
}

impl std::fmt::Display for ServerExtensionConfigurationError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::AlreadyInstalled => {
                formatter.write_str("a server extension registry is already installed")
            }
            Self::FinalTasksAlreadyInstalled => {
                formatter.write_str("the final Tasks extension is already installed")
            }
            Self::OfficialMcpAppsAlreadyInstalled => {
                formatter.write_str("the official MCP Apps extension is already installed")
            }
            Self::ConflictingServerMetadata(id) => {
                write!(
                    formatter,
                    "server discovery contradicts registered metadata: {id}"
                )
            }
            Self::UnregisteredAdvertisedExtension(id) => {
                write!(
                    formatter,
                    "server discovery advertises an unregistered extension: {id}"
                )
            }
            Self::Registry(error) => {
                write!(formatter, "server extension registry is invalid: {error}")
            }
            Self::Handler(error) => {
                write!(formatter, "server extension handler is invalid: {error}")
            }
            Self::ResolverPoisoned => {
                formatter.write_str("the server extension resolver is unavailable")
            }
        }
    }
}

impl std::error::Error for ServerExtensionConfigurationError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Registry(error) => Some(error),
            Self::Handler(error) => Some(error),
            Self::AlreadyInstalled
            | Self::FinalTasksAlreadyInstalled
            | Self::OfficialMcpAppsAlreadyInstalled
            | Self::ConflictingServerMetadata(_)
            | Self::UnregisteredAdvertisedExtension(_)
            | Self::ResolverPoisoned => None,
        }
    }
}

/// Failure while deriving a current-exchange extension capability set.
#[derive(Debug)]
pub enum ServerExtensionNegotiationError {
    /// This server has no extension registry installed.
    NotConfigured,
    /// The installed resolver lock was poisoned by an earlier caller panic.
    ResolverPoisoned,
    /// The frozen protocol registry rejected the current peer settings.
    Protocol(ExtensionNegotiationError),
}

impl std::fmt::Display for ServerExtensionNegotiationError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NotConfigured => formatter.write_str("the server has no extension registry"),
            Self::ResolverPoisoned => {
                formatter.write_str("the server extension resolver is unavailable")
            }
            Self::Protocol(error) => {
                write!(formatter, "server extension negotiation failed: {error}")
            }
        }
    }
}

impl std::error::Error for ServerExtensionNegotiationError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Protocol(error) => Some(error),
            Self::NotConfigured | Self::ResolverPoisoned => None,
        }
    }
}

/// Sized bridge for a caller-provided dynamic extension settings resolver.
struct BoxedExtensionSettingsResolver(Box<dyn ExtensionSettingsCompatibilityResolver + Send>);

impl ExtensionSettingsCompatibilityResolver for BoxedExtensionSettingsResolver {
    fn resolve(
        &mut self,
        descriptor: &ExtensionDescriptor,
        client: &ExtensionSettings,
        server: &ExtensionSettings,
    ) -> Result<ExtensionSettings, ExtensionNegotiationError> {
        self.0.resolve(descriptor, client, server)
    }

    fn resolve_with_disposition(
        &mut self,
        descriptor: &ExtensionDescriptor,
        client: &ExtensionSettings,
        server: &ExtensionSettings,
    ) -> Result<ExtensionSettingsResolution, ExtensionNegotiationError> {
        self.0.resolve_with_disposition(descriptor, client, server)
    }
}

/// Immutable server-owned extension runtime retained after builder freeze.
pub(crate) struct ServerExtensionRuntime {
    handlers: ExtensionHandlerRegistry,
    local_enablement: ExtensionLocalEnablement,
    server_discovery: ServerExtensionDiscovery,
    resolver: Mutex<BoxedExtensionSettingsResolver>,
}

impl ServerExtensionRuntime {
    pub(crate) fn new<R>(
        handlers: ExtensionHandlerRegistry,
        mut server_discovery: ServerExtensionDiscovery,
        resolver: R,
    ) -> Result<Self, ServerExtensionConfigurationError>
    where
        R: ExtensionSettingsCompatibilityResolver + Send + 'static,
    {
        let registered_discovery = handlers.configured_server_discovery();
        for (id, settings) in registered_discovery.extensions {
            match server_discovery.extensions.get(&id) {
                Some(existing) if existing != &settings => {
                    return Err(
                        ServerExtensionConfigurationError::ConflictingServerMetadata(
                            id.to_string(),
                        ),
                    );
                }
                Some(_) => {}
                None => {
                    server_discovery.extensions.insert(id, settings);
                }
            }
        }
        for id in server_discovery.extensions.keys() {
            if handlers.descriptor_registry().descriptor(id).is_none() {
                return Err(
                    ServerExtensionConfigurationError::UnregisteredAdvertisedExtension(
                        id.to_string(),
                    ),
                );
            }
        }

        // `ServerBuilder::build` has no failure channel. Freeze a clone now so
        // its canonical descriptor digest is known-valid before construction.
        let mut preflight = handlers.descriptor_registry().clone();
        preflight
            .freeze()
            .map_err(ServerExtensionConfigurationError::Registry)?;

        let mut local_enablement = ExtensionLocalEnablement::default();
        for id in server_discovery.extensions.keys() {
            local_enablement.enable(id.clone());
        }

        let resolver = BoxedExtensionSettingsResolver(Box::new(resolver));
        #[cfg(feature = "apps")]
        let resolver = {
            let apps_id = fastmcp_protocol::extensions::official_mcp_apps_extension_id();
            if server_discovery.extensions.contains_key(&apps_id) {
                BoxedExtensionSettingsResolver(Box::new(McpAppsNegotiationResolver::with_fallback(
                    resolver,
                )))
            } else {
                resolver
            }
        };

        Ok(Self {
            handlers,
            local_enablement,
            server_discovery,
            resolver: Mutex::new(resolver),
        })
    }

    #[cfg(feature = "apps")]
    pub(crate) fn with_official_mcp_apps() -> Result<Self, ServerExtensionConfigurationError> {
        let handlers = ExtensionHandlerRegistry::new(ExtensionDescriptorRegistry::new());
        let mut runtime = Self::new(
            handlers,
            ServerExtensionDiscovery::default(),
            |descriptor: &ExtensionDescriptor,
             _client: &ExtensionSettings,
             _server: &ExtensionSettings|
             -> Result<ExtensionSettings, ExtensionNegotiationError> {
                Err(ExtensionNegotiationError::SettingsCompatibilityRejected(
                    descriptor.id.to_string(),
                ))
            },
        )?;
        runtime.install_official_mcp_apps()?;
        Ok(runtime)
    }

    #[cfg(feature = "tasks")]
    pub(crate) fn with_final_tasks(
        task_runtime: &FinalTaskRuntime,
    ) -> Result<Self, ServerExtensionConfigurationError> {
        let handlers = ExtensionHandlerRegistry::new(ExtensionDescriptorRegistry::new());
        let mut runtime = Self::new(
            handlers,
            ServerExtensionDiscovery::default(),
            |descriptor: &ExtensionDescriptor,
             _client: &ExtensionSettings,
             _server: &ExtensionSettings|
             -> Result<ExtensionSettings, ExtensionNegotiationError> {
                Err(ExtensionNegotiationError::SettingsCompatibilityRejected(
                    descriptor.id.to_string(),
                ))
            },
        )?;
        runtime.install_final_tasks(task_runtime)?;
        Ok(runtime)
    }

    #[cfg(all(feature = "proxy", feature = "tasks"))]
    pub(crate) fn with_proxy_final_tasks(
        task_relay: Arc<ProxyFinalTaskRelay>,
    ) -> Result<Self, ServerExtensionConfigurationError> {
        let handlers = ExtensionHandlerRegistry::new(ExtensionDescriptorRegistry::new());
        let mut runtime = Self::new(
            handlers,
            ServerExtensionDiscovery::default(),
            |descriptor: &ExtensionDescriptor,
             _client: &ExtensionSettings,
             _server: &ExtensionSettings|
             -> Result<ExtensionSettings, ExtensionNegotiationError> {
                Err(ExtensionNegotiationError::SettingsCompatibilityRejected(
                    descriptor.id.to_string(),
                ))
            },
        )?;
        runtime.install_proxy_final_tasks(task_relay)?;
        Ok(runtime)
    }

    /// Merges the official final Tasks descriptor, handlers, discovery
    /// settings, and resolver branch into this still-mutable registry.
    ///
    /// The caller-supplied registry keeps ownership of every unrelated
    /// descriptor and resolver path. A pre-existing official Tasks descriptor
    /// is a real duplicate ownership conflict because the final runtime owns
    /// all three Tasks request handlers as one atomic surface.
    #[cfg(feature = "tasks")]
    pub(crate) fn install_final_tasks(
        &mut self,
        task_runtime: &FinalTaskRuntime,
    ) -> Result<(), ServerExtensionConfigurationError> {
        let tasks_id = fastmcp_protocol::extensions::official_tasks_extension_id();
        if self
            .handlers
            .descriptor_registry()
            .descriptor(&tasks_id)
            .is_some()
        {
            return Err(ServerExtensionConfigurationError::FinalTasksAlreadyInstalled);
        }

        fastmcp_protocol::extensions::register_official_tasks_extension(
            self.handlers
                .descriptor_registry_mut()
                .map_err(ServerExtensionConfigurationError::Handler)?,
        )
        .map_err(ServerExtensionConfigurationError::Registry)?;

        let task_settings = fastmcp_protocol::extensions::official_tasks_empty_settings();
        if self
            .server_discovery
            .extensions
            .insert(tasks_id.clone(), task_settings)
            .is_some()
        {
            return Err(ServerExtensionConfigurationError::FinalTasksAlreadyInstalled);
        }
        self.local_enablement.enable(tasks_id.clone());

        let get_runtime = task_runtime.clone();
        self.handlers
            .register(
                tasks_id.clone(),
                fastmcp_protocol::tasks_extension::TASK_GET,
                move |context: &McpContext, parameters: serde_json::Value| {
                    tasks::dispatch_final_tasks_get(&get_runtime, context, parameters)
                },
            )
            .map_err(ServerExtensionConfigurationError::Handler)?;

        let update_runtime = task_runtime.clone();
        self.handlers
            .register(
                tasks_id.clone(),
                fastmcp_protocol::tasks_extension::TASK_UPDATE,
                move |context: &McpContext, parameters: serde_json::Value| {
                    tasks::dispatch_final_tasks_update(&update_runtime, context, parameters)
                },
            )
            .map_err(ServerExtensionConfigurationError::Handler)?;

        let cancel_runtime = task_runtime.clone();
        self.handlers
            .register(
                tasks_id.clone(),
                fastmcp_protocol::tasks_extension::TASK_CANCEL,
                move |context: &McpContext, parameters: serde_json::Value| {
                    tasks::dispatch_final_tasks_cancel(&cancel_runtime, context, parameters)
                },
            )
            .map_err(ServerExtensionConfigurationError::Handler)?;

        let resolver = self
            .resolver
            .get_mut()
            .map_err(|_| ServerExtensionConfigurationError::ResolverPoisoned)?;
        let previous = std::mem::replace(
            resolver,
            BoxedExtensionSettingsResolver(Box::new(
                |descriptor: &ExtensionDescriptor,
                 _client: &ExtensionSettings,
                 _server: &ExtensionSettings|
                 -> Result<ExtensionSettings, ExtensionNegotiationError> {
                    Err(ExtensionNegotiationError::SettingsCompatibilityRejected(
                        descriptor.id.to_string(),
                    ))
                },
            )),
        );
        *resolver = BoxedExtensionSettingsResolver(Box::new(
            TasksNegotiationResolver::with_fallback(previous),
        ));
        Ok(())
    }

    /// Installs the official final Tasks descriptor around one selected
    /// upstream relay. The handlers deliberately construct fresh upstream
    /// request metadata through that selected client; downstream `_meta` is
    /// admission data and is never replayed across a proxy boundary.
    #[cfg(all(feature = "proxy", feature = "tasks"))]
    pub(crate) fn install_proxy_final_tasks(
        &mut self,
        task_relay: Arc<ProxyFinalTaskRelay>,
    ) -> Result<(), ServerExtensionConfigurationError> {
        let tasks_id = fastmcp_protocol::extensions::official_tasks_extension_id();
        if self
            .handlers
            .descriptor_registry()
            .descriptor(&tasks_id)
            .is_some()
        {
            return Err(ServerExtensionConfigurationError::FinalTasksAlreadyInstalled);
        }
        fastmcp_protocol::extensions::register_official_tasks_extension(
            self.handlers
                .descriptor_registry_mut()
                .map_err(ServerExtensionConfigurationError::Handler)?,
        )
        .map_err(ServerExtensionConfigurationError::Registry)?;
        let task_settings = fastmcp_protocol::extensions::official_tasks_empty_settings();
        if self
            .server_discovery
            .extensions
            .insert(tasks_id.clone(), task_settings)
            .is_some()
        {
            return Err(ServerExtensionConfigurationError::FinalTasksAlreadyInstalled);
        }
        self.local_enablement.enable(tasks_id.clone());

        let get_relay = Arc::clone(&task_relay);
        self.handlers
            .register_async(
                tasks_id.clone(),
                fastmcp_protocol::tasks_extension::TASK_GET,
                move |context: &McpContext, parameters: serde_json::Value| {
                    let relay = Arc::clone(&get_relay);
                    Box::pin(async move { relay.dispatch_get(context, parameters).await })
                },
            )
            .map_err(ServerExtensionConfigurationError::Handler)?;
        let update_relay = Arc::clone(&task_relay);
        self.handlers
            .register_async(
                tasks_id.clone(),
                fastmcp_protocol::tasks_extension::TASK_UPDATE,
                move |context: &McpContext, parameters: serde_json::Value| {
                    let relay = Arc::clone(&update_relay);
                    Box::pin(async move { relay.dispatch_update(context, parameters).await })
                },
            )
            .map_err(ServerExtensionConfigurationError::Handler)?;
        self.handlers
            .register_async(
                tasks_id.clone(),
                fastmcp_protocol::tasks_extension::TASK_CANCEL,
                move |context: &McpContext, parameters: serde_json::Value| {
                    let relay = Arc::clone(&task_relay);
                    Box::pin(async move { relay.dispatch_cancel(context, parameters).await })
                },
            )
            .map_err(ServerExtensionConfigurationError::Handler)?;

        let resolver = self
            .resolver
            .get_mut()
            .map_err(|_| ServerExtensionConfigurationError::ResolverPoisoned)?;
        let previous = std::mem::replace(
            resolver,
            BoxedExtensionSettingsResolver(Box::new(
                |descriptor: &ExtensionDescriptor,
                 _client: &ExtensionSettings,
                 _server: &ExtensionSettings|
                 -> Result<ExtensionSettings, ExtensionNegotiationError> {
                    Err(ExtensionNegotiationError::SettingsCompatibilityRejected(
                        descriptor.id.to_string(),
                    ))
                },
            )),
        );
        *resolver = BoxedExtensionSettingsResolver(Box::new(
            TasksNegotiationResolver::with_fallback(previous),
        ));
        Ok(())
    }

    /// Merges the official MCP Apps descriptor, its exact empty discovery
    /// marker, and its disposition-preserving resolver branch into this
    /// still-mutable runtime.
    #[cfg(feature = "apps")]
    pub(crate) fn install_official_mcp_apps(
        &mut self,
    ) -> Result<(), ServerExtensionConfigurationError> {
        let apps_id = fastmcp_protocol::extensions::official_mcp_apps_extension_id();
        if self
            .handlers
            .descriptor_registry()
            .descriptor(&apps_id)
            .is_some()
            || self.server_discovery.extensions.contains_key(&apps_id)
        {
            return Err(ServerExtensionConfigurationError::OfficialMcpAppsAlreadyInstalled);
        }
        self.handlers
            .install_official_mcp_apps()
            .map_err(ServerExtensionConfigurationError::Handler)?;
        self.server_discovery.extensions.insert(
            apps_id.clone(),
            fastmcp_protocol::extensions::official_mcp_apps_empty_server_settings(),
        );
        self.local_enablement.enable(apps_id);

        let resolver = self
            .resolver
            .get_mut()
            .map_err(|_| ServerExtensionConfigurationError::ResolverPoisoned)?;
        let previous = std::mem::replace(
            resolver,
            BoxedExtensionSettingsResolver(Box::new(
                |descriptor: &ExtensionDescriptor,
                 _client: &ExtensionSettings,
                 _server: &ExtensionSettings|
                 -> Result<ExtensionSettings, ExtensionNegotiationError> {
                    Err(ExtensionNegotiationError::SettingsCompatibilityRejected(
                        descriptor.id.to_string(),
                    ))
                },
            )),
        );
        *resolver = BoxedExtensionSettingsResolver(Box::new(
            McpAppsNegotiationResolver::with_fallback(previous),
        ));
        Ok(())
    }

    pub(crate) fn freeze(&mut self) -> Result<ExtensionRegistryReceipt, ExtensionRegistryError> {
        self.handlers.freeze()
    }

    fn discovery_capabilities(&self) -> BTreeMap<String, serde_json::Value> {
        self.server_discovery
            .extensions
            .iter()
            .map(|(id, settings)| {
                (
                    id.as_str().to_owned(),
                    serde_json::Value::Object(settings.as_object().clone()),
                )
            })
            .collect()
    }

    fn negotiate(
        &self,
        client: &ClientExtensionDiscovery,
    ) -> Result<fastmcp_protocol::extensions::NegotiatedExtensionSet, ServerExtensionNegotiationError>
    {
        let mut resolver = self
            .resolver
            .lock()
            .map_err(|_| ServerExtensionNegotiationError::ResolverPoisoned)?;
        self.handlers
            .descriptor_registry()
            .negotiate(
                ProtocolEra::Modern2026,
                &self.local_enablement,
                client,
                &self.server_discovery,
                &mut *resolver,
            )
            .map_err(ServerExtensionNegotiationError::Protocol)
    }
}

/// Request-owned state retained until the exact legacy response reaches its
/// stdio commit boundary.
#[cfg(feature = "legacy-2024-11-05")]
struct LiveLegacy2024ActiveRequest {
    cancellation: McpRequestCancellation,
    active_guard: ActiveRequestGuard,
    budget: Budget,
}

/// Result of a live exact-2024 dispatch together with its still-active
/// cancellation authority.
#[cfg(feature = "legacy-2024-11-05")]
struct LiveLegacy2024Dispatch {
    result: McpResult<serde_json::Value>,
    active_request: LiveLegacy2024ActiveRequest,
}

/// Shared handler-facing state for one live exact-2024 stdio connection.
///
/// The lifecycle adapter owns exact wire admission, while this runtime owns
/// the server facilities a dispatched handler can use. Keeping these values
/// together prevents an admitted legacy request from receiving a fresh state
/// bag or a disconnected outbound request registry.
#[derive(Clone)]
#[cfg(feature = "legacy-2024-11-05")]
struct LiveLegacy2024ConnectionRuntime {
    session_state: SessionState,
    notification_sender: NotificationSender,
    request_sender: Option<RequestSender>,
    supports_sampling: Arc<AtomicBool>,
    supports_roots: Arc<AtomicBool>,
    client_info: Arc<Mutex<Option<fastmcp_protocol::ClientInfo>>>,
    resource_subscriptions: Arc<Mutex<Vec<String>>>,
    log_level: Arc<Mutex<Option<LogLevel>>>,
    logging_ceiling: LevelFilter,
}

#[cfg(feature = "legacy-2024-11-05")]
fn map_legacy_log_level(level: &str, ceiling: LevelFilter) -> Option<LogLevel> {
    let mapped = match level {
        "debug" => LogLevel::Debug,
        "info" => LogLevel::Info,
        "notice" => LogLevel::Notice,
        "warning" => LogLevel::Warning,
        "error" => LogLevel::Error,
        "critical" => LogLevel::Critical,
        "alert" => LogLevel::Alert,
        "emergency" => LogLevel::Emergency,
        _ => return None,
    };
    let requested = match mapped {
        LogLevel::Debug => LevelFilter::Debug,
        LogLevel::Info | LogLevel::Notice => LevelFilter::Info,
        LogLevel::Warning => LevelFilter::Warn,
        LogLevel::Error | LogLevel::Critical | LogLevel::Alert | LogLevel::Emergency => {
            LevelFilter::Error
        }
    };
    if ceiling == LevelFilter::Off {
        return None;
    }
    let effective = requested.min(ceiling);
    if effective == requested {
        return Some(mapped);
    }
    Some(match effective {
        LevelFilter::Debug => LogLevel::Debug,
        LevelFilter::Info => LogLevel::Info,
        LevelFilter::Warn => LogLevel::Warning,
        LevelFilter::Error | LevelFilter::Trace => LogLevel::Error,
        LevelFilter::Off => return None,
    })
}

#[cfg(feature = "legacy-2024-11-05")]
impl LiveLegacy2024ConnectionRuntime {
    fn new(
        session_state: SessionState,
        notification_sender: NotificationSender,
        request_sender: Option<RequestSender>,
        logging_ceiling: LevelFilter,
    ) -> Self {
        Self {
            session_state,
            notification_sender,
            request_sender,
            supports_sampling: Arc::new(AtomicBool::new(false)),
            supports_roots: Arc::new(AtomicBool::new(false)),
            client_info: Arc::new(Mutex::new(None)),
            resource_subscriptions: Arc::new(Mutex::new(Vec::new())),
            log_level: Arc::new(Mutex::new(None)),
            logging_ceiling,
        }
    }

    fn bidirectional_senders(
        &self,
        server: &Server,
        request_cancellation: &McpRequestCancellation,
        request_context: &McpContext,
    ) -> Option<BidirectionalSenders> {
        let request_sender = self.request_sender.as_ref()?;
        server.create_bidirectional_senders_from_capabilities(
            self.supports_sampling.load(Ordering::Acquire),
            false,
            self.supports_roots.load(Ordering::Acquire),
            request_sender,
            request_cancellation,
            request_context,
        )
    }

    fn log_level(&self) -> Option<LogLevel> {
        *self
            .log_level
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    fn sync_from_adapter_snapshot(&self, snapshot: &Legacy2024StateSnapshot) {
        let supports_sampling =
            serde_json::from_slice::<serde_json::Value>(&snapshot.client_capabilities_bytes)
                .ok()
                .and_then(|capabilities| {
                    decode_legacy_2024_11_05_client_capabilities(capabilities).ok()
                })
                .is_some_and(|capabilities| capabilities.sampling.is_some());
        self.supports_sampling
            .store(supports_sampling, Ordering::Release);

        let supports_roots =
            serde_json::from_slice::<serde_json::Value>(&snapshot.client_capabilities_bytes)
                .ok()
                .and_then(|capabilities| {
                    decode_legacy_2024_11_05_client_capabilities(capabilities).ok()
                })
                .is_some_and(|capabilities| capabilities.roots.is_some());
        self.supports_roots.store(supports_roots, Ordering::Release);

        *self
            .resource_subscriptions
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = snapshot.subscriptions.clone();

        let log_level = snapshot
            .logging_level
            .as_deref()
            .and_then(|level| map_legacy_log_level(level, self.logging_ceiling));
        *self
            .log_level
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = log_level;
    }
}

/// Bridges an admitted exact-2024 operation to the server's legacy result
/// surface while retaining the peer's original request identity.
#[cfg(feature = "legacy-2024-11-05")]
struct LiveLegacy2024RuntimeHandler<'a> {
    server: &'a Server,
    cx: Cx,
    session_id: u64,
    session_principal: SessionPrincipalBinding,
    runtime: LiveLegacy2024ConnectionRuntime,
    queue_state: Option<Arc<DispatchQueueState>>,
    active_request: Arc<Mutex<Option<LiveLegacy2024ActiveRequest>>>,
    connection_auth: Option<AuthDispatchCustody>,
}

/// The live exact-2024 runtime handlers are driven only through
/// `Legacy2024ServerAdapter::receive_async`. Their synchronous hook would have
/// to block on the request future, so it refuses instead of dispatching.
#[cfg(feature = "legacy-2024-11-05")]
const LIVE_LEGACY_SYNC_DISPATCH_REFUSED: &str =
    "live exact-2024 runtime handlers dispatch only through receive_async";

#[cfg(feature = "legacy-2024-11-05")]
fn live_legacy_sync_dispatch_refused() -> Legacy2024HandlerError {
    Legacy2024HandlerError::new(LIVE_LEGACY_SYNC_DISPATCH_REFUSED)
}

#[cfg(feature = "legacy-2024-11-05")]
fn combine_legacy_dispatch_and_close<T>(
    dispatch: Result<T, Legacy2024HandlerError>,
    close: Result<(), Legacy2024HandlerError>,
) -> Result<T, Legacy2024HandlerError> {
    match (dispatch, close) {
        (Ok(value), Ok(())) => Ok(value),
        (Err(dispatch_error), Ok(())) => Err(dispatch_error),
        (Ok(_), Err(close_error)) => Err(close_error),
        (Err(dispatch_error), Err(close_error)) => Err(Legacy2024HandlerError::with_code(
            dispatch_error.code().clone(),
            format!("{}; {}", dispatch_error.message(), close_error.message()),
        )),
    }
}

#[cfg(feature = "legacy-2024-11-05")]
impl Legacy2024Handler for LiveLegacy2024RuntimeHandler<'_> {
    fn handle_legacy_2024(
        &mut self,
        method: &'static str,
        params: Option<&serde_json::Value>,
    ) -> Result<serde_json::Value, Legacy2024HandlerError> {
        self.handle_legacy_2024_with_request_id(&serde_json::json!(0), method, params)
    }

    fn handle_legacy_2024_with_request_id(
        &mut self,
        _request_id: &serde_json::Value,
        _method: &'static str,
        _params: Option<&serde_json::Value>,
    ) -> Result<serde_json::Value, Legacy2024HandlerError> {
        Err(live_legacy_sync_dispatch_refused())
    }

    fn handle_legacy_2024_with_request_id_async<'a>(
        &'a mut self,
        request_id: &'a serde_json::Value,
        method: &'static str,
        params: Option<&'a serde_json::Value>,
    ) -> BoxFuture<'a, Result<serde_json::Value, Legacy2024HandlerError>> {
        Box::pin(async move {
            let request_id =
                serde_json::from_value::<RequestId>(request_id.clone()).map_err(|_| {
                    Legacy2024HandlerError::new("legacy adapter supplied an invalid request ID")
                })?;
            let request_cancellation = self
                .queue_state
                .as_ref()
                .and_then(|queue| queue.admitted_request_cancellation(&request_id));
            let request = JsonRpcRequest::new(method, params.cloned(), request_id.clone());
            // Exact-2024 custom transports are intentionally serial at the
            // wire boundary, but each admitted request still needs its own
            // structured cancellation owner. Without this child region the
            // active-request registry records the caller/pump region for
            // every request, so request shutdown and sibling reuse share one
            // ownership domain.
            let request_budget = self.server.create_request_budget(&self.cx);
            let request_region = self
                .cx
                .open_child_region(ChildRegionSpec::inherit().with_budget(request_budget))
                .await
                .map_err(|_| {
                    Legacy2024HandlerError::new("legacy request region could not be opened")
                })?;
            let request_cx = request_region.cx().clone();
            let dispatch = self
                .server
                .dispatch_legacy_2024(
                    &request_cx,
                    self.session_id,
                    &self.session_principal,
                    Some(&self.runtime),
                    request_cancellation,
                    &request,
                    None,
                    self.connection_auth.as_ref(),
                )
                .await
                .map_err(|error| {
                    legacy_handler_error_from_mcp(error, self.server.mask_error_details)
                });
            let close_result = request_region
                .close()
                .await
                .map_err(|_| Legacy2024HandlerError::new("legacy request region close failed"));
            let dispatch = combine_legacy_dispatch_and_close(dispatch, close_result)?;
            let LiveLegacy2024Dispatch {
                result,
                active_request,
            } = dispatch;
            let mut retained = self
                .active_request
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if retained.is_some() {
                return Err(Legacy2024HandlerError::new(
                    "legacy runtime attempted to overlap exact request finalization",
                ));
            }
            *retained = Some(active_request);
            drop(retained);
            result.map_err(|error| {
                legacy_handler_error_from_mcp(error, self.server.mask_error_details)
            })
        })
    }
}

/// Owns a server reference for an exact-2024 HTTP session. The session updates
/// the request context before every adapter call, while the adapter retains the
/// lifecycle and original wire identity across independent HTTP requests.
#[cfg(feature = "legacy-2024-11-05")]
struct HttpLegacy2024RuntimeHandler {
    server: Arc<Server>,
    session_id: u64,
    session_principal: SessionPrincipalBinding,
    active_request: Arc<Mutex<Option<LiveLegacy2024ActiveRequest>>>,
    request_cx: Arc<Mutex<Cx>>,
    runtime: LiveLegacy2024ConnectionRuntime,
    /// The live HTTP connection admits a correlated request before waiting
    /// for the session mutex. Reusing that authority here closes the gap
    /// between a separate cancellation POST and active-request registration.
    legacy_admissions: Arc<HttpLegacyRequestAdmissions>,
    /// Native HTTP admission receipt for the in-flight exact-2024 POST.
    auth_receipt: Arc<Mutex<Option<AuthAdmissionReceipt>>>,
}

#[cfg(feature = "legacy-2024-11-05")]
impl Legacy2024Handler for HttpLegacy2024RuntimeHandler {
    fn handle_legacy_2024(
        &mut self,
        method: &'static str,
        params: Option<&serde_json::Value>,
    ) -> Result<serde_json::Value, Legacy2024HandlerError> {
        self.handle_legacy_2024_with_request_id(&serde_json::json!(0), method, params)
    }

    fn handle_legacy_2024_with_request_id(
        &mut self,
        _request_id: &serde_json::Value,
        _method: &'static str,
        _params: Option<&serde_json::Value>,
    ) -> Result<serde_json::Value, Legacy2024HandlerError> {
        Err(live_legacy_sync_dispatch_refused())
    }

    fn handle_legacy_2024_with_request_id_async<'a>(
        &'a mut self,
        request_id: &'a serde_json::Value,
        method: &'static str,
        params: Option<&'a serde_json::Value>,
    ) -> BoxFuture<'a, Result<serde_json::Value, Legacy2024HandlerError>> {
        Box::pin(async move {
            let request_id =
                serde_json::from_value::<RequestId>(request_id.clone()).map_err(|_| {
                    Legacy2024HandlerError::new("legacy adapter supplied an invalid request ID")
                })?;
            let request = JsonRpcRequest::new(method, params.cloned(), request_id.clone());
            let request_cx = self
                .request_cx
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .clone();
            let request_cancellation = self
                .legacy_admissions
                .admitted_request_cancellation(&request_id);
            let auth_receipt = self
                .auth_receipt
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .take();
            let dispatch = self
                .server
                .dispatch_legacy_2024(
                    &request_cx,
                    self.session_id,
                    &self.session_principal,
                    Some(&self.runtime),
                    request_cancellation,
                    &request,
                    auth_receipt.as_ref(),
                    None,
                )
                .await
                .map_err(|error| {
                    legacy_handler_error_from_mcp(error, self.server.mask_error_details)
                })?;
            let LiveLegacy2024Dispatch {
                result,
                active_request,
            } = dispatch;
            let mut retained = self
                .active_request
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if retained.is_some() {
                return Err(Legacy2024HandlerError::new(
                    "legacy runtime attempted to overlap exact request finalization",
                ));
            }
            *retained = Some(active_request);
            drop(retained);
            result.map_err(|error| {
                legacy_handler_error_from_mcp(error, self.server.mask_error_details)
            })
        })
    }
}

fn final_client_extension_discovery(
    request: &JsonRpcRequest,
) -> McpResult<ClientExtensionDiscovery> {
    let Some(params) = request.params.as_ref() else {
        return Ok(ClientExtensionDiscovery::default());
    };
    let Some(parameters) = params.as_object() else {
        return Err(McpError::invalid_params(
            "Invalid final client extension capabilities",
        ));
    };
    let Some(metadata) = parameters.get("_meta") else {
        return Ok(ClientExtensionDiscovery::default());
    };
    let Some(metadata) = metadata.as_object() else {
        return Err(McpError::invalid_params(
            "Invalid final client extension capabilities",
        ));
    };
    let Some(capabilities) = metadata.get(FINAL_CLIENT_CAPABILITIES_META_KEY) else {
        return Ok(ClientExtensionDiscovery::default());
    };
    let Some(capabilities) = capabilities.as_object() else {
        return Err(McpError::invalid_params(
            "Invalid final client extension capabilities",
        ));
    };
    let Some(extensions) = capabilities.get("extensions") else {
        return Ok(ClientExtensionDiscovery::default());
    };
    let Some(extensions) = extensions.as_object() else {
        return Err(McpError::invalid_params(
            "Invalid final client extension capabilities",
        ));
    };

    let mut parsed = BTreeMap::new();
    for (raw_id, raw_settings) in extensions {
        let id = ExtensionId::parse(raw_id.clone())
            .map_err(|_| McpError::invalid_params("Invalid final client extension capabilities"))?;
        let settings = ExtensionSettings::new(raw_settings.clone())
            .map_err(|_| McpError::invalid_params("Invalid final client extension capabilities"))?;
        parsed.insert(id, settings);
    }
    Ok(ClientExtensionDiscovery { extensions: parsed })
}

fn require_exact_modern_extension_metadata(request: &JsonRpcRequest) -> McpResult<()> {
    if modern_protocol_version(request) == Some(MODERN_PROTOCOL_VERSION) {
        Ok(())
    } else {
        Err(McpError::invalid_request(
            "Extension requests require the admitted MCP 2026-07-28 protocol version",
        ))
    }
}

#[derive(Default)]
struct DispatchRequestByteCounter {
    bytes: usize,
}

impl Write for DispatchRequestByteCounter {
    fn write(&mut self, buffer: &[u8]) -> std::io::Result<usize> {
        let prospective = self
            .bytes
            .checked_add(buffer.len())
            .ok_or_else(|| std::io::Error::other(DISPATCH_QUEUE_CAPACITY_MESSAGE))?;
        if prospective > MAX_DISPATCH_QUEUE_BYTES {
            return Err(std::io::Error::other(DISPATCH_QUEUE_CAPACITY_MESSAGE));
        }
        self.bytes = prospective;
        Ok(buffer.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

fn measure_dispatch_request(request: &JsonRpcRequest) -> Option<usize> {
    let mut counter = DispatchRequestByteCounter::default();
    serde_json::to_writer(&mut counter, request)
        .ok()
        .map(|()| counter.bytes)
}

const MODERN_PROTOCOL_VERSION_METADATA_KEY: &str = "io.modelcontextprotocol/protocolVersion";

fn modern_protocol_version(request: &JsonRpcRequest) -> Option<&str> {
    request
        .params
        .as_ref()?
        .get("_meta")?
        .get(MODERN_PROTOCOL_VERSION_METADATA_KEY)?
        .as_str()
}

/// Decodes an active final core request before middleware can short-circuit
/// normal dispatch. Unknown methods remain eligible for extension fallback.
fn decode_final_core_request_for_middleware(
    request: &JsonRpcRequest,
) -> McpResult<Option<CoreRequest>> {
    if request.id.is_none() || final_2026_07_28_method(&request.method).is_none() {
        return Ok(None);
    }

    CoreRequest::decode(
        ProtocolEra::Modern2026,
        &request.method,
        request.params.as_ref(),
    )
    .map(Some)
    .map_err(|error| McpError::invalid_params(error.to_string()))
}

/// Admits the sole client-originated final notification before an ID-less
/// registered final frame can enter authentication or application dispatch.
///
/// Final registry membership is intentionally checked first: extension
/// notifications remain eligible for their registered extension path, while a
/// final request missing its id and every server-originated final notification
/// is rejected by the typed client union.
fn admit_final_client_notification_ingress(request: &JsonRpcRequest) -> McpResult<()> {
    if request.id.is_some() || final_2026_07_28_method(&request.method).is_none() {
        return Ok(());
    }

    ClientNotification::decode(request)
        .map(|_| ())
        .map_err(|error| McpError::invalid_request(error.to_string()))
}

/// Rejects a final client-forbidden notification from raw native-HTTP input
/// before strict POST admission rejects its missing request id.  That keeps
/// HTTP on the same typed direction authority as stateful transports without
/// treating an untyped malformed document as a notification.
fn rejects_final_client_notification_http_ingress(body: &[u8], document_byte_limit: usize) -> bool {
    JsonRpcRequest::decode_strict_with_raw_params(body, document_byte_limit)
        .is_ok_and(|(request, _)| admit_final_client_notification_ingress(&request).is_err())
}

/// Projects admitted final client capabilities into the handler context.
///
/// Final handlers use the context capability view to decide whether an
/// embedded MRTR input may be emitted. This is intentionally independent of
/// legacy reverse-request senders: final elicitation is carried by the
/// router-owned `input_required` registry, not by a server-to-client request.
fn admitted_final_client_capability_info(
    request: Option<&CoreRequest>,
) -> McpResult<Option<ClientCapabilityInfo>> {
    let Some(CoreRequest::Final(request)) = request else {
        return Ok(None);
    };
    let metadata = match request {
        FinalCoreRequest::Discover(params) => &params.meta,
        FinalCoreRequest::Completion(params) => &params.meta,
        FinalCoreRequest::ToolsList(params)
        | FinalCoreRequest::ResourcesList(params)
        | FinalCoreRequest::ResourceTemplatesList(params)
        | FinalCoreRequest::PromptsList(params) => &params.meta,
        FinalCoreRequest::ToolsCall(params) => &params.meta,
        FinalCoreRequest::ResourcesRead(params) => &params.meta,
        FinalCoreRequest::PromptsGet(params) => &params.meta,
        FinalCoreRequest::SubscriptionsListen(params) => &params.meta,
    };
    let capability_members = metadata
        .client_capabilities()
        .map_err(|error| McpError::invalid_params(error.to_string()))?
        .ok_or_else(|| McpError::invalid_params("final client capabilities are required"))?
        .clone();
    #[cfg(feature = "tasks")]
    let supports_tasks = capability_members
        .get("extensions")
        .and_then(serde_json::Value::as_object)
        .and_then(|extensions| extensions.get(fastmcp_protocol::TASKS_EXTENSION))
        .and_then(serde_json::Value::as_object)
        .is_some_and(serde_json::Map::is_empty);
    let capability_value = serde_json::Value::Object(capability_members);
    let capabilities: ClientCapabilities = serde_json::from_value(capability_value)
        .map_err(|error| McpError::invalid_params(error.to_string()))?;
    let (elicitation_form, elicitation_url) = capabilities
        .elicitation
        .as_ref()
        .map_or((false, false), |elicitation| {
            (elicitation.supports_form(), elicitation.supports_url())
        });
    let capability_info =
        ClientCapabilityInfo::new().with_elicitation(elicitation_form, elicitation_url);
    let capability_info = if capabilities.sampling.is_some() {
        capability_info.with_sampling()
    } else {
        capability_info
    };
    let capability_info = match capabilities.roots.as_ref() {
        Some(roots) => capability_info.with_roots(roots.list_changed),
        None => capability_info,
    };
    #[cfg(feature = "tasks")]
    let capability_info = if supports_tasks {
        capability_info.with_tasks()
    } else {
        capability_info
    };
    Ok(Some(capability_info))
}

fn admitted_final_client_implementation(
    request: Option<&CoreRequest>,
) -> McpResult<Option<fastmcp_core::ClientImplementationInfo>> {
    let Some(CoreRequest::Final(request)) = request else {
        return Ok(None);
    };
    let metadata = match request {
        FinalCoreRequest::Discover(params) => &params.meta,
        FinalCoreRequest::Completion(params) => &params.meta,
        FinalCoreRequest::ToolsList(params)
        | FinalCoreRequest::ResourcesList(params)
        | FinalCoreRequest::ResourceTemplatesList(params)
        | FinalCoreRequest::PromptsList(params) => &params.meta,
        FinalCoreRequest::ToolsCall(params) => &params.meta,
        FinalCoreRequest::ResourcesRead(params) => &params.meta,
        FinalCoreRequest::PromptsGet(params) => &params.meta,
        FinalCoreRequest::SubscriptionsListen(params) => &params.meta,
    };
    let Some(implementation) = metadata
        .client_info()
        .map_err(|error| McpError::invalid_params(error.to_string()))?
    else {
        return Ok(None);
    };
    Ok(Some(fastmcp_core::ClientImplementationInfo {
        name: implementation.name,
        version: implementation.version,
        title: implementation.title,
        description: implementation.description,
        website_url: implementation
            .website_url
            .map(|uri| uri.as_str().to_owned()),
        icon_sources: implementation
            .icons
            .iter()
            .map(|icon| icon.src.as_str().to_owned())
            .collect(),
    }))
}

/// A raw parameter sidecar is usable only while authentication and admission
/// have left the materialized parameter value untouched.  In particular,
/// stripping a recognized credential must sever the raw source before router
/// MRTR decoding can observe it.  The sidecar was admitted as the source of
/// `admitted`, so comparing that value with the current one replaces decoding
/// the source again; final core decoding still verifies the source against
/// the value it receives.
fn retained_raw_params<'a>(
    raw_params: Option<&'a str>,
    admitted: Option<&serde_json::Value>,
    current: Option<&serde_json::Value>,
) -> Option<&'a str> {
    raw_params.filter(|_| admitted == current)
}

/// Re-admits a middleware-produced final core response through the request's
/// exact result algebra and returns its canonical wire representation.
/// A response-cache hit may complete a final core method. Arbitrary
/// middleware still cannot invent a typed final result. Only the sealed
/// continuation replay journal may also answer with the router-minted
/// `input_required` reply it captured, and only with a nonempty requestState.
fn middleware_may_complete_final_core_from_cache(
    ctx: &McpContext,
    middleware: &dyn crate::Middleware,
    value: &serde_json::Value,
) -> bool {
    if !ctx.response_was_served_from_cache() {
        return false;
    }
    match value.get("resultType").and_then(serde_json::Value::as_str) {
        Some("complete") => true,
        Some("input_required") => {
            middleware.replays_router_minted_continuation(crate::middleware::seal::Sealed)
                && value
                    .get("requestState")
                    .and_then(serde_json::Value::as_str)
                    .is_some_and(|state| !state.is_empty())
        }
        _ => false,
    }
}

fn validate_final_core_middleware_response(
    core_request: Option<&CoreRequest>,
    request: &JsonRpcRequest,
    value: serde_json::Value,
) -> McpResult<serde_json::Value> {
    let Some(core_request) = core_request else {
        return Ok(value);
    };

    if core_request.method() != SERVER_DISCOVER_METHOD && value.get("resultType").is_none() {
        return Err(McpError::internal_error(
            "middleware response omits the required final result discriminator",
        ));
    }

    let response_id = request.id.clone().ok_or_else(|| {
        McpError::internal_error("final core middleware response is missing a request id")
    })?;
    let response = JsonRpcResponse::success(response_id, value);
    let result = core_request.decode_response(&response).map_err(|_| {
        McpError::internal_error("middleware response violates the final result contract")
    })?;
    let encoded = result.encode().map_err(|_| {
        McpError::internal_error("middleware response violates the final result contract")
    })?;
    serde_json::from_str(&encoded).map_err(McpError::from)
}

/// Captures server-owned final metadata before response middleware receives a
/// core response. Unknown methods deliberately have no core seal.
fn final_core_middleware_metadata_seal(
    core_request: Option<&CoreRequest>,
    request: &JsonRpcRequest,
    value: &serde_json::Value,
) -> McpResult<Option<FinalResultMetadataSeal>> {
    let Some(core_request) = core_request else {
        return Ok(None);
    };
    let response_id = request.id.clone().ok_or_else(|| {
        McpError::internal_error("final core middleware response is missing a request id")
    })?;
    let response = JsonRpcResponse::success(response_id, value.clone());
    let CoreResult::Final(result) = core_request.decode_response(&response).map_err(|_| {
        McpError::internal_error("middleware response violates the final result contract")
    })?
    else {
        return Err(McpError::internal_error(
            "final core middleware response selected a non-final result",
        ));
    };
    result
        .protected_metadata_seal()
        .map(Some)
        .map_err(|_| McpError::internal_error("middleware response violates final metadata"))
}

/// Rejects middleware changes to server-owned final response metadata while
/// leaving every open metadata entry available for ordinary middleware use.
fn validate_final_core_middleware_metadata_seal(
    expected: Option<&FinalResultMetadataSeal>,
    core_request: Option<&CoreRequest>,
    request: &JsonRpcRequest,
    value: &serde_json::Value,
) -> McpResult<()> {
    let Some(expected) = expected else {
        return Ok(());
    };
    let actual = final_core_middleware_metadata_seal(core_request, request, value)?
        .ok_or_else(|| McpError::internal_error("final core middleware metadata seal is absent"))?;
    if &actual != expected {
        return Err(McpError::internal_error(
            "middleware changed protected final response metadata",
        ));
    }
    Ok(())
}

fn stdio_opening_frame(request: &JsonRpcRequest) -> StdioOpeningFrame {
    if let Some(protocol_version) = modern_protocol_version(request) {
        return if request.method == "initialize" {
            StdioOpeningFrame::MixedInitializeAndModernMetadata {
                protocol_version: protocol_version.to_owned(),
            }
        } else {
            StdioOpeningFrame::ModernRequest {
                protocol_version: protocol_version.to_owned(),
            }
        };
    }

    if request.id.is_none() {
        return StdioOpeningFrame::Notification;
    }

    // The proposed version is negotiated by initialize, not an era marker.
    // Modern metadata was checked above; malformed params belong to dispatch.
    if request.method == "initialize" {
        StdioOpeningFrame::LegacyInitialize
    } else {
        StdioOpeningFrame::RequestWithoutModernMetadata
    }
}

/// Classifies the first complete stdio envelope before any envelope-specific
/// side effect can run. Auto selection is one-shot: a response, an invalid
/// request, or a notification without final metadata is a terminal opening
/// rejection rather than a frame the pump may ignore and retry after.
fn classify_initial_stdio_envelope(
    classifier: &mut StdioEraClassifier,
    message: &JsonRpcMessage,
) -> Result<ProtocolEra, StdioEraDecision> {
    let opening = match message {
        JsonRpcMessage::Response(_) => StdioOpeningFrame::Response,
        JsonRpcMessage::Request(request) if request.validate().is_err() => {
            StdioOpeningFrame::Malformed
        }
        JsonRpcMessage::Request(request) => stdio_opening_frame(request),
    };
    let decision = classifier.classify_opening(opening);
    #[cfg(not(feature = "legacy-2024-11-05"))]
    if matches!(
        &decision,
        StdioEraDecision::Selected {
            era: ProtocolEra::Legacy2024,
            ..
        }
    ) {
        // No-legacy profiles must reject at the envelope boundary, before an
        // adapter, session, request authority, or handler can be installed.
        return Err(decision);
    }
    match decision {
        StdioEraDecision::Selected {
            era: ProtocolEra::Modern2026,
            modern_version: Some(ModernVersionSupport::Supported),
        } => Ok(ProtocolEra::Modern2026),
        StdioEraDecision::Selected {
            era: ProtocolEra::Legacy2024,
            modern_version: None,
        } => Ok(ProtocolEra::Legacy2024),
        decision => Err(decision),
    }
}

/// Preserves the configured runtime classifier policy.
///
/// A no-legacy build rejects an exact legacy selection at the envelope
/// boundary in [`classify_initial_stdio_envelope`]. It must not silently turn
/// `LegacyOnly` into `ModernOnly`: the former is an unavailable configuration,
/// while the latter is an explicit final-era admission policy.
fn runtime_stdio_policy(policy: ProtocolPolicy) -> ProtocolPolicy {
    policy
}

/// Rejects a malformed receive failure as an Auto connection's terminal
/// opening frame. Later malformed frames retain ordinary JSON-RPC recovery
/// behavior because their era was already selected.
#[cfg(feature = "legacy-2024-11-05")]
fn reject_initial_stdio_malformed(classifier: &mut StdioEraClassifier) -> StdioEraDecision {
    classifier.classify_opening(StdioOpeningFrame::Malformed)
}

#[cfg(feature = "legacy-2024-11-05")]
fn runtime_legacy_binding(generation: u64) -> LegacyPeerBinding {
    let mut partition = [0_u8; LegacyAuthenticatedPeerPartition::BYTE_LEN];
    partition[..8].copy_from_slice(&generation.to_be_bytes());
    partition[8..16].copy_from_slice(&(!generation).to_be_bytes());
    LegacyPeerBinding::from_authenticated_transport(
        LegacyAuthenticatedPeerPartition::from_authenticated_transport(partition),
        generation,
    )
}

/// Polls `future` on `cx` instead of the process-global `block_on` runtime.
///
/// Stdio workers and sequential pumps already own a request/connection `Cx`.
/// Driving the handler future here keeps cancellation, budget, and nested
/// `ctx.call_tool` / `ctx.read_resource` on that same context. A 1ms park
/// timeout is the same bound the multiplexed worker already uses for an
/// empty dispatch queue, so a missed wake cannot deadlock the pump.
fn poll_on_cx<F: Future>(cx: &Cx, future: F) -> F::Output {
    use std::task::{Context as TaskContext, Poll, Wake, Waker};

    struct ThreadWake(std::thread::Thread);

    impl Wake for ThreadWake {
        fn wake(self: Arc<Self>) {
            self.0.unpark();
        }

        fn wake_by_ref(self: &Arc<Self>) {
            self.0.unpark();
        }
    }

    let _guard = Cx::set_current(Some(cx.clone()));
    let waker = Waker::from(Arc::new(ThreadWake(std::thread::current())));
    let mut task_cx = TaskContext::from_waker(&waker);
    let mut future = std::pin::pin!(future);
    loop {
        if let Poll::Ready(output) = future.as_mut().poll(&mut task_cx) {
            return output;
        }
        if cx.is_cancel_requested()
            && let Poll::Ready(output) = future.as_mut().poll(&mut task_cx)
        {
            return output;
        }
        std::thread::park_timeout(Duration::from_millis(1));
    }
}

/// Establishes or verifies the connection owner at an ordinary request's
/// admission boundary.
///
/// The live stdio/WebSocket modern path and the exact-2024 adapter both commit
/// anonymous request authentication internally. Binding that same principal
/// before queue hand-off lets a following control notification prove ownership
/// even when it races the first request's dispatch. Cancellation itself still
/// uses `verify_existing`, so a control frame can never claim an unbound
/// connection.
#[cfg(feature = "legacy-2024-11-05")]
fn bind_anonymous_connection_principal(
    principal_binding: &SessionPrincipalBinding,
) -> McpResult<()> {
    bind_connection_principal(principal_binding, auth::principal_fingerprint(None)?)
}

#[cfg(feature = "legacy-2024-11-05")]
fn bind_connection_principal(
    principal_binding: &SessionPrincipalBinding,
    fingerprint: Sha256Digest,
) -> McpResult<()> {
    if principal_binding.bind_or_verify(fingerprint) {
        Ok(())
    } else {
        Err(McpError::new(
            McpErrorCode::ResourceForbidden,
            "Authenticated principal does not own this session",
        ))
    }
}

#[cfg(feature = "legacy-2024-11-05")]
async fn legacy_adapter_response_async<H: Legacy2024Handler>(
    adapter: &mut Legacy2024ServerAdapter<H>,
    binding: LegacyPeerBinding,
    request: &JsonRpcRequest,
) -> Result<Option<JsonRpcResponse>, Legacy2024AdapterError> {
    let wire = serde_json::to_value(request)
        .expect("a validated JSON-RPC request must serialize for the legacy adapter");
    match adapter.receive_async(binding, wire).await? {
        Legacy2024Outbound::Response(response) => {
            let response = serde_json::from_value(response)
                .expect("the legacy adapter must emit a valid JSON-RPC response");
            Ok(Some(response))
        }
        Legacy2024Outbound::NoResponse => Ok(None),
        Legacy2024Outbound::ReverseRequest(_) | Legacy2024Outbound::ReverseNotification(_) => {
            unreachable!("receiving a client frame cannot create a legacy reverse frame")
        }
    }
}

#[cfg(feature = "legacy-2024-11-05")]
fn sync_live_legacy_runtime_from_adapter<H: Legacy2024Handler>(
    runtime: &LiveLegacy2024ConnectionRuntime,
    adapter: &Legacy2024ServerAdapter<H>,
) {
    runtime.sync_from_adapter_snapshot(&adapter.snapshot());
    *runtime
        .client_info
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner) = adapter.client_info().cloned();
}

/// Applies an exact legacy client response to the adapter that allocated its
/// reverse-request ID. A response cannot produce peer output, so any other
/// adapter result is a protocol failure.
#[cfg(feature = "legacy-2024-11-05")]
fn legacy_adapter_accept_response<H: Legacy2024Handler>(
    adapter: &mut Legacy2024ServerAdapter<H>,
    binding: LegacyPeerBinding,
    response: &JsonRpcResponse,
) -> bool {
    let wire = match serde_json::to_value(response) {
        Ok(wire) => wire,
        Err(_) => return false,
    };
    matches!(
        adapter.receive(binding, wire),
        Ok(Legacy2024Outbound::NoResponse)
    )
}

#[cfg(feature = "legacy-2024-11-05")]
fn take_live_legacy_active_request(
    active_request: &Arc<Mutex<Option<LiveLegacy2024ActiveRequest>>>,
) -> Option<LiveLegacy2024ActiveRequest> {
    active_request
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .take()
}

#[cfg(feature = "legacy-2024-11-05")]
fn legacy_handled_response(
    response: JsonRpcResponse,
    active_request: Option<LiveLegacy2024ActiveRequest>,
    cx: &Cx,
) -> HandledRequest {
    match active_request {
        Some(LiveLegacy2024ActiveRequest {
            cancellation,
            active_guard,
            budget,
        }) => HandledRequest::tracked(
            response,
            cancellation,
            Some(active_guard),
            None,
            cx.clone(),
            budget,
        )
        .suppress_cancelled_response(),
        None => HandledRequest::untracked(response),
    }
}

fn remove_modern_protocol_metadata(request: &mut JsonRpcRequest) {
    let Some(params) = request.params.as_mut() else {
        return;
    };
    let Some(params) = params.as_object_mut() else {
        return;
    };
    let remove_meta = params
        .get_mut("_meta")
        .and_then(serde_json::Value::as_object_mut)
        .is_some_and(|metadata| {
            metadata.remove(MODERN_PROTOCOL_VERSION_METADATA_KEY);
            metadata.is_empty()
        });
    if remove_meta {
        params.remove("_meta");
    }
}

fn protocol_era_refusal(request: &JsonRpcRequest) -> Option<JsonRpcResponse> {
    request.id.clone().map(|id| {
        JsonRpcResponse::error(
            Some(id),
            JsonRpcError {
                code: McpErrorCode::InvalidRequest.into(),
                message: "Request does not match the connection's negotiated MCP protocol era"
                    .to_owned(),
                data: Some(serde_json::json!({
                    "supported": [MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION],
                })),
            },
        )
    })
}

/// Methods MCP 2026-07-28 removed. On a modern connection they are unknown
/// methods (`-32601`), never era-selection signals.
fn is_removed_legacy_method(method: &str) -> bool {
    matches!(
        method,
        "initialize"
            | "ping"
            | "logging/setLevel"
            | "resources/subscribe"
            | "resources/unsubscribe"
    )
}

/// Stateless per-request refusal for a request on a modern stdio connection
/// that does not carry exact MCP 2026-07-28 metadata.
///
/// Every modern request is admitted on its own `_meta` (SEP-2575), so one
/// invalid request is answered and the connection keeps serving: an
/// unsupported version is `-32022` with the supported list, a removed method
/// is `-32601`, and a request missing the required protocol version is
/// `-32602`. Notifications receive no response.
fn modern_request_version_refusal(request: &JsonRpcRequest) -> Option<JsonRpcResponse> {
    let id = request.id.clone()?;
    let error = match modern_protocol_version(request) {
        Some(requested) => JsonRpcError {
            code: fastmcp_protocol::UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE.into(),
            message: "Unsupported MCP protocol version".to_owned(),
            data: Some(serde_json::json!({
                "supported": fastmcp_protocol::SUPPORTED_FINAL_PROTOCOL_VERSIONS,
                "requested": requested,
            })),
        },
        None if is_removed_legacy_method(&request.method) => JsonRpcError {
            code: McpErrorCode::MethodNotFound.into(),
            message: "Method not found".to_owned(),
            data: None,
        },
        None => JsonRpcError {
            code: McpErrorCode::InvalidParams.into(),
            message: format!(
                "Invalid params: request _meta must carry {MODERN_PROTOCOL_VERSION_METADATA_KEY}"
            ),
            data: None,
        },
    };
    Some(JsonRpcResponse::error(Some(id), error))
}

/// Whether an opening-frame rejection left the connection in the modern era.
///
/// `ModernOnly` fixes the era before the first frame, and `Auto` selects it
/// from a modern request even when that request names an unsupported
/// version. In both cases the rejected frame is answered statelessly instead
/// of ending the connection.
fn opening_rejection_selected_modern(decision: &StdioEraDecision) -> bool {
    matches!(
        decision,
        StdioEraDecision::Selected {
            era: ProtocolEra::Modern2026,
            modern_version: Some(ModernVersionSupport::Unsupported { .. }),
        } | StdioEraDecision::RejectedUnderSelectedEra {
            era: ProtocolEra::Modern2026,
            ..
        }
    )
}

/// `-32601` refusal for a modern request that reaches a `LegacyOnly` policy.
fn legacy_only_modern_refusal(request: &JsonRpcRequest) -> Option<JsonRpcResponse> {
    request.id.clone().map(|id| {
        JsonRpcResponse::error(
            Some(id),
            JsonRpcError {
                code: (-32601).into(),
                message: LEGACY_ONLY_MODERN_MESSAGE.to_owned(),
                data: Some(serde_json::json!({ "supported": [LEGACY_PROTOCOL_VERSION] })),
            },
        )
    })
}

/// Selects the refusal shape for a request that failed era admission:
/// a modern request under `LegacyOnly` is a method-not-found style typed
/// refusal, every other mismatch is the negotiated-era `-32600` refusal.
#[cfg(feature = "legacy-2024-11-05")]
fn era_admission_refusal(
    policy: ProtocolPolicy,
    request: &JsonRpcRequest,
) -> Option<JsonRpcResponse> {
    if matches!(policy, ProtocolPolicy::LegacyOnly) && modern_protocol_version(request).is_some() {
        return legacy_only_modern_refusal(request);
    }
    protocol_era_refusal(request)
}

// Exact-2024 era: era_admission_refusal serves only the dual-era loop.
#[cfg(all(test, feature = "legacy-2024-11-05"))]
mod era_admission_refusal_tests {
    use super::*;

    fn modern_discover() -> JsonRpcRequest {
        JsonRpcRequest::new(
            "server/discover",
            Some(serde_json::json!({
                "_meta": {
                    fastmcp_protocol::FINAL_PROTOCOL_VERSION_META_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                }
            })),
            7,
        )
    }

    fn legacy_initialize() -> JsonRpcRequest {
        JsonRpcRequest::new(
            "initialize",
            Some(serde_json::json!({
                "protocolVersion": LEGACY_PROTOCOL_VERSION,
                "capabilities": {},
                "clientInfo": {"name": "probe", "version": "1"},
            })),
            7,
        )
    }

    fn refusal(policy: ProtocolPolicy, request: &JsonRpcRequest) -> JsonRpcError {
        era_admission_refusal(policy, request)
            .expect("an id-bearing request receives a refusal response")
            .error
            .expect("the refusal is a JSON-RPC error")
    }

    /// Positive: a modern probe against `LegacyOnly` is the typed `-32601`
    /// signal the Auto stdio client admits as a legacy refusal.
    #[test]
    fn legacy_only_refuses_a_modern_probe_with_method_not_found() {
        let error = refusal(ProtocolPolicy::LegacyOnly, &modern_discover());
        assert_eq!(error.code, fastmcp_protocol::JsonInteger::from(-32601));
        assert_eq!(error.message, LEGACY_ONLY_MODERN_MESSAGE);
        assert_eq!(
            error.data,
            Some(serde_json::json!({ "supported": [LEGACY_PROTOCOL_VERSION] }))
        );
    }

    /// Planted negative (policy differs): the same probe on an Auto
    /// connection that already failed era admission keeps the negotiated-era
    /// `-32600` refusal.
    #[test]
    fn auto_keeps_the_negotiated_era_refusal_for_a_modern_probe() {
        let error = refusal(ProtocolPolicy::Auto, &modern_discover());
        assert_eq!(error.code, fastmcp_protocol::JsonInteger::from(-32600));
        assert_eq!(
            error.data,
            Some(serde_json::json!({
                "supported": [MODERN_PROTOCOL_VERSION, LEGACY_PROTOCOL_VERSION],
            }))
        );
    }

    /// Planted negative (request differs): a legacy-shaped request that
    /// fails admission under `LegacyOnly` is not a modern method and keeps
    /// the `-32600` refusal.
    #[test]
    fn legacy_only_keeps_the_negotiated_era_refusal_for_a_legacy_request() {
        let error = refusal(ProtocolPolicy::LegacyOnly, &legacy_initialize());
        assert_eq!(error.code, fastmcp_protocol::JsonInteger::from(-32600));
        assert_ne!(error.message, LEGACY_ONLY_MODERN_MESSAGE);
    }

    /// A notification (no id) never receives a refusal response.
    #[test]
    fn notifications_receive_no_refusal_response() {
        let mut request = modern_discover();
        request.id = None;
        assert!(era_admission_refusal(ProtocolPolicy::LegacyOnly, &request).is_none());
    }
}

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

    fn request(method: &str, meta: Option<serde_json::Value>) -> JsonRpcRequest {
        let mut params = serde_json::json!({});
        if let Some(meta) = meta {
            params["_meta"] = meta;
        }
        JsonRpcRequest::new(method, Some(params), 7_i64)
    }

    fn meta(version: &str) -> serde_json::Value {
        serde_json::json!({
            MODERN_PROTOCOL_VERSION_METADATA_KEY: version,
            "io.modelcontextprotocol/clientCapabilities": {},
        })
    }

    fn refusal_error(request: &JsonRpcRequest) -> JsonRpcError {
        let response =
            modern_request_version_refusal(request).expect("a request receives a refusal");
        assert_eq!(response.id, request.id, "a refusal echoes the request id");
        response.error.expect("a refusal is a JSON-RPC error")
    }

    #[test]
    fn unsupported_version_gets_the_official_unsupported_version_shape() {
        let error = refusal_error(&request("tools/list", Some(meta("2099-01-01"))));
        assert_eq!(error.code, fastmcp_protocol::JsonInteger::from(-32022));
        assert_eq!(
            error.data,
            Some(serde_json::json!({
                "supported": [MODERN_PROTOCOL_VERSION],
                "requested": "2099-01-01",
            }))
        );
    }

    #[test]
    fn missing_protocol_version_is_invalid_params() {
        let without_meta = request("tools/list", None);
        let without_version = request(
            "tools/list",
            Some(serde_json::json!({"io.modelcontextprotocol/clientCapabilities": {}})),
        );
        for request in [without_meta, without_version] {
            assert_eq!(
                refusal_error(&request).code,
                fastmcp_protocol::JsonInteger::from(-32602)
            );
        }
    }

    #[test]
    fn removed_methods_are_method_not_found_not_invalid_params() {
        for method in [
            "initialize",
            "ping",
            "logging/setLevel",
            "resources/subscribe",
            "resources/unsubscribe",
        ] {
            assert_eq!(
                refusal_error(&request(method, None)).code,
                fastmcp_protocol::JsonInteger::from(-32601),
                "{method} was removed in MCP 2026-07-28"
            );
        }
        // Planted negative: a current method without metadata stays -32602.
        assert_eq!(
            refusal_error(&request("server/discover", None)).code,
            fastmcp_protocol::JsonInteger::from(-32602)
        );
    }

    #[test]
    fn notifications_receive_no_response() {
        let mut notification = request("notifications/cancelled", None);
        notification.id = None;
        assert!(modern_request_version_refusal(&notification).is_none());
    }

    #[test]
    fn only_modern_selecting_opening_rejections_keep_the_connection() {
        let mut modern_only = StdioEraClassifier::new(ProtocolPolicy::ModernOnly);
        let missing = modern_only.classify_opening(StdioOpeningFrame::RequestWithoutModernMetadata);
        assert!(opening_rejection_selected_modern(&missing));

        let mut auto = StdioEraClassifier::new(ProtocolPolicy::Auto);
        let unsupported = auto.classify_opening(StdioOpeningFrame::ModernRequest {
            protocol_version: "2099-01-01".to_owned(),
        });
        assert!(opening_rejection_selected_modern(&unsupported));
        assert_eq!(
            auto.state(),
            &fastmcp_protocol::protocol_policy::StdioEraState::Selected(ProtocolEra::Modern2026),
            "the unsupported modern opening still selects the modern era"
        );

        // Planted negatives: ambiguous Auto openings select no era and still
        // close, and a supported opening is not a rejection at all.
        let mut auto = StdioEraClassifier::new(ProtocolPolicy::Auto);
        let notification = auto.classify_opening(StdioOpeningFrame::Notification);
        assert!(!opening_rejection_selected_modern(&notification));
        let mut auto = StdioEraClassifier::new(ProtocolPolicy::Auto);
        let supported = auto.classify_opening(StdioOpeningFrame::ModernRequest {
            protocol_version: MODERN_PROTOCOL_VERSION.to_owned(),
        });
        assert!(!opening_rejection_selected_modern(&supported));
    }
}

fn is_quarantined_task_rpc(method: &str) -> bool {
    // Legacy 2024-era names. Official MCP 2026-07-28 Tasks methods are
    // tasks/get, tasks/update, and tasks/cancel; with the `tasks` feature a
    // built server serves them from a process-local in-memory store unless
    // ServerBuilder::final_tasks (or a proxy relay) supplies the runtime.
    matches!(method, "tasks/list" | "tasks/submit")
}

fn is_notification_only_method(method: &str) -> bool {
    method.starts_with("notifications/")
}

fn is_request_only_method(method: &str) -> bool {
    matches!(
        method,
        "server/discover"
            | "initialize"
            | "ping"
            | "logging/setLevel"
            | "completion/complete"
            | "tools/list"
            | "tools/call"
            | "resources/list"
            | "resources/templates/list"
            | "resources/read"
            | "resources/subscribe"
            | "resources/unsubscribe"
            | "prompts/list"
            | "prompts/get"
            | SUBSCRIPTIONS_LISTEN
            | "tasks/list"
            | "tasks/get"
            | "tasks/update"
            | "tasks/cancel"
            | "tasks/submit"
    )
}

fn is_session_mutation(method: &str) -> bool {
    matches!(
        method,
        "initialize" | "logging/setLevel" | "resources/subscribe" | "resources/unsubscribe"
    )
}

enum SessionMutationRollback {
    RemoveResourceSubscription(String),
    RestoreResourceSubscription(String),
    RestoreInitialization(InitializationSnapshot),
    RestoreLogLevel(Option<LogLevel>),
}

impl SessionMutationRollback {
    fn apply(self, session: &mut Session) {
        match self {
            Self::RemoveResourceSubscription(uri) => {
                session.rollback_resource_subscription(&uri);
            }
            Self::RestoreResourceSubscription(uri) => {
                session.restore_resource_subscription(uri);
            }
            Self::RestoreInitialization(snapshot) => {
                session.restore_initialization(snapshot);
            }
            Self::RestoreLogLevel(level) => {
                session.restore_log_level(level);
            }
        }
    }
}

#[cfg(feature = "legacy-2024-11-05")]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum DispatchPrincipalAdmissionState {
    Pending,
    Admitted,
    Rejected,
}

#[cfg(feature = "legacy-2024-11-05")]
struct DispatchPrincipalAdmission {
    state: Mutex<DispatchPrincipalAdmissionState>,
    changed: Condvar,
}

#[cfg(feature = "legacy-2024-11-05")]
impl DispatchPrincipalAdmission {
    fn pending() -> Self {
        Self {
            state: Mutex::new(DispatchPrincipalAdmissionState::Pending),
            changed: Condvar::new(),
        }
    }

    fn admitted() -> Self {
        Self {
            state: Mutex::new(DispatchPrincipalAdmissionState::Admitted),
            changed: Condvar::new(),
        }
    }

    fn resolve(&self, admitted: bool) {
        let mut state = self
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        debug_assert_eq!(*state, DispatchPrincipalAdmissionState::Pending);
        *state = if admitted {
            DispatchPrincipalAdmissionState::Admitted
        } else {
            DispatchPrincipalAdmissionState::Rejected
        };
        self.changed.notify_all();
    }

    fn wait_timeout(&self, timeout: Duration) -> Option<bool> {
        let state = self
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let (state, result) = self
            .changed
            .wait_timeout_while(state, timeout, |state| {
                matches!(state, DispatchPrincipalAdmissionState::Pending)
            })
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        match *state {
            DispatchPrincipalAdmissionState::Admitted => Some(true),
            DispatchPrincipalAdmissionState::Rejected => Some(false),
            DispatchPrincipalAdmissionState::Pending => {
                debug_assert!(result.timed_out());
                None
            }
        }
    }
}

#[derive(Default)]
struct DispatchQueueState {
    inner: Mutex<DispatchQueueStateInner>,
    drained: Condvar,
}

#[derive(Default)]
struct DispatchQueueStateInner {
    /// Request IDs retain this reservation from admission until the response
    /// attempt completes. Keeping it across the queued-to-active transition
    /// closes both admission TOCTOU and post-commit ABA races with ID reuse.
    reserved: HashSet<CorrelationKey>,
    /// Initialization requests remain cancellable only by the server-owned
    /// connection shutdown path. Peer cancellation cannot erase the request
    /// that establishes the selected legacy lifecycle.
    peer_cancellation_protected: HashSet<CorrelationKey>,
    /// Every correlated request retains one cancellation authority from queue
    /// admission through active dispatch and response finalization. The
    /// modern child and exact-2024 adapter must both receive this same handle
    /// so a control notification cannot be lost in the queued-to-active gap.
    admitted_cancellations: HashMap<CorrelationKey, McpRequestCancellation>,
    /// Reserved requests that a worker has begun dispatching.
    dispatching: HashSet<CorrelationKey>,
    cancelled: HashSet<CorrelationKey>,
    modern_cancellations: HashMap<u64, McpRequestCancellation>,
    /// The subset of [`Self::modern_cancellations`] belonging to id-less
    /// (notification) children. These have no response to commit, so shutdown
    /// cancels them before the pre-stop drain window instead of waiting it
    /// out on their behalf.
    uncorrelated_modern_cancellations: HashSet<u64>,
    next_modern_cancellation_id: u64,
    queued_bytes: usize,
    modern_in_flight: usize,
    stopping: bool,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum ModernDispatchStart {
    Ready,
    Cancelled,
    Stopping,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum DispatchCancellationDisposition {
    NotOwned,
    Protected,
    Accepted,
    AlreadySettled,
}

#[cfg(feature = "legacy-2024-11-05")]
struct QueuedDispatchRequest {
    request: JsonRpcRequest,
    era: ProtocolEra,
    serialized_bytes: usize,
    principal_admission: Arc<DispatchPrincipalAdmission>,
}

#[cfg(feature = "legacy-2024-11-05")]
enum QueuedDispatchMessage {
    Request(QueuedDispatchRequest),
    /// Exact-2024 client responses are serialized through the same adapter
    /// that allocated their reverse-request IDs. Generic bidirectional
    /// responses never enter this variant: they are consumed directly by the
    /// generic pending-request registry.
    LegacyResponse(JsonRpcResponse),
}

impl DispatchQueueState {
    fn admit(&self, id: &RequestId, peer_cancellation_allowed: bool) -> bool {
        let Ok(key) = id.correlation_key() else {
            return false;
        };
        let mut inner = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if inner.stopping || !inner.reserved.insert(key.clone()) {
            return false;
        }
        let previous = inner
            .admitted_cancellations
            .insert(key.clone(), McpRequestCancellation::new());
        debug_assert!(previous.is_none());
        if !peer_cancellation_allowed {
            inner.peer_cancellation_protected.insert(key);
        }
        true
    }

    fn discard(&self, id: &RequestId) {
        let Ok(key) = id.correlation_key() else {
            return;
        };
        let mut inner = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let removed = inner.reserved.remove(&key);
        inner.peer_cancellation_protected.remove(&key);
        inner.admitted_cancellations.remove(&key);
        inner.dispatching.remove(&key);
        inner.cancelled.remove(&key);
        if removed && inner.reserved.is_empty() {
            self.drained.notify_all();
        }
    }

    fn admitted_request_cancellation(&self, id: &RequestId) -> Option<McpRequestCancellation> {
        let key = id.correlation_key().ok()?;
        self.inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .admitted_cancellations
            .get(&key)
            .cloned()
    }

    fn reserve_queued_bytes(&self, serialized_bytes: usize) -> bool {
        let mut inner = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if inner.stopping {
            return false;
        }
        let Some(prospective) = inner.queued_bytes.checked_add(serialized_bytes) else {
            return false;
        };
        if prospective > MAX_DISPATCH_QUEUE_BYTES {
            return false;
        }
        inner.queued_bytes = prospective;
        true
    }

    fn release_queued_bytes(&self, serialized_bytes: usize) {
        let mut inner = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        inner.queued_bytes = inner.queued_bytes.saturating_sub(serialized_bytes);
    }

    /// Registers the request-local cancellation domain retained by a modern
    /// child. This covers notifications as well as correlated requests: the
    /// latter are also indexed by `Server::active_requests`, while a
    /// notification has no wire id to index there.
    fn register_modern_cancellation(
        &self,
        cancellation: McpRequestCancellation,
        correlated: bool,
    ) -> u64 {
        let mut inner = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let cancellation_id = inner.next_modern_cancellation_id;
        inner.next_modern_cancellation_id = inner.next_modern_cancellation_id.wrapping_add(1);
        if inner.stopping {
            cancellation.cancel();
        } else {
            let previous = inner
                .modern_cancellations
                .insert(cancellation_id, cancellation);
            debug_assert!(previous.is_none());
            if !correlated {
                inner
                    .uncorrelated_modern_cancellations
                    .insert(cancellation_id);
            }
        }
        cancellation_id
    }

    fn unregister_modern_cancellation(&self, cancellation_id: u64) {
        let mut inner = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        inner.modern_cancellations.remove(&cancellation_id);
        inner
            .uncorrelated_modern_cancellations
            .remove(&cancellation_id);
    }

    /// Cancels id-less (notification) modern children ahead of the pre-stop
    /// drain: the drain window exists to let response commits finish, and a
    /// notification has no response to protect.
    fn cancel_uncorrelated_modern_children(&self) {
        let cancellations = {
            let inner = self
                .inner
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            inner
                .uncorrelated_modern_cancellations
                .iter()
                .filter_map(|id| inner.modern_cancellations.get(id).cloned())
                .collect::<Vec<_>>()
        };
        for cancellation in cancellations {
            cancellation.cancel();
        }
    }

    /// Reserves one bounded modern request slot before it is submitted to the
    /// caller's runtime. The reservation persists until the request-owned
    /// child finishes, so mailbox admission cannot turn into unbounded work.
    fn reserve_modern_slot(&self) -> bool {
        let mut inner = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if inner.stopping || inner.modern_in_flight >= MAX_DISPATCH_QUEUE_DEPTH {
            return false;
        }
        inner.modern_in_flight += 1;
        true
    }

    fn release_modern_slot(&self) {
        let mut inner = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        inner.modern_in_flight = inner.modern_in_flight.saturating_sub(1);
        if inner.modern_in_flight == 0 {
            self.drained.notify_all();
        }
    }

    fn wait_for_modern_drain(&self, timeout: Duration) -> bool {
        let inner = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let (inner, _) = self
            .drained
            .wait_timeout_while(inner, timeout, |inner| inner.modern_in_flight != 0)
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        inner.modern_in_flight == 0
    }

    /// Waits for every admitted id-bearing request to finish its terminal
    /// response attempt. This spans modern children and the exact-2024
    /// adapter; `reserved` is retained from queue admission through the send
    /// attempt, so an ingress EOF cannot strand a reply by stopping the shared
    /// dispatch worker too early.
    fn wait_for_correlated_response_drain(&self, timeout: Duration) -> bool {
        let inner = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let (inner, _) = self
            .drained
            .wait_timeout_while(inner, timeout, |inner| !inner.reserved.is_empty())
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        inner.reserved.is_empty()
    }

    fn wait_for_modern_drain_unbounded(&self) {
        let inner = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let _quiesced_guard = self
            .drained
            .wait_while(inner, |inner| inner.modern_in_flight != 0)
            .unwrap_or_else(std::sync::PoisonError::into_inner);
    }

    fn cancel_reserved(&self, id: &RequestId) -> DispatchCancellationDisposition {
        let Ok(key) = id.correlation_key() else {
            return DispatchCancellationDisposition::NotOwned;
        };
        let mut inner = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if !inner.reserved.contains(&key) {
            return DispatchCancellationDisposition::NotOwned;
        }
        if inner.peer_cancellation_protected.contains(&key) {
            return DispatchCancellationDisposition::Protected;
        }
        if let Some(cancellation) = inner.admitted_cancellations.get(&key).cloned() {
            if !inner.dispatching.contains(&key) {
                inner.cancelled.insert(key);
            }
            return if cancellation.cancel() {
                DispatchCancellationDisposition::Accepted
            } else {
                DispatchCancellationDisposition::AlreadySettled
            };
        }
        if inner.dispatching.contains(&key) {
            return DispatchCancellationDisposition::NotOwned;
        }
        if inner.cancelled.insert(key) {
            DispatchCancellationDisposition::Accepted
        } else {
            DispatchCancellationDisposition::AlreadySettled
        }
    }

    fn begin_dispatch(&self, id: &RequestId) -> bool {
        let Ok(key) = id.correlation_key() else {
            return false;
        };
        let mut inner = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        debug_assert!(inner.reserved.contains(&key));
        inner.dispatching.insert(key.clone());
        inner.cancelled.remove(&key) || inner.stopping
    }

    fn begin_modern_dispatch(&self, id: Option<&RequestId>) -> ModernDispatchStart {
        let mut inner = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if inner.stopping {
            return ModernDispatchStart::Stopping;
        }
        let Some(id) = id else {
            return ModernDispatchStart::Ready;
        };
        let Ok(key) = id.correlation_key() else {
            return ModernDispatchStart::Stopping;
        };
        debug_assert!(inner.reserved.contains(&key));
        inner.dispatching.insert(key.clone());
        if inner.cancelled.remove(&key) {
            ModernDispatchStart::Cancelled
        } else {
            ModernDispatchStart::Ready
        }
    }

    #[cfg(feature = "legacy-2024-11-05")]
    fn is_stopping(&self) -> bool {
        self.inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .stopping
    }

    fn stop(&self) {
        let cancellations = {
            let mut inner = self
                .inner
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            inner.stopping = true;
            let queued = inner
                .reserved
                .difference(&inner.dispatching)
                .cloned()
                .collect::<Vec<_>>();
            inner.cancelled.extend(queued);
            inner
                .modern_cancellations
                .values()
                .chain(inner.admitted_cancellations.values())
                .cloned()
                .collect::<Vec<_>>()
        };
        for cancellation in cancellations {
            cancellation.cancel();
        }
    }
}

/// Marks an unexpected dispatch-worker exit before the worker stack unwinds.
///
/// The latch is disarmed only after a stop requested by the receive pump. A
/// returned send failure, disconnected worker queue, or panic therefore closes
/// admission and makes the pump report failure. Its drop path contains queue
/// wake-up failures so a worker panic cannot turn into a double-panic abort.
#[cfg(feature = "legacy-2024-11-05")]
struct DispatchWorkerFailureLatch {
    failed: Arc<AtomicBool>,
    queue: Arc<DispatchQueueState>,
    armed: bool,
}

#[cfg(feature = "legacy-2024-11-05")]
impl DispatchWorkerFailureLatch {
    fn new(failed: Arc<AtomicBool>, queue: Arc<DispatchQueueState>) -> Self {
        Self {
            failed,
            queue,
            armed: true,
        }
    }

    fn disarm(&mut self) {
        self.armed = false;
    }
}

#[cfg(feature = "legacy-2024-11-05")]
impl Drop for DispatchWorkerFailureLatch {
    fn drop(&mut self) {
        if !self.armed {
            return;
        }
        self.failed.store(true, Ordering::Release);
        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.queue.stop()));
    }
}

#[cfg(feature = "legacy-2024-11-05")]
struct DispatchWorkerCompletionSignal(Option<std::sync::mpsc::Sender<()>>);

#[cfg(feature = "legacy-2024-11-05")]
impl Drop for DispatchWorkerCompletionSignal {
    fn drop(&mut self) {
        if let Some(sender) = self.0.take() {
            let _ = sender.send(());
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum PumpIoMode {
    Split,
    #[cfg(not(feature = "legacy-2024-11-05"))]
    Unsplit,
}

/// Longest an unsplit pump holds off its next `recv` for a listen that has
/// neither acknowledged nor finished. Past it the pump reads again, and the
/// acknowledgement is written when that `recv` returns.
#[cfg(not(feature = "legacy-2024-11-05"))]
const UNSPLIT_LISTEN_OPEN_TIMEOUT: Duration = Duration::from_secs(5);

/// Set once a listen dispatched off an unsplit pump has written its
/// acknowledgement or finished (bd-4crkf).
#[cfg(not(feature = "legacy-2024-11-05"))]
#[derive(Default)]
struct UnsplitListenOpened {
    opened: Mutex<bool>,
    changed: Condvar,
}

#[cfg(not(feature = "legacy-2024-11-05"))]
impl UnsplitListenOpened {
    fn fire(&self) {
        *self
            .opened
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = true;
        self.changed.notify_all();
    }

    /// Waits until fired, `timeout` elapses, or the pump is cancelled.
    fn wait(&self, cx: &Cx, timeout: Duration) {
        let deadline = Instant::now() + timeout;
        let mut opened = self
            .opened
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        while !*opened && cx.checkpoint().is_ok() {
            let remaining = deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                return;
            }
            opened = self
                .changed
                .wait_timeout(opened, remaining.min(Duration::from_millis(10)))
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .0;
        }
    }
}

#[cfg(not(feature = "legacy-2024-11-05"))]
struct UnsplitListenOpenedOnDrop(Arc<UnsplitListenOpened>);

#[cfg(not(feature = "legacy-2024-11-05"))]
impl Drop for UnsplitListenOpenedOnDrop {
    fn drop(&mut self) {
        self.0.fire();
    }
}

/// Owns every admission-side resource for one modern stdio request until its
/// caller-owned child task has finished. The reservation is deliberately held
/// by the task closure itself: a runtime that rejects or cancels a task before
/// first poll still releases its capacity without leaving an orphaned request
/// ID or byte charge behind.
struct ModernDispatchReservation {
    queue: Arc<DispatchQueueState>,
    request_id: Option<RequestId>,
    serialized_bytes: usize,
    cancellation: McpRequestCancellation,
    cancellation_id: u64,
    failed: Arc<AtomicBool>,
    failure_latched: bool,
}

impl ModernDispatchReservation {
    fn new(
        queue: Arc<DispatchQueueState>,
        request_id: Option<RequestId>,
        serialized_bytes: usize,
        failed: Arc<AtomicBool>,
    ) -> Self {
        let cancellation = request_id.as_ref().map_or_else(
            McpRequestCancellation::new,
            |id| {
                queue.admitted_request_cancellation(id).expect(
                    "a correlated modern child must retain its queue-admission cancellation authority",
                )
            },
        );
        let cancellation_id =
            queue.register_modern_cancellation(cancellation.clone(), request_id.is_some());
        Self {
            queue,
            request_id,
            serialized_bytes,
            cancellation,
            cancellation_id,
            failed,
            failure_latched: false,
        }
    }

    fn begin(&mut self) {
        self.failure_latched = true;
    }

    fn disarm_failure(&mut self) {
        self.failure_latched = false;
    }

    fn cancellation(&self) -> McpRequestCancellation {
        self.cancellation.clone()
    }
}

impl DispatchQueueState {
    fn admit_modern_request(
        self: &Arc<Self>,
        request: &JsonRpcRequest,
        failed: Arc<AtomicBool>,
    ) -> Result<ModernDispatchReservation, JsonRpcError> {
        if let Some(id) = request.id.as_ref()
            && !self.admit(id, request.method != "initialize")
        {
            return Err(JsonRpcError {
                code: McpErrorCode::InvalidRequest.into(),
                message: "Request id is already active".to_owned(),
                data: None,
            });
        }
        let slot = self.reserve_modern_slot();
        let bytes = measure_dispatch_request(request);
        if slot
            && let Some(bytes) = bytes
            && self.reserve_queued_bytes(bytes)
        {
            return Ok(ModernDispatchReservation::new(
                Arc::clone(self),
                request.id.clone(),
                bytes,
                failed,
            ));
        }
        if slot {
            self.release_modern_slot();
        }
        if let Some(id) = request.id.as_ref() {
            self.discard(id);
        }
        Err(JsonRpcError {
            code: RESOURCE_EXHAUSTED_ERROR_CODE.into(),
            message: DISPATCH_QUEUE_CAPACITY_MESSAGE.to_owned(),
            data: None,
        })
    }
}

impl Drop for ModernDispatchReservation {
    fn drop(&mut self) {
        if self.failure_latched {
            self.failed.store(true, Ordering::Release);
            let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                self.queue.stop();
            }));
        }
        if let Some(id) = self.request_id.as_ref() {
            self.queue.discard(id);
        }
        self.queue
            .unregister_modern_cancellation(self.cancellation_id);
        self.queue.release_queued_bytes(self.serialized_bytes);
        self.queue.release_modern_slot();
    }
}

thread_local! {
    static REDACT_EXTENSION_PANIC: Cell<bool> = const { Cell::new(false) };
}

struct ExtensionPanicRedactionGuard {
    previous: bool,
}

impl ExtensionPanicRedactionGuard {
    fn enter() -> Self {
        let previous = REDACT_EXTENSION_PANIC.with(|redact| redact.replace(true));
        Self { previous }
    }
}

impl Drop for ExtensionPanicRedactionGuard {
    fn drop(&mut self) {
        REDACT_EXTENSION_PANIC.with(|redact| redact.set(self.previous));
    }
}

/// Installs FastMCP's payload-redacting diagnostic hook once.
///
/// Rust exposes one process-global, replaceable panic hook. An embedding
/// application can call `std::panic::set_hook` after this function returns and
/// replace FastMCP's hook; FastMCP cannot prevent or reliably detect that. The
/// fixed peer-facing error produced after `catch_unwind` remains payload-free,
/// but payload-free process diagnostics require the application to preserve or
/// correctly chain the installed hook.
fn install_extension_panic_hook() {
    INSTALL_EXTENSION_PANIC_HOOK.call_once(|| {
        let previous = std::panic::take_hook();
        std::panic::set_hook(Box::new(move |panic_info| {
            let redact = REDACT_EXTENSION_PANIC.try_with(Cell::get).unwrap_or(false);
            if redact {
                // This branch deliberately cannot observe `panic_info`. Keep
                // the local diagnostic constant-sized and payload-free.
                #[cfg(test)]
                REDACTED_EXTENSION_PANIC_COUNT.fetch_add(1, Ordering::Relaxed);
                let _ = std::io::stderr().write_all(REDACTED_EXTENSION_PANIC_INCIDENT);
            } else {
                previous(panic_info);
            }
        }));
    });
}

pub(crate) fn catch_extension_unwind<R>(
    callback: impl FnOnce() -> R,
) -> Result<R, Box<dyn Any + Send>> {
    install_extension_panic_hook();
    let _redaction = ExtensionPanicRedactionGuard::enter();
    std::panic::catch_unwind(std::panic::AssertUnwindSafe(callback))
}

fn extension_panic_error(extension_class: &'static str) -> McpError {
    static NEXT_EXTENSION_INCIDENT_ID: std::sync::atomic::AtomicU64 =
        std::sync::atomic::AtomicU64::new(1);
    let incident_id = NEXT_EXTENSION_INCIDENT_ID.fetch_add(1, Ordering::Relaxed);
    error!(
        target: targets::SERVER,
        "extension callback terminated unexpectedly; incident_id={incident_id}; class={extension_class}; detail=panic_payload_redacted"
    );
    McpError::internal_error("Internal server error")
}

fn resource_subscription_capacity_error() -> McpError {
    McpError::new(
        McpErrorCode::Custom(RESOURCE_EXHAUSTED_ERROR_CODE),
        RESOURCE_SUBSCRIPTION_CAPACITY_MESSAGE,
    )
}

#[cfg(feature = "tasks")]
fn missing_final_tasks_capability_error() -> McpResult<McpError> {
    let mut extensions = serde_json::Map::new();
    extensions.insert(
        fastmcp_protocol::TASKS_EXTENSION.to_owned(),
        serde_json::json!({}),
    );
    let missing = MissingRequiredClientCapabilityError::new(serde_json::json!({
        "extensions": serde_json::Value::Object(extensions),
    }))
    .map_err(|_| McpError::internal_error("failed to encode required Tasks capability"))?;
    Ok(McpError::with_data(
        McpErrorCode::Custom(missing.jsonrpc_error_code()),
        "Required client capability is missing",
        missing.canonical_error_data(),
    ))
}

fn has_canonical_missing_required_client_capability_payload(
    data: Option<&serde_json::Value>,
) -> bool {
    let Some(data) = data else {
        return false;
    };
    let Some(payload) = data.as_object() else {
        return false;
    };
    if payload.len() != 1 {
        return false;
    }
    let Some(required_capabilities) = payload.get("requiredCapabilities") else {
        return false;
    };
    MissingRequiredClientCapabilityError::new(required_capabilities.clone())
        .is_ok_and(|error| error.canonical_error_data() == *data)
}

fn is_canonical_missing_required_client_capability_error(error: &McpError) -> bool {
    error.code == McpErrorCode::Custom(MISSING_REQUIRED_CLIENT_CAPABILITY_ERROR_CODE)
        && error.message == "Required client capability is missing"
        && has_canonical_missing_required_client_capability_payload(error.data.as_ref())
}

fn mask_peer_error(error: McpError, mask_error_details: bool) -> McpError {
    // Preserve only the fixed, reviewed missing-capability error shape while
    // continuing to mask arbitrary custom extension errors, including
    // lookalikes that reuse its code but alter its message or payload.
    if is_canonical_missing_required_client_capability_error(&error)
        || error.code == McpErrorCode::Custom(RESOURCE_EXHAUSTED_ERROR_CODE)
            && error.message == RESOURCE_SUBSCRIPTION_CAPACITY_MESSAGE
            && error.data.is_none()
        || error.code == McpErrorCode::Custom(fastmcp_protocol::HEADER_MISMATCH_ERROR_CODE)
            && error.message == http_admission::HEADER_MISMATCH_MESSAGE
            && error.data.is_none()
    {
        error
    } else {
        error.masked(mask_error_details)
    }
}

#[cfg(feature = "legacy-2024-11-05")]
fn legacy_handler_error_from_mcp(
    error: McpError,
    mask_error_details: bool,
) -> Legacy2024HandlerError {
    let masked = mask_peer_error(error, mask_error_details);
    Legacy2024HandlerError::with_code(i64::from(i32::from(masked.code)), masked.message)
}

fn is_canonical_missing_required_client_capability_response(response: &JsonRpcResponse) -> bool {
    response.error.as_ref().is_some_and(|error| {
        error.code.as_i32() == Some(MISSING_REQUIRED_CLIENT_CAPABILITY_ERROR_CODE)
            && error.message == "Required client capability is missing"
            && has_canonical_missing_required_client_capability_payload(error.data.as_ref())
    })
}

/// Whether a recognized `Mcp-Param-*` mirror refused a modern HTTP
/// `tools/call` after its tool was resolved (HTTP-05).
fn is_parameter_header_mismatch_response(response: &JsonRpcResponse) -> bool {
    response.error.as_ref().is_some_and(|error| {
        error.code.as_i32() == Some(fastmcp_protocol::HEADER_MISMATCH_ERROR_CODE)
            && error.message == http_admission::HEADER_MISMATCH_MESSAGE
            && error.data.is_none()
    })
}

/// Whether a final outcome is JSON-RPC Method not found (`-32601`).
fn is_method_not_found_response(response: &JsonRpcResponse) -> bool {
    response
        .error
        .as_ref()
        .is_some_and(|error| error.code.as_i32() == Some(-32_601))
}

/// Final outcomes whose canonical modern HTTP status is not 200, each carried
/// as the JSON-RPC error body:
///
/// - 400 for a missing required client capability (`-32021`) or a
///   parameter-header mismatch (`-32020`);
/// - 404 for a method the server does not implement (`-32601`), including
///   methods MCP 2026-07-28 removed such as `initialize` and `ping`.
fn canonical_http_error_status_response(response: &JsonRpcResponse) -> Option<HttpResponse> {
    if is_canonical_missing_required_client_capability_response(response)
        || is_parameter_header_mismatch_response(response)
    {
        return Some(HttpResponse::new(HttpStatus::BAD_REQUEST).with_json(response));
    }
    is_method_not_found_response(response)
        .then(|| HttpResponse::new(HttpStatus::NOT_FOUND).with_json(response))
}
#[cfg(feature = "legacy-2024-11-05")]
use fastmcp_transport::sse::SseServerTransport;
use fastmcp_transport::{
    AsyncStdout, Codec, StdioTransport, Transport, TransportError, TransportRecvHalf,
    TransportSendHalf,
};
#[cfg(test)]
use log::Level;
use log::LevelFilter;

#[derive(Debug, Clone, PartialEq, Eq)]
enum ReceiveErrorDisposition {
    ReplyWithParseError,
    ReplyWithInvalidRequest(Option<RequestId>),
    Terminate,
}

fn classify_receive_error(error: &TransportError) -> ReceiveErrorDisposition {
    match error {
        // A transport timeout does not prove that the byte stream is still at
        // a message boundary. Some receive paths report it after consuming a
        // partial or complete frame, while a context deadline remains
        // exhausted even when no bytes were consumed. Retrying is therefore
        // neither framing-safe nor capable of making progress in general.
        TransportError::Timeout => ReceiveErrorDisposition::Terminate,
        // An explicit bounded-receive deadline may have interrupted a partial
        // frame. This server dispatcher does not own the transport-specific
        // closed-state proof needed to retry it safely.
        TransportError::ReceiveDeadlineExceeded => ReceiveErrorDisposition::Terminate,
        // JSON decoding begins only after a transport has isolated one
        // complete message. Reply with the fixed uncorrelated JSON-RPC error,
        // then admit the next complete message.
        TransportError::Codec(fastmcp_transport::CodecError::Json(_)) => {
            ReceiveErrorDisposition::ReplyWithParseError
        }
        TransportError::Codec(fastmcp_transport::CodecError::InvalidMessage {
            kind: fastmcp_transport::InvalidMessageKind::Request,
            request_id,
            ..
        }) => ReceiveErrorDisposition::ReplyWithInvalidRequest(request_id.clone()),
        TransportError::Codec(fastmcp_transport::CodecError::InvalidMessage {
            kind: fastmcp_transport::InvalidMessageKind::Response,
            ..
        }) => ReceiveErrorDisposition::Terminate,
        // A bounded line reader can detect an oversized frame before it has
        // consumed the delimiter. The byte stream may still point inside the
        // rejected frame, so retrying would reinterpret its suffix.
        TransportError::Codec(fastmcp_transport::CodecError::MessageTooLarge(_)) => {
            ReceiveErrorDisposition::Terminate
        }
        // I/O errors include HTTP/WebSocket framing and protocol violations.
        // Continuing on the same byte stream could reinterpret attacker-owned
        // suffix bytes after the parser has lost synchronization.
        TransportError::Io(_)
        | TransportError::Closed
        | TransportError::ControlFrameTooLarge { .. }
        | TransportError::Cancelled => ReceiveErrorDisposition::Terminate,
    }
}

fn transport_run_error(stage: &'static str, error: &TransportError) -> McpError {
    let kind = match error {
        TransportError::Io(_) => "io",
        TransportError::Closed => "closed",
        TransportError::Codec(_) => "codec",
        TransportError::Timeout => "timeout",
        TransportError::ReceiveDeadlineExceeded => "receive_deadline_exceeded",
        TransportError::ControlFrameTooLarge { .. } => "control_frame_too_large",
        TransportError::Cancelled => "cancelled",
    };
    McpError::with_data(
        McpErrorCode::InternalError,
        format!("Server transport failed during {stage}"),
        serde_json::json!({
            "stage": stage,
            "kind": kind,
        }),
    )
}

fn returning_send_result(error: &TransportError) -> McpResult<()> {
    if error.is_cancelled() {
        Ok(())
    } else {
        Err(transport_run_error("send", error))
    }
}

fn server_run_error(stage: &'static str, kind: &'static str, message: &'static str) -> McpError {
    McpError::with_data(
        McpErrorCode::InternalError,
        message,
        serde_json::json!({
            "stage": stage,
            "kind": kind,
        }),
    )
}

fn returning_send_result_with_connection_failure(
    error: &TransportError,
    connection_failure: &Option<Arc<AtomicBool>>,
) -> McpResult<()> {
    if connection_failure
        .as_ref()
        .is_some_and(|failed| failed.load(Ordering::Acquire))
    {
        Err(server_run_error(
            "notification",
            "send_failure",
            "Server notification send failed",
        ))
    } else {
        returning_send_result(error)
    }
}

fn combined_run_and_close_error(run_error: McpError, close_error: McpError) -> McpError {
    McpError::with_data(
        McpErrorCode::InternalError,
        "Server transport run and close both failed",
        serde_json::json!({
            "stage": "run_and_close",
            "kind": "multiple_failures",
            "run": run_error,
            "close": close_error,
        }),
    )
}

fn combined_operation_and_cleanup_error(
    operation_error: McpError,
    cleanup: ShutdownCleanupOutcome,
) -> McpError {
    let Some(cleanup_error) = cleanup.into_error() else {
        return operation_error;
    };
    McpError::with_data(
        McpErrorCode::InternalError,
        "Server transport operation and shutdown cleanup both failed",
        serde_json::json!({
            "stage": "run_and_cleanup",
            "kind": "multiple_failures",
            "run": operation_error,
            "cleanup": cleanup_error,
        }),
    )
}

fn send_uncorrelated_parse_error<S>(send: &Arc<Mutex<S>>, cx: &Cx) -> Result<(), TransportError>
where
    S: FnMut(&Cx, &JsonRpcMessage) -> Result<(), TransportError>,
{
    send_jsonrpc_error(send, cx, None, McpErrorCode::ParseError, "Parse error")
}

fn send_invalid_request<S>(
    send: &Arc<Mutex<S>>,
    cx: &Cx,
    request_id: Option<RequestId>,
) -> Result<(), TransportError>
where
    S: FnMut(&Cx, &JsonRpcMessage) -> Result<(), TransportError>,
{
    send_jsonrpc_error(
        send,
        cx,
        request_id,
        McpErrorCode::InvalidRequest,
        "Invalid Request",
    )
}

fn send_jsonrpc_error<S>(
    send: &Arc<Mutex<S>>,
    cx: &Cx,
    request_id: Option<RequestId>,
    code: McpErrorCode,
    message: &'static str,
) -> Result<(), TransportError>
where
    S: FnMut(&Cx, &JsonRpcMessage) -> Result<(), TransportError>,
{
    let response = JsonRpcResponse::error(
        request_id,
        JsonRpcError {
            code: code.into(),
            message: message.to_string(),
            data: None,
        },
    );
    let mut guard = send
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    guard(cx, &JsonRpcMessage::Response(response))
}

/// Type alias for startup hook function.
pub type StartupHook =
    Box<dyn FnOnce() -> Result<(), Box<dyn std::error::Error + Send + Sync>> + Send>;

/// Type alias for shutdown hook function.
pub type ShutdownHook = Box<dyn FnOnce() + Send>;

/// Lifecycle hooks for server startup and shutdown.
///
/// These hooks allow custom initialization and cleanup logic to run
/// at well-defined points in the server lifecycle:
///
/// - `on_startup`: Called before the server starts accepting connections
/// - `on_shutdown`: Called when the server is shutting down
///
/// # Example
///
/// ```ignore
/// use fastmcp_rust::{modern::ServerBuilder, prelude::*};
///
/// // Inside the application's async entry point, with its supplied `cx`.
/// ServerBuilder::new("demo", "1.0.0")
///     .on_startup(|| {
///         eprintln!("Initializing...");
///         // Initialize database, caches, etc.
///         Ok::<(), std::io::Error>(())
///     })
///     .on_shutdown(|| {
///         eprintln!("Cleaning up...");
///         // Close connections, flush buffers, etc.
///     })
///     .build()
///     .run_stdio_with_cx(cx)
///     .await;
/// ```
#[derive(Default)]
pub struct LifespanHooks {
    /// Hook called before the server starts accepting connections.
    pub on_startup: Option<StartupHook>,
    /// Hook called when the server is shutting down.
    pub on_shutdown: Option<ShutdownHook>,
}

impl LifespanHooks {
    /// Creates empty lifecycle hooks.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
}

/// Logging configuration for the server.
#[derive(Debug, Clone)]
pub struct LoggingConfig {
    /// Maximum enabled log verbosity (default: INFO).
    ///
    /// Set this to [`LevelFilter::Off`] to disable server-managed logging.
    pub level: LevelFilter,
    /// Show timestamps in logs (default: true).
    pub timestamps: bool,
    /// Show module targets in logs (default: true).
    pub targets: bool,
    /// Show file:line in logs (default: false).
    pub file_line: bool,
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            level: LevelFilter::Info,
            timestamps: true,
            targets: true,
            file_line: false,
        }
    }
}

impl LoggingConfig {
    /// Create logging config from environment variables.
    ///
    /// Respects:
    /// - `FASTMCP_LOG`: Log filter (`off`, `error`, `warn`, `info`, `debug`, or `trace`)
    /// - `FASTMCP_LOG_TIMESTAMPS`: Show timestamps (0/false to disable)
    /// - `FASTMCP_LOG_TARGETS`: Show targets (0/false to disable)
    /// - `FASTMCP_LOG_FILE_LINE`: Show file:line (1/true to enable)
    #[must_use]
    pub fn from_env() -> Self {
        Self::from(&ConsoleConfig::from_env())
    }
}

impl From<&ConsoleConfig> for LoggingConfig {
    fn from(config: &ConsoleConfig) -> Self {
        Self {
            level: config.log_level,
            timestamps: config.log_timestamps,
            targets: config.log_targets,
            file_line: config.log_file_line,
        }
    }
}

/// Behavior when registering a component with a name that already exists.
///
/// This setting controls how the server handles duplicate tool, resource,
/// or prompt names during registration.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DuplicateBehavior {
    /// Raise an error and fail registration.
    ///
    /// Use this for strict validation in production environments.
    Error,

    /// Log a warning and keep the original component.
    ///
    /// This is the default behavior, providing visibility into duplicates
    /// while maintaining backwards compatibility.
    #[default]
    Warn,

    /// Replace the original component with the new one.
    ///
    /// Use this when you want later registrations to override earlier ones.
    Replace,

    /// Silently keep the original component.
    ///
    /// Use this when duplicates are expected and should be ignored.
    Ignore,
}

/// Configuration for the live HTTP listener used by [`Server::run_http`].
///
/// The listener serves modern Streamable HTTP at [`Self::mcp_path`]. Enabling
/// the dated legacy feature additionally exposes the exact MCP 2024-11-05 SSE
/// and message POST routes. It runs on the caller-owned asupersync context and
/// does not create a runtime of its own.
///
/// # Example
///
/// ```ignore
/// use fastmcp_server::HttpServerConfig;
///
/// let config = HttpServerConfig::new()
///     .mcp_path("/api/mcp")
///     .health_path("/healthz")
///     .max_connections(128);
/// ```
#[derive(Debug, Clone)]
pub struct HttpServerConfig {
    /// Path for the health-check endpoint (default: `"/health"`).
    pub health_path: String,
    /// Maximum number of concurrent connections (default: 64).
    pub max_connections: usize,
    /// Time allowed to receive one complete request on an accepted
    /// connection before it is closed (default: 30 seconds).
    pub request_read_timeout: Duration,
    /// Inner HTTP handler configuration (endpoint path, CORS, and body size).
    pub handler_config: HttpHandlerConfig,
    /// Maximum requests buffered for one live HTTP session.
    pub request_capacity: usize,
    /// GET path for the exact MCP 2024-11-05 SSE stream.
    #[cfg(feature = "legacy-2024-11-05")]
    pub legacy_sse_path: String,
    /// POST path advertised to an exact MCP 2024-11-05 SSE client.
    #[cfg(feature = "legacy-2024-11-05")]
    pub legacy_message_path: String,
}

// These match the transport's fixed HTTP/1 header-block ceiling. The body
// ceiling remains deployment-configurable through `HttpHandlerConfig` and is
// passed to the strict admission authority for every endpoint session.
const MODERN_HTTP_ADMISSION_MAX_HEADER_COUNT: usize = 64;
const MODERN_HTTP_ADMISSION_MAX_HEADER_BLOCK_BYTES: usize = 64 * 1024;

fn modern_post_rejection_response(
    rejection: ModernPostRejection,
    body: &[u8],
    max_body_size: usize,
) -> HttpResponse {
    match rejection {
        ModernPostRejection::EndpointMismatch => HttpResponse::new(HttpStatus::NOT_FOUND),
        ModernPostRejection::MethodNotAllowed => HttpResponse::new(HttpStatus::METHOD_NOT_ALLOWED),
        ModernPostRejection::NotAcceptable => HttpResponse::new(HttpStatus::NOT_ACCEPTABLE),
        ModernPostRejection::FinalAdmission(admission) => {
            protocol_admission_error_response(body, admission, max_body_size)
        }
        ModernPostRejection::InvalidRequestMeta { issue } => {
            let response = JsonRpcResponse::error(
                admitted_request_id(body, max_body_size),
                JsonRpcError {
                    code: McpErrorCode::InvalidParams.into(),
                    message: format!("Invalid params: {issue}"),
                    data: None,
                },
            );
            HttpResponse::new(HttpStatus::BAD_REQUEST).with_json(&response)
        }
        // A strictly decoded JSON-RPC notification is accepted with 202 and no
        // body (plan HTTP-02 "successful notification acceptance"). Modern
        // HTTP is stateless per POST: a request is cancelled by closing its
        // own response stream, so a separately POSTed notification carries no
        // authority over another connection's request and has no effect.
        ModernPostRejection::NotARequest => HttpResponse::new(HttpStatus::ACCEPTED),
        ModernPostRejection::TooManyHeaders { .. }
        | ModernPostRejection::HeaderBlockTooLarge { .. }
        | ModernPostRejection::DuplicateSingletonHeader { .. }
        | ModernPostRejection::UnsupportedMediaType
        | ModernPostRejection::UnsupportedContentCoding
        | ModernPostRejection::Raw(_)
        | ModernPostRejection::InvalidEnvelope => HttpResponse::bad_request(),
    }
}

fn admit_modern_http_post(
    handler_config: &HttpHandlerConfig,
    method: &str,
    path: &str,
    headers: &[(String, String)],
    body: &[u8],
) -> Result<AdmittedModernPost, HttpResponse> {
    let limits = HttpAdmissionLimits::new(
        MODERN_HTTP_ADMISSION_MAX_HEADER_COUNT,
        MODERN_HTTP_ADMISSION_MAX_HEADER_BLOCK_BYTES,
        handler_config.max_body_size,
    )
    .expect("fixed modern HTTP admission limits are nonzero");
    let config = HttpEndpointConfig::new(handler_config.base_path.clone(), limits)
        .ok_or_else(HttpResponse::bad_request)?;

    admit_modern_post(&config, method, path, headers, body).map_err(|rejection| {
        modern_post_rejection_response(rejection, body, handler_config.max_body_size)
    })
}

impl Default for HttpServerConfig {
    fn default() -> Self {
        Self {
            health_path: "/health".to_string(),
            max_connections: 64,
            request_read_timeout: DEFAULT_HTTP_REQUEST_READ_TIMEOUT,
            handler_config: HttpHandlerConfig {
                base_path: "/mcp".to_string(),
                ..HttpHandlerConfig::default()
            },
            request_capacity: 64,
            #[cfg(feature = "legacy-2024-11-05")]
            legacy_sse_path: "/sse".to_string(),
            #[cfg(feature = "legacy-2024-11-05")]
            legacy_message_path: "/messages".to_string(),
        }
    }
}

impl HttpServerConfig {
    /// Creates a new configuration with default values.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the MCP endpoint path.
    #[must_use]
    pub fn mcp_path(mut self, path: impl Into<String>) -> Self {
        self.handler_config.base_path = path.into();
        self
    }

    /// Sets the health-check endpoint path.
    #[must_use]
    pub fn health_path(mut self, path: impl Into<String>) -> Self {
        self.health_path = path.into();
        self
    }

    /// Sets the maximum number of concurrent connections.
    #[must_use]
    pub fn max_connections(mut self, max: usize) -> Self {
        self.max_connections = max;
        self
    }

    /// Sets the time allowed to receive one complete request before the
    /// connection is closed and its slot released.
    #[must_use]
    pub fn request_read_timeout(mut self, timeout: Duration) -> Self {
        self.request_read_timeout = timeout;
        self
    }

    /// Sets the inner HTTP handler configuration.
    #[must_use]
    pub fn handler_config(mut self, config: HttpHandlerConfig) -> Self {
        self.handler_config = config;
        self
    }

    /// Sets the per-session HTTP request queue capacity.
    #[must_use]
    pub fn request_capacity(mut self, capacity: usize) -> Self {
        self.request_capacity = capacity;
        self
    }

    /// Sets the exact MCP 2024-11-05 SSE stream path.
    #[must_use]
    #[cfg(feature = "legacy-2024-11-05")]
    pub fn legacy_sse_path(mut self, path: impl Into<String>) -> Self {
        self.legacy_sse_path = path.into();
        self
    }

    /// Sets the exact MCP 2024-11-05 POST path advertised through SSE.
    #[must_use]
    #[cfg(feature = "legacy-2024-11-05")]
    pub fn legacy_message_path(mut self, path: impl Into<String>) -> Self {
        self.legacy_message_path = path.into();
        self
    }
}

/// Failure while constructing or operating a public server HTTP endpoint.
///
/// This is the stable server API for both ModernOnly and legacy-enabled
/// builds; transport-internal endpoint errors never cross the server boundary.
#[derive(Debug)]
pub enum ServerHttpEndpointError {
    /// The endpoint configuration is invalid.
    InvalidConfiguration(String),
    /// Modern HTTP admission failed.
    Http(HttpError),
    /// A bounded transport operation failed.
    Transport(TransportError),
    /// A bounded HTTP session could not be opened.
    Session(HttpSessionError),
    /// The endpoint session has closed.
    Closed,
}

impl std::fmt::Display for ServerHttpEndpointError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidConfiguration(message) => {
                write!(
                    formatter,
                    "invalid server HTTP endpoint configuration: {message}"
                )
            }
            Self::Http(error) => write!(formatter, "modern HTTP admission failed: {error}"),
            Self::Transport(error) => write!(formatter, "HTTP transport failed: {error}"),
            Self::Session(error) => write!(formatter, "HTTP session setup failed: {error}"),
            Self::Closed => formatter.write_str("server HTTP endpoint session is closed"),
        }
    }
}

impl std::error::Error for ServerHttpEndpointError {}

impl ServerHttpEndpointError {
    fn from_internal(error: DualEraHttpEndpointError) -> Self {
        match error {
            DualEraHttpEndpointError::InvalidConfiguration(message) => {
                Self::InvalidConfiguration(message)
            }
            DualEraHttpEndpointError::Http(error) => Self::Http(error),
            DualEraHttpEndpointError::Transport(error) => Self::Transport(error),
            #[cfg(feature = "legacy-2024-11-05")]
            DualEraHttpEndpointError::Session(error) => Self::Session(error),
            DualEraHttpEndpointError::Closed => Self::Closed,
        }
    }
}

fn http_request_accepts_sse(request: &HttpRequest) -> bool {
    request.header("accept").is_some_and(|value| {
        fastmcp_transport::http::HttpResponsePreferences::from_headers([("accept", value)])
            .is_ok_and(|preferences| {
                preferences.accepts(fastmcp_transport::http::HttpResponseRepresentation::Sse)
            })
    })
}

/// A live server composition over a bounded HTTP endpoint.
///
/// Modern Streamable HTTP POSTs, including discovery, are independently
/// dispatched and neither emit nor accept `MCP-Session-Id`. A final
/// `subscriptions/listen` SSE body retains its request-owned dispatch only for
/// that response body. A retained [`ServerHttpSession`] is an embedding
/// lifecycle handle whose repeated [`ServerHttpSession::handle_async`] calls share
/// modern mutable component state; it does not own a private MRTR namespace.
/// Turnkey live ingress opens a fresh embedding session per stateless POST.
/// Eligible stateless MRTR continuations are owned by the router; listener
/// shutdown additionally closes them for turnkey live ingress. Exact MCP
/// 2024-11-05 requests retain the transport-issued session identifier,
/// lifecycle adapter, and SSE response stream for this one session when the
/// legacy feature is enabled.
pub struct ServerHttpEndpoint {
    server: Arc<Server>,
    #[cfg(feature = "legacy-2024-11-05")]
    legacy_origin: String,
}

fn validate_server_http_route_configuration(
    server: &Server,
) -> Result<(), ServerHttpEndpointError> {
    let Some(routes) = server.oauth_http_routes.as_ref() else {
        return Ok(());
    };
    let occupied = vec![
        server.http_config.handler_config.base_path.as_str(),
        server.http_config.health_path.as_str(),
    ];
    #[cfg(feature = "legacy-2024-11-05")]
    let occupied = {
        let mut occupied = occupied;
        occupied.push(server.http_config.legacy_sse_path.as_str());
        occupied.push(server.http_config.legacy_message_path.as_str());
        occupied
    };
    routes
        .validate_non_overlapping_paths(occupied)
        .map_err(|error| ServerHttpEndpointError::InvalidConfiguration(error.to_string()))
}

/// A server-owned session opened through [`ServerHttpEndpoint`].
///
/// Call [`ServerHttpSession::close`] before dropping a session that admitted
/// modern request work. Async close is the only API that joins those tasks;
/// `Drop` can cancel their exact authorities but cannot synchronously drive an
/// asupersync runtime to quiescence.
#[must_use = "a ServerHttpSession with admitted work must be closed asynchronously"]
pub struct ServerHttpSession {
    server: Arc<Server>,
    endpoint_session: Arc<Mutex<DualEraHttpSession>>,
    #[cfg(feature = "legacy-2024-11-05")]
    legacy_session_id: String,
    #[cfg(feature = "legacy-2024-11-05")]
    legacy_lifecycle: DualEraHttpLegacyLifecycle,
    #[cfg(feature = "legacy-2024-11-05")]
    legacy_session: Session,
    #[cfg(feature = "legacy-2024-11-05")]
    legacy_binding: LegacyPeerBinding,
    #[cfg(feature = "legacy-2024-11-05")]
    legacy_adapter: Option<Legacy2024ServerAdapter<HttpLegacy2024RuntimeHandler>>,
    #[cfg(feature = "legacy-2024-11-05")]
    legacy_active_request: Arc<Mutex<Option<LiveLegacy2024ActiveRequest>>>,
    #[cfg(feature = "legacy-2024-11-05")]
    legacy_request_cx: Arc<Mutex<Cx>>,
    #[cfg(feature = "legacy-2024-11-05")]
    legacy_admissions: Arc<HttpLegacyRequestAdmissions>,
    #[cfg(feature = "legacy-2024-11-05")]
    legacy_auth_receipt: Arc<Mutex<Option<AuthAdmissionReceipt>>>,
    /// Principal admitted on the GET `/sse` that opened this generation.
    ///
    /// GET has no JSON-RPC body, so its receipt cannot be committed onto a
    /// later POST. The fingerprint must still bind the session: otherwise the
    /// first POST wins ownership and can stream results to a different opener.
    #[cfg(feature = "legacy-2024-11-05")]
    legacy_sse_open_fingerprint: Option<Sha256Digest>,
    #[cfg(feature = "legacy-2024-11-05")]
    legacy_pending_requests: Arc<PendingRequests>,
    #[cfg(feature = "legacy-2024-11-05")]
    legacy_runtime: LiveLegacy2024ConnectionRuntime,
    /// Embedding-session-owned modern mutable component state.
    ///
    /// Repeated calls to this public session share the value. Turnkey live
    /// ingress instead creates a fresh public session per stateless POST.
    /// Eligible MRTR continuation state lives in the router-owned registry
    /// rather than in a session-specific namespace here. Listener shutdown
    /// closes that registry for turnkey live ingress.
    modern_connection: Arc<ModernConnection>,
    /// Owned modern listen dispatches whose SSE bodies were returned to the
    /// embedding caller. Handles are retained because dropping an asupersync
    /// task handle detaches it from the session lifecycle.
    modern_dispatches: Arc<Mutex<Vec<OwnedModernHttpDispatch>>>,
    /// The first recognized, policy-admitted wire era for this public session.
    /// A session never bridges state across the two incompatible HTTP eras.
    selected_era: Option<ProtocolEra>,
    closed: bool,
}

struct OwnedModernHttpDispatch {
    owner_generation: u64,
    request_cancellation: McpRequestCancellation,
    task: asupersync::runtime::TaskHandle<()>,
}

type ModernHttpDispatchRegistry = Arc<Mutex<Vec<OwnedModernHttpDispatch>>>;

fn take_modern_http_dispatches(
    registry: &ModernHttpDispatchRegistry,
    owner_generation: Option<u64>,
) -> Vec<OwnedModernHttpDispatch> {
    let mut registry = registry
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    let mut retained = Vec::with_capacity(registry.len());
    let mut removed = Vec::new();
    for dispatch in std::mem::take(&mut *registry) {
        if owner_generation.is_none_or(|owner| dispatch.owner_generation == owner) {
            removed.push(dispatch);
        } else {
            retained.push(dispatch);
        }
    }
    *registry = retained;
    removed
}

fn cancel_modern_http_dispatches(
    server: &Server,
    registry: &ModernHttpDispatchRegistry,
    owner_generation: Option<u64>,
) -> Vec<asupersync::runtime::TaskHandle<()>> {
    let dispatches = take_modern_http_dispatches(registry, owner_generation);
    for dispatch in &dispatches {
        server
            .final_subscriptions
            .cancel_modern_http_owner(dispatch.owner_generation);
        dispatch.request_cancellation.cancel();
        dispatch.task.abort();
    }
    dispatches
        .into_iter()
        .map(|dispatch| dispatch.task)
        .collect()
}

/// A server-bound modern SSE response body.
///
/// The transport body owns peer-drop cancellation. A graceful HTTP
/// `subscriptions/listen` ends with its correlated final response (normally a
/// complete result, or a canonical post-admission error); it never emits an
/// MCP `notifications/cancelled` control.
pub struct ServerHttpSseResponse {
    inner: DualEraHttpSseResponse,
    request_cancellation: McpRequestCancellation,
    terminal_delivery: Arc<FinalSubscriptionTerminalDelivery>,
}

const FINAL_TERMINAL_OPEN: u8 = 0;
const FINAL_TERMINAL_ENQUEUED: u8 = 1;
const FINAL_TERMINAL_DRAINED: u8 = 2;
const FINAL_TERMINAL_FAILED: u8 = 3;

#[derive(Default)]
struct FinalSubscriptionTerminalDelivery {
    state: AtomicU8,
    completion_state: AtomicU8,
}

impl FinalSubscriptionTerminalDelivery {
    fn mark_drained(&self) {
        let mut state = self.state.load(Ordering::Acquire);
        while matches!(state, FINAL_TERMINAL_OPEN | FINAL_TERMINAL_ENQUEUED) {
            match self.state.compare_exchange_weak(
                state,
                FINAL_TERMINAL_DRAINED,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => return,
                Err(observed) => state = observed,
            }
        }
    }

    /// Modern HTTP ends a graceful `subscriptions/listen` body without an MCP
    /// `notifications/cancelled` control. Its terminal response may be the
    /// correlated complete result or a canonical post-admission error, so the
    /// control half of this receipt is satisfied before that response queues.
    fn mark_control_not_required(&self) {
        let _ = self.state.compare_exchange(
            FINAL_TERMINAL_OPEN,
            FINAL_TERMINAL_DRAINED,
            Ordering::AcqRel,
            Ordering::Acquire,
        );
    }

    fn mark_completion_enqueued(&self) {
        let _ = self.completion_state.compare_exchange(
            FINAL_TERMINAL_OPEN,
            FINAL_TERMINAL_ENQUEUED,
            Ordering::AcqRel,
            Ordering::Acquire,
        );
    }

    fn mark_completion_drained(&self) {
        let mut state = self.completion_state.load(Ordering::Acquire);
        // The writer must never settle a response merely because it can parse
        // it. Only the dispatcher marks a selected terminal response
        // `ENQUEUED`; this makes a post-admission substituted error wait for
        // its actual pop and flush just like a complete result.
        while state == FINAL_TERMINAL_ENQUEUED {
            match self.completion_state.compare_exchange_weak(
                state,
                FINAL_TERMINAL_DRAINED,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => return,
                Err(observed) => state = observed,
            }
        }
    }

    fn mark_failed(&self) {
        let _ = self.state.compare_exchange(
            FINAL_TERMINAL_OPEN,
            FINAL_TERMINAL_FAILED,
            Ordering::AcqRel,
            Ordering::Acquire,
        );
        let _ = self.completion_state.compare_exchange(
            FINAL_TERMINAL_OPEN,
            FINAL_TERMINAL_FAILED,
            Ordering::AcqRel,
            Ordering::Acquire,
        );
        let _ = self.completion_state.compare_exchange(
            FINAL_TERMINAL_ENQUEUED,
            FINAL_TERMINAL_FAILED,
            Ordering::AcqRel,
            Ordering::Acquire,
        );
        let _ = self.state.compare_exchange(
            FINAL_TERMINAL_ENQUEUED,
            FINAL_TERMINAL_FAILED,
            Ordering::AcqRel,
            Ordering::Acquire,
        );
    }

    fn is_committed(&self) -> bool {
        matches!(
            self.state.load(Ordering::Acquire),
            FINAL_TERMINAL_ENQUEUED | FINAL_TERMINAL_DRAINED
        )
    }

    #[cfg(test)]
    fn is_drained(&self) -> bool {
        self.state.load(Ordering::Acquire) == FINAL_TERMINAL_DRAINED
    }

    fn is_settled(&self) -> bool {
        let terminal_state = self.state.load(Ordering::Acquire);
        let completion_state = self.completion_state.load(Ordering::Acquire);
        terminal_state == FINAL_TERMINAL_FAILED
            || completion_state == FINAL_TERMINAL_FAILED
            || terminal_state == FINAL_TERMINAL_DRAINED
                && completion_state == FINAL_TERMINAL_DRAINED
    }
}

/// Cancellation view shared by one public HTTP response body and its MCP
/// request authority.
#[derive(Clone)]
pub struct ServerHttpRequestCancellation {
    transport: StreamableHttpRequestCancellation,
    request: McpRequestCancellation,
    terminal_delivery: Arc<FinalSubscriptionTerminalDelivery>,
}

impl ServerHttpRequestCancellation {
    /// Returns whether peer body closure or MCP request cancellation won.
    #[must_use]
    pub fn is_cancelled(&self) -> bool {
        self.transport.is_cancelled()
            || self.terminal_delivery.is_settled()
            || self.request.is_cancel_requested() && !self.terminal_delivery.is_committed()
    }

    /// Returns the exact JSON-RPC request ID owned by this response body.
    #[must_use]
    pub fn request_id(&self) -> &RequestId {
        self.transport.request_id()
    }

    /// Checks caller, transport-body, and MCP request cancellation together.
    ///
    /// # Errors
    ///
    /// Returns the transport's cancellation error, or [`TransportError::Cancelled`]
    /// when MCP cancellation has closed the response body.
    pub fn checkpoint(&self, cx: &Cx) -> Result<(), TransportError> {
        self.transport.checkpoint(cx)?;
        // A committed terminal sequence keeps the cancelled request live
        // until its required HTTP completion frame settles.
        if self.terminal_delivery.is_settled()
            || self.request.is_cancel_requested() && !self.terminal_delivery.is_committed()
        {
            return Err(TransportError::Cancelled);
        }
        Ok(())
    }
}

impl ServerHttpSseResponse {
    fn new(
        inner: DualEraHttpSseResponse,
        request_cancellation: McpRequestCancellation,
        terminal_delivery: Arc<FinalSubscriptionTerminalDelivery>,
    ) -> Self {
        Self {
            inner,
            request_cancellation,
            terminal_delivery,
        }
    }

    /// Returns the HTTP response head for this SSE body.
    #[must_use]
    pub fn response(&self) -> &HttpResponse {
        self.inner.response()
    }

    /// Returns the cancellation view shared by the transport body and MCP request.
    #[must_use]
    pub fn cancellation(&self) -> ServerHttpRequestCancellation {
        ServerHttpRequestCancellation {
            transport: self.inner.cancellation(),
            request: self.request_cancellation.clone(),
            terminal_delivery: Arc::clone(&self.terminal_delivery),
        }
    }

    /// Returns the producer bound to this exact response body.
    #[must_use]
    pub fn sender(&self) -> StreamableHttpRequestResponseSender {
        self.inner.sender()
    }

    /// Returns whether either the transport body or the graceful terminal
    /// sequence reached its completed state.
    #[must_use]
    pub fn is_finished(&self) -> bool {
        self.inner.is_finished()
            || self.terminal_delivery.is_settled()
            || self.request_cancellation.is_cancel_requested()
                && !self.terminal_delivery.is_committed()
    }

    /// Pops the next queued event, then reports a fully drained terminal
    /// sequence as a closed body rather than an indefinitely pending queue.
    ///
    /// # Errors
    ///
    /// Returns the underlying transport failure, or [`ServerHttpEndpointError::Closed`]
    /// after the final terminal response has drained.
    pub fn pop_event(&self) -> Result<Option<SseEvent>, ServerHttpEndpointError> {
        if self.terminal_delivery.is_settled() {
            return Err(ServerHttpEndpointError::Closed);
        }
        let popped = match pop_sse_body_event(&self.inner) {
            // A peer/session close cancels the transport body directly; with
            // no committed terminal sequence that is this body's clean close,
            // not a transport failure the reader must distinguish.
            Err(DualEraHttpEndpointError::Transport(TransportError::Cancelled))
                if !self.terminal_delivery.is_committed() =>
            {
                self.terminal_delivery.mark_failed();
                return Err(ServerHttpEndpointError::Closed);
            }
            popped => popped.map_err(ServerHttpEndpointError::from_internal)?,
        };
        match popped {
            Some(event) => {
                if final_subscription_terminal_event(&event) {
                    self.terminal_delivery.mark_drained();
                }
                if final_subscription_terminal_response_event(&event) {
                    self.terminal_delivery.mark_completion_drained();
                }
                Ok(Some(event))
            }
            None if self.request_cancellation.is_cancel_requested() => {
                if self.terminal_delivery.is_committed() {
                    Ok(None)
                } else {
                    self.terminal_delivery.mark_failed();
                    Err(ServerHttpEndpointError::Closed)
                }
            }
            None => Ok(None),
        }
    }

    /// Receives the next event while observing both transport and MCP terminal
    /// cancellation.
    ///
    /// # Errors
    ///
    /// Returns the underlying transport failure, or [`ServerHttpEndpointError::Closed`]
    /// when the response body, MCP request, or caller context is terminal.
    pub fn recv_event(&self, cx: &Cx) -> Result<SseEvent, ServerHttpEndpointError> {
        loop {
            match self.pop_event()? {
                Some(event) => return Ok(event),
                None if cx.checkpoint().is_err() => {
                    return Err(ServerHttpEndpointError::Closed);
                }
                None => std::thread::sleep(Duration::from_millis(1)),
            }
        }
    }
}

fn retryable_http_sse_transport_error(error: &TransportError) -> bool {
    matches!(
        error,
        TransportError::Io(error) if error.kind() == std::io::ErrorKind::WouldBlock
    )
}

fn retryable_http_sse_endpoint_error(error: &DualEraHttpEndpointError) -> bool {
    matches!(
        error,
        DualEraHttpEndpointError::Transport(error) if retryable_http_sse_transport_error(error)
    )
}

/// Observes one event of a request-owned SSE body without blocking. Every
/// server-side reader (the public response and both live writers) uses this.
fn pop_sse_body_event(
    response: &DualEraHttpSseResponse,
) -> Result<Option<SseEvent>, DualEraHttpEndpointError> {
    sse_body_observation(response.pop_event())
}

/// A producer may hold the response mailbox for the few instructions needed to
/// commit an event. That contention means "nothing observable yet", not that
/// the body failed; a writer that treated it as fatal dropped a live
/// `subscriptions/listen` connection mid-stream.
fn sse_body_observation(
    popped: Result<Option<SseEvent>, DualEraHttpEndpointError>,
) -> Result<Option<SseEvent>, DualEraHttpEndpointError> {
    match popped {
        Err(error) if retryable_http_sse_endpoint_error(&error) => Ok(None),
        popped => popped,
    }
}

/// Serializes a request-owned modern HTTP SSE commit through transient
/// transport contention. `WouldBlock` represents a bounded commit gate or
/// mailbox being busy, not peer cancellation. The retry remains bounded so a
/// permanently stalled transport reports its own error instead of pinning a
/// server worker.
fn retry_http_sse_commit<T, E>(
    cx: &Cx,
    request_cancellation: &McpRequestCancellation,
    mut commit: impl FnMut() -> Result<T, E>,
    is_retryable: impl Fn(&E) -> bool,
) -> Result<T, E> {
    let mut retries = 0;
    loop {
        match commit() {
            Ok(value) => return Ok(value),
            Err(error)
                if is_retryable(&error)
                    && !request_cancellation.is_cancel_requested()
                    && cx.checkpoint().is_ok() =>
            {
                if retries >= MAX_HTTP_SSE_COMMIT_RETRIES {
                    return Err(error);
                }
                retries += 1;
                std::thread::yield_now();
            }
            Err(error) => return Err(error),
        }
    }
}

/// Drives one modern request while retaining its final-progress runtime in the
/// same request owner. The timer is polled alongside the dispatch future, so
/// it neither creates detached work nor waits for handler completion before
/// delivering the newest coalesced update.
async fn await_final_progress_rate_tick<T, F, SendFn>(
    cx: &Cx,
    request_cancellation: &McpRequestCancellation,
    runtime: &handler::FinalProgressRuntime<SendFn>,
    future: F,
) -> T
where
    F: std::future::Future<Output = T>,
    SendFn: Fn(JsonRpcRequest) + Send + Sync,
{
    let mut future = std::pin::pin!(future);
    let mut tick = Box::pin(asupersync::time::sleep(
        cx.now(),
        FINAL_PROGRESS_FLUSH_INTERVAL,
    ));

    std::future::poll_fn(|task_cx| {
        if let std::task::Poll::Ready(result) = std::future::Future::poll(future.as_mut(), task_cx)
        {
            return std::task::Poll::Ready(result);
        }

        if !request_cancellation.is_terminal()
            && matches!(
                std::future::Future::poll(tick.as_mut(), task_cx),
                std::task::Poll::Ready(())
            )
        {
            runtime.flush_pending();
            tick.as_mut().set(asupersync::time::sleep(
                cx.now(),
                FINAL_PROGRESS_FLUSH_INTERVAL,
            ));
            // Poll the replacement on the next turn instead of discarding an
            // immediately-ready result and later repolling a completed Sleep.
            // Arrange that turn even when the handler has no wake of its own.
            task_cx.waker().wake_by_ref();
        }

        std::task::Poll::Pending
    })
    .await
}

fn final_subscription_terminal_event(event: &SseEvent) -> bool {
    let Ok(notification) = serde_json::from_str::<JsonRpcRequest>(&event.data) else {
        return false;
    };
    final_subscription_terminal_notification(&notification)
}

/// Returns whether this request-owned SSE event is its terminal JSON-RPC
/// response. A graceful subscription normally ends in a complete result, but
/// response middleware may substitute the canonical required-capability error
/// after the stream has already been admitted. Both must settle the delivery
/// receipt only after the writer actually consumes the frame.
fn final_subscription_terminal_response_event(event: &SseEvent) -> bool {
    serde_json::from_str::<JsonRpcResponse>(&event.data).is_ok()
}

fn final_subscription_completion_response(response: &JsonRpcResponse) -> bool {
    response.error.is_none()
        && response.result.as_ref().is_some_and(|result| {
            final_subscription_completion_result(result, response.id.as_ref())
        })
}

fn final_subscription_completion_result(
    result: &serde_json::Value,
    response_id: Option<&RequestId>,
) -> bool {
    result.get("resultType") == Some(&serde_json::json!("complete"))
        && result
            .get("_meta")
            .and_then(|metadata| metadata.get(FINAL_SUBSCRIPTION_ID_META_KEY))
            .and_then(|subscription_id| {
                serde_json::from_value::<RequestId>(subscription_id.clone()).ok()
            })
            .is_some_and(|subscription_id| response_id == Some(&subscription_id))
}

fn final_subscription_terminal_notification(notification: &JsonRpcRequest) -> bool {
    let Ok(ServerNotification::Cancelled(params)) = ServerNotification::decode(notification) else {
        return false;
    };
    params
        .meta
        .as_ref()
        .and_then(|metadata| metadata.get(FINAL_SUBSCRIPTION_ID_META_KEY))
        .cloned()
        .and_then(|subscription_id| serde_json::from_value::<RequestId>(subscription_id).ok())
        .is_some_and(|subscription_id| subscription_id == params.request_id)
}

fn final_subscription_acknowledgement_notification(notification: &JsonRpcRequest) -> bool {
    matches!(
        ServerNotification::decode(notification),
        Ok(ServerNotification::SubscriptionsAcknowledged(_))
    )
}

/// A response emitted by [`ServerHttpSession::handle_async`].
pub enum ServerHttpEndpointResponse {
    /// A complete response, including modern JSON and legacy POST acknowledgement.
    Immediate(HttpResponse),
    /// A finite modern request-scoped SSE response body.
    ModernSse(ServerHttpSseResponse),
    /// A live exact MCP 2024-11-05 SSE stream.
    #[cfg(feature = "legacy-2024-11-05")]
    LegacySse(DualEraHttpLegacySseResponse),
}

/// Upper bound for live final subscription streams owned by one server.
///
/// Each entry retains only a selected filter, request ID, and a transport
/// notification callback. The callback remains owned by the originating
/// request transport; this registry never creates a background runtime.
const MAX_FINAL_SUBSCRIPTION_STREAMS: usize = 64;

/// Per-subscription bounds for events retained by the registry, including its
/// sole active callback. Concurrent publishers enqueue without waiting for
/// that callback; exceeding either bound retires only that subscription.
const MAX_FINAL_SUBSCRIPTION_QUEUED_EVENTS: usize = 64;
const MAX_FINAL_SUBSCRIPTION_QUEUED_BYTES: usize = 256 * 1024;

/// Modern Streamable HTTP has no protocol session identifier.  A listen
/// response nevertheless owns one connection-local cancellation domain, so
/// give its active-request entry a process-local generation rather than
/// collapsing unrelated HTTP response streams that happen to reuse a JSON-RPC
/// request ID.
static NEXT_MODERN_HTTP_STREAM_GENERATION: AtomicU64 = AtomicU64::new(1);

/// Opaque endpoint-local ownership for live modern response bodies. This is
/// intentionally unrelated to JSON-RPC request IDs and never appears on the
/// wire, so listener teardown can own every active SSE dispatch.
static NEXT_LIVE_MODERN_HTTP_RESPONSE_BODY_GENERATION: AtomicU64 = AtomicU64::new(1);

/// Bridges handler catalog mutations onto live `subscriptions/listen` streams.
struct FinalCatalogPublisher {
    registry: Arc<FinalSubscriptionRegistry>,
}

impl fastmcp_core::CatalogChangePublisher for FinalCatalogPublisher {
    fn publish_catalog_changed(&self, kind: fastmcp_core::McpCatalogKind) -> bool {
        let notification = match kind {
            fastmcp_core::McpCatalogKind::Tools => ServerNotification::ToolsListChanged(None),
            fastmcp_core::McpCatalogKind::Resources => {
                ServerNotification::ResourcesListChanged(None)
            }
            fastmcp_core::McpCatalogKind::Prompts => ServerNotification::PromptsListChanged(None),
        };
        self.registry.publish(notification).unwrap_or(0) > 0
    }

    fn publish_resource_updated(&self, uri: &str) -> bool {
        let Ok(uri) = fastmcp_protocol::common_types::AbsoluteUri::parse(uri) else {
            return false;
        };
        self.registry
            .publish(ServerNotification::ResourceUpdated(
                fastmcp_protocol::FinalResourceUpdatedNotificationParams {
                    uri,
                    meta: None,
                    additional: BTreeMap::new(),
                },
            ))
            .unwrap_or(0)
            > 0
    }
}

/// A server-wide registry of request-owned final subscription streams.
///
/// Stdio and modern HTTP both reserve the same bounded entry while sending the
/// mandatory acknowledgement, then make it publishable. Teardown can remove
/// and cancel that opening reservation without waiting on an external sender.
/// Events are cloned and tagged per entry so a notification can never escape
/// its accepted filter or correlation ID.
#[derive(Default)]
struct FinalSubscriptionRegistry {
    inner: Mutex<FinalSubscriptionRegistryState>,
    terminating: AtomicBool,
}

#[derive(Default)]
struct FinalSubscriptionRegistryState {
    next_key: usize,
    entries: HashMap<usize, FinalSubscriptionEntry>,
    /// Request-body ownership, rather than the JSON-RPC ID, isolates modern
    /// Streamable HTTP listens. Different HTTP bodies may legitimately reuse
    /// the same JSON-RPC request ID without sharing cancellation authority.
    modern_http_owners: HashMap<u64, usize>,
}

#[derive(Clone)]
struct FinalSubscriptionEntry {
    registry_key: usize,
    subscription_id: RequestId,
    modern_http_owner: Option<u64>,
    accepted_filter: SubscriptionFilter,
    #[cfg(feature = "tasks")]
    task_principal: Option<Sha256Digest>,
    notification_sender: NotificationSender,
    request_cancellation: McpRequestCancellation,
    terminal_delivery: Option<Arc<FinalSubscriptionTerminalDelivery>>,
    election: Arc<FinalSubscriptionElection>,
}

#[derive(Default)]
struct FinalSubscriptionTerminationReceipt {
    terminated: usize,
    terminal_deliveries: Vec<Arc<FinalSubscriptionTerminalDelivery>>,
    /// Elections the server won. One won while an acknowledgement or event
    /// callback was in flight is left `ServerTerminationPending`; that
    /// callback's owner completes it, and only while its request is not yet
    /// cancelled.
    won_elections: Vec<(Arc<FinalSubscriptionElection>, McpRequestCancellation)>,
}

impl FinalSubscriptionTerminationReceipt {
    fn is_settled(&self) -> bool {
        self.terminal_deliveries
            .iter()
            .all(|delivery| delivery.is_settled())
    }

    /// Every path that finishes a won election leaves the pending phase and
    /// cancels its request last, so both together mean its owner is done.
    fn elections_settled(&self) -> bool {
        self.won_elections.iter().all(|(election, cancellation)| {
            cancellation.is_cancel_requested()
                && !matches!(
                    *election
                        .phase
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner),
                    FinalSubscriptionPhase::ServerTerminationPending(_)
                )
        })
    }

    /// Waits, bounded, for the callbacks that own pending elections to finish
    /// them. Generic shutdown cancellation must not run before this: it is
    /// indistinguishable from a peer cancel and would defeat the server's
    /// already-won graceful completion (bd-81cct).
    fn wait_for_pending_elections(&self, timeout: Duration) -> bool {
        let deadline = Instant::now() + timeout;
        while !self.elections_settled() {
            if Instant::now() >= deadline {
                return false;
            }
            std::thread::sleep(Duration::from_millis(1));
        }
        true
    }

    fn fail_pending(&self) {
        for delivery in &self.terminal_deliveries {
            if !delivery.is_settled() {
                delivery.mark_failed();
            }
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum FinalSubscriptionPhase {
    Opening,
    /// The acknowledgement has returned and one queued event callback is in
    /// flight. New events still join the opening FIFO so they cannot overtake
    /// the callback already selected for delivery.
    OpeningDelivery,
    Active,
    /// Exactly one notification callback owns the FIFO drain. The count is
    /// retained for the shared terminal-election representation.
    EventDelivery(usize),
    /// Server termination won and is waiting for the acknowledgement callback
    /// (`0`) or this many already-admitted event callbacks (`> 0`) to finish.
    ServerTerminationPending(usize),
    PeerTerminated,
    ServerTerminated,
}

struct FinalSubscriptionElection {
    phase: Mutex<FinalSubscriptionPhase>,
    opening_events: Mutex<FinalSubscriptionEventQueue>,
    graceful_completion: AtomicBool,
}

#[derive(Default)]
struct FinalSubscriptionEventQueue {
    events: VecDeque<(JsonRpcRequest, usize)>,
    retained_events: usize,
    retained_bytes: usize,
}

impl FinalSubscriptionEventQueue {
    fn try_push(&mut self, notification: JsonRpcRequest, bytes: usize) -> bool {
        if self.retained_events >= MAX_FINAL_SUBSCRIPTION_QUEUED_EVENTS
            || bytes > MAX_FINAL_SUBSCRIPTION_QUEUED_BYTES.saturating_sub(self.retained_bytes)
        {
            return false;
        }
        self.retained_events += 1;
        self.retained_bytes += bytes;
        self.events.push_back((notification, bytes));
        true
    }

    fn pop_front(&mut self) -> Option<(JsonRpcRequest, usize)> {
        // Keep the popped event charged until its callback returns. A blocked
        // callback cannot permit another full queue in addition to its bytes.
        self.events.pop_front()
    }

    fn finish_delivery(&mut self, bytes: usize) {
        self.retained_events = self.retained_events.saturating_sub(1);
        self.retained_bytes = self.retained_bytes.saturating_sub(bytes);
    }

    fn clear(&mut self) {
        self.events.clear();
        self.retained_events = 0;
        self.retained_bytes = 0;
    }
}

/// Measure without allocating a second encoded copy or accepting an
/// arbitrarily large application-authored event into a listener's queue.
fn final_subscription_event_bytes<T: serde::Serialize>(notification: &T) -> Option<usize> {
    struct BoundedSize(usize);

    impl std::io::Write for BoundedSize {
        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
            if bytes.len() > MAX_FINAL_SUBSCRIPTION_QUEUED_BYTES.saturating_sub(self.0) {
                return Err(std::io::Error::other(
                    "subscription event byte limit exceeded",
                ));
            }
            self.0 += bytes.len();
            Ok(bytes.len())
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    let mut size = BoundedSize(0);
    serde_json::to_writer(&mut size, notification).ok()?;
    Some(size.0)
}

impl FinalSubscriptionElection {
    fn opening() -> Self {
        Self {
            phase: Mutex::new(FinalSubscriptionPhase::Opening),
            opening_events: Mutex::new(FinalSubscriptionEventQueue::default()),
            graceful_completion: AtomicBool::new(false),
        }
    }
}

/// Caller-owned in-process `subscriptions/listen` stream.
///
/// Keep this handle alive for as long as events should be delivered. Drop
/// unregisters the listener from the server.
pub struct SubscriptionListenHandle {
    _lease: FinalSubscriptionLease,
}

#[cfg(test)]
impl SubscriptionListenHandle {
    /// The registration this handle keeps alive, for tests that inspect it.
    fn lease(&self) -> &FinalSubscriptionLease {
        let Self { _lease: lease } = self;
        lease
    }
}

/// Removes one subscription entry when its request exits for any reason.
struct FinalSubscriptionLease {
    registry: Arc<FinalSubscriptionRegistry>,
    key: usize,
    election: Arc<FinalSubscriptionElection>,
}

impl FinalSubscriptionLease {
    fn has_graceful_completion(&self) -> bool {
        self.election.graceful_completion.load(Ordering::Acquire)
    }

    fn is_peer_terminated(&self) -> bool {
        matches!(
            *self
                .election
                .phase
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner),
            FinalSubscriptionPhase::PeerTerminated
        )
    }
}

impl Drop for FinalSubscriptionLease {
    fn drop(&mut self) {
        let mut state = self
            .registry
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(entry) = state.entries.remove(&self.key) {
            if let Some(owner) = entry.modern_http_owner {
                state.modern_http_owners.remove(&owner);
            }
            drop(state);
            let mut phase = entry
                .election
                .phase
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if matches!(
                *phase,
                FinalSubscriptionPhase::Opening
                    | FinalSubscriptionPhase::OpeningDelivery
                    | FinalSubscriptionPhase::Active
                    | FinalSubscriptionPhase::EventDelivery(_)
            ) {
                *phase = FinalSubscriptionPhase::PeerTerminated;
                entry
                    .election
                    .opening_events
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .clear();
            }
        }
    }
}

fn send_final_subscription_termination_control(
    subscription_id: &RequestId,
    modern_http_owner: Option<u64>,
    terminal_delivery: Option<&Arc<FinalSubscriptionTerminalDelivery>>,
    notification_sender: &NotificationSender,
) -> bool {
    if modern_http_owner.is_some() {
        if let Some(delivery) = terminal_delivery {
            delivery.mark_control_not_required();
        }
        return true;
    }

    match subscription_cancellation_notification(subscription_id) {
        Ok(notification) => {
            let sent = catch_extension_unwind(|| notification_sender(notification)).is_ok();
            if !sent {
                let _ = extension_panic_error("final_subscription_termination_sender");
            }
            sent
        }
        Err(_) => false,
    }
}

fn complete_final_subscription_server_termination(
    election: &FinalSubscriptionElection,
    subscription_id: &RequestId,
    modern_http_owner: Option<u64>,
    terminal_delivery: Option<&Arc<FinalSubscriptionTerminalDelivery>>,
    notification_sender: &NotificationSender,
    request_cancellation: &McpRequestCancellation,
) -> bool {
    let sent = send_final_subscription_termination_control(
        subscription_id,
        modern_http_owner,
        terminal_delivery,
        notification_sender,
    );
    let terminal_committed = terminal_delivery.is_some_and(|delivery| delivery.is_committed());
    if !sent || request_cancellation.is_cancel_requested() && !terminal_committed {
        if let Some(delivery) = terminal_delivery {
            delivery.mark_failed();
        }
        request_cancellation.cancel();
        return false;
    }
    election.graceful_completion.store(true, Ordering::Release);
    request_cancellation.cancel();
    true
}

impl FinalSubscriptionRegistry {
    #[cfg(all(test, feature = "proxy", feature = "tasks"))]
    fn snapshot_for_test(&self) -> serde_json::Value {
        let state = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let mut entries = state
            .entries
            .values()
            .map(|entry| {
                serde_json::json!({
                    "subscriptionId": entry.subscription_id.clone(),
                    "filter": entry.accepted_filter.clone(),
                    "modernHttpOwner": entry.modern_http_owner,
                })
            })
            .collect::<Vec<_>>();
        entries.sort_by_key(|entry| entry.to_string());
        serde_json::json!({
            "terminating": self.terminating.load(Ordering::Acquire),
            "entries": entries,
        })
    }

    fn remove_entry(&self, key: usize) {
        let mut state = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(entry) = state.entries.remove(&key)
            && let Some(owner) = entry.modern_http_owner
        {
            state.modern_http_owners.remove(&owner);
        }
    }

    fn open(
        self: &Arc<Self>,
        subscription_id: RequestId,
        requested: SubscriptionFilter,
        accept_tasks: bool,
        modern_http_owner: Option<u64>,
        request_cancellation: McpRequestCancellation,
        terminal_delivery: Option<Arc<FinalSubscriptionTerminalDelivery>>,
        notification_sender: NotificationSender,
    ) -> McpResult<FinalSubscriptionLease> {
        self.open_with_task_principal(
            subscription_id,
            requested,
            accept_tasks,
            modern_http_owner,
            request_cancellation,
            terminal_delivery,
            notification_sender,
            None,
        )
    }

    fn open_with_task_principal(
        self: &Arc<Self>,
        subscription_id: RequestId,
        requested: SubscriptionFilter,
        accept_tasks: bool,
        modern_http_owner: Option<u64>,
        request_cancellation: McpRequestCancellation,
        terminal_delivery: Option<Arc<FinalSubscriptionTerminalDelivery>>,
        notification_sender: NotificationSender,
        task_principal: Option<Sha256Digest>,
    ) -> McpResult<FinalSubscriptionLease> {
        #[cfg(not(feature = "tasks"))]
        let _ = task_principal;
        if subscription_id.validate().is_err() {
            return Err(McpError::invalid_request(
                "subscriptions/listen requires a valid JSON-RPC request id",
            ));
        }
        if self.terminating.load(Ordering::Acquire) {
            return Err(McpError::request_cancelled());
        }

        #[cfg(feature = "tasks")]
        let accepted_filter = accepted_subscription_filter(&requested, accept_tasks)?;
        #[cfg(not(feature = "tasks"))]
        let accepted_filter = accepted_subscription_filter(&requested, accept_tasks);
        let acknowledgement =
            subscription_acknowledgement(subscription_id.clone(), accepted_filter.clone())?;
        let acknowledgement = acknowledgement.encode().map_err(|error| {
            McpError::internal_error(format!(
                "failed to encode subscriptions/listen acknowledgement: {error}"
            ))
        })?;

        let mut state = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if self.terminating.load(Ordering::Acquire) {
            return Err(McpError::request_cancelled());
        }
        if state.entries.len() >= MAX_FINAL_SUBSCRIPTION_STREAMS {
            return Err(McpError::new(
                McpErrorCode::Custom(RESOURCE_EXHAUSTED_ERROR_CODE),
                "final subscription stream capacity exhausted",
            ));
        }
        if let Some(owner) = modern_http_owner
            && state.modern_http_owners.contains_key(&owner)
        {
            return Err(McpError::invalid_request(
                "a modern HTTP subscriptions/listen response body is already active",
            ));
        }
        let mut key = state.next_key;
        while state.entries.contains_key(&key) {
            key = key.checked_add(1).unwrap_or(0);
        }
        state.next_key = key.checked_add(1).unwrap_or(0);
        let election = Arc::new(FinalSubscriptionElection::opening());
        let previous = state.entries.insert(
            key,
            FinalSubscriptionEntry {
                registry_key: key,
                subscription_id: subscription_id.clone(),
                modern_http_owner,
                accepted_filter,
                #[cfg(feature = "tasks")]
                task_principal,
                notification_sender: notification_sender.clone(),
                request_cancellation: request_cancellation.clone(),
                terminal_delivery: terminal_delivery.clone(),
                election: Arc::clone(&election),
            },
        );
        debug_assert!(previous.is_none());
        if let Some(owner) = modern_http_owner {
            let previous = state.modern_http_owners.insert(owner, key);
            debug_assert!(previous.is_none());
        }

        drop(state);

        // Application-supplied senders are never called under the registry or
        // election mutex. A concurrent server shutdown records
        // `ServerTerminationPending`; this opener then emits the terminal
        // control after the acknowledgement callback returns.
        let acknowledgement_sent =
            catch_extension_unwind(|| notification_sender(acknowledgement)).is_ok();
        if !acknowledgement_sent {
            self.remove_entry(key);
            let mut phase = election
                .phase
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if matches!(
                *phase,
                FinalSubscriptionPhase::Opening
                    | FinalSubscriptionPhase::OpeningDelivery
                    | FinalSubscriptionPhase::Active
                    | FinalSubscriptionPhase::ServerTerminationPending(_)
            ) {
                *phase = FinalSubscriptionPhase::PeerTerminated;
            }
            election
                .opening_events
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .clear();
            if let Some(delivery) = &terminal_delivery {
                delivery.mark_failed();
            }
            request_cancellation.cancel();
            return Err(extension_panic_error(
                "final_subscription_acknowledgement_sender",
            ));
        }

        // Publishers append to the bounded FIFO while the acknowledgement or
        // an earlier queued callback is in flight. Drain one callback at a
        // time while retaining the opening phase so a concurrent publisher
        // cannot overtake an already-admitted event.
        loop {
            let queued_notification;
            let queued_bytes;
            let mut phase = election
                .phase
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            match *phase {
                FinalSubscriptionPhase::Opening if !request_cancellation.is_cancel_requested() => {
                    let mut opening_events = election
                        .opening_events
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    if let Some((notification, bytes)) = opening_events.pop_front() {
                        *phase = FinalSubscriptionPhase::OpeningDelivery;
                        queued_notification = notification;
                        queued_bytes = bytes;
                    } else {
                        *phase = FinalSubscriptionPhase::Active;
                        break;
                    }
                }
                FinalSubscriptionPhase::ServerTerminationPending(0)
                    if !request_cancellation.is_cancel_requested() =>
                {
                    election
                        .opening_events
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .clear();
                    *phase = FinalSubscriptionPhase::ServerTerminated;
                    drop(phase);
                    if !complete_final_subscription_server_termination(
                        &election,
                        &subscription_id,
                        modern_http_owner,
                        terminal_delivery.as_ref(),
                        &notification_sender,
                        &request_cancellation,
                    ) {
                        *election
                            .phase
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner) =
                            FinalSubscriptionPhase::PeerTerminated;
                        return Err(McpError::request_cancelled());
                    }
                    return Ok(FinalSubscriptionLease {
                        registry: Arc::clone(self),
                        key,
                        election,
                    });
                }
                FinalSubscriptionPhase::Opening
                | FinalSubscriptionPhase::OpeningDelivery
                | FinalSubscriptionPhase::Active
                | FinalSubscriptionPhase::EventDelivery(_)
                | FinalSubscriptionPhase::ServerTerminationPending(_)
                | FinalSubscriptionPhase::PeerTerminated
                | FinalSubscriptionPhase::ServerTerminated => {
                    *phase = FinalSubscriptionPhase::PeerTerminated;
                    election
                        .opening_events
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .clear();
                    drop(phase);
                    self.remove_entry(key);
                    if let Some(delivery) = &terminal_delivery {
                        delivery.mark_failed();
                    }
                    request_cancellation.cancel();
                    return Err(McpError::request_cancelled());
                }
            }
            drop(phase);

            let sent = catch_extension_unwind(|| notification_sender(queued_notification)).is_ok();
            if !sent {
                let _ = extension_panic_error("final_subscription_event_sender");
            }
            let mut phase = election
                .phase
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            election
                .opening_events
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .finish_delivery(queued_bytes);
            match *phase {
                FinalSubscriptionPhase::OpeningDelivery
                    if sent && !request_cancellation.is_cancel_requested() =>
                {
                    *phase = FinalSubscriptionPhase::Opening;
                }
                FinalSubscriptionPhase::ServerTerminationPending(1)
                    if sent && !request_cancellation.is_cancel_requested() =>
                {
                    *phase = FinalSubscriptionPhase::ServerTerminated;
                    drop(phase);
                    if !complete_final_subscription_server_termination(
                        &election,
                        &subscription_id,
                        modern_http_owner,
                        terminal_delivery.as_ref(),
                        &notification_sender,
                        &request_cancellation,
                    ) {
                        *election
                            .phase
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner) =
                            FinalSubscriptionPhase::PeerTerminated;
                        return Err(McpError::request_cancelled());
                    }
                    return Ok(FinalSubscriptionLease {
                        registry: Arc::clone(self),
                        key,
                        election,
                    });
                }
                FinalSubscriptionPhase::OpeningDelivery
                | FinalSubscriptionPhase::ServerTerminationPending(_)
                | FinalSubscriptionPhase::PeerTerminated
                | FinalSubscriptionPhase::ServerTerminated
                | FinalSubscriptionPhase::Opening
                | FinalSubscriptionPhase::Active
                | FinalSubscriptionPhase::EventDelivery(_) => {
                    *phase = FinalSubscriptionPhase::PeerTerminated;
                    election
                        .opening_events
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .clear();
                    drop(phase);
                    self.remove_entry(key);
                    if let Some(delivery) = &terminal_delivery {
                        delivery.mark_failed();
                    }
                    request_cancellation.cancel();
                    return Err(McpError::request_cancelled());
                }
            }
        }

        Ok(FinalSubscriptionLease {
            registry: Arc::clone(self),
            key,
            election,
        })
    }

    fn publish(&self, notification: ServerNotification) -> McpResult<usize> {
        if !is_final_subscription_event(&notification) {
            return Err(McpError::invalid_params(
                "only final catalog or resource change notifications may use subscriptions/listen",
            ));
        }
        // Bound application-owned data before cloning it into recipient-
        // specific metadata and wire objects. The exact tagged frame is
        // measured again at each queue, including its subscription ID.
        let bounded = match &notification {
            ServerNotification::ResourceUpdated(params) => {
                final_subscription_event_bytes(params).is_some()
            }
            ServerNotification::ResourcesListChanged(params)
            | ServerNotification::ToolsListChanged(params)
            | ServerNotification::PromptsListChanged(params) => params
                .as_ref()
                .is_none_or(|params| final_subscription_event_bytes(params).is_some()),
            _ => unreachable!("only subscription events passed admission above"),
        };
        if !bounded {
            return Err(McpError::new(
                McpErrorCode::Custom(RESOURCE_EXHAUSTED_ERROR_CODE),
                "subscription event byte limit exceeded",
            ));
        }
        let targets = {
            let state = self
                .inner
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            state
                .entries
                .values()
                .filter(|entry| subscription_filter_accepts(&entry.accepted_filter, &notification))
                .cloned()
                .collect::<Vec<_>>()
        };

        // Author all recipient-specific metadata before sending the first
        // callback. If one entry cannot be represented within the bounded
        // metadata contract, no recipient observes a partial publication.
        let mut deliveries = Vec::with_capacity(targets.len());
        for entry in targets {
            let event = tag_subscription_notification(&notification, &entry.subscription_id)?;
            let wire = event.encode().map_err(|error| {
                McpError::internal_error(format!(
                    "failed to encode final subscription notification: {error}"
                ))
            })?;
            deliveries.push((entry, wire));
        }
        Ok(self.publish_prepared(deliveries, "final_subscription_event_sender"))
    }

    #[cfg(feature = "tasks")]
    fn publish_task(&self, notification: FinalTaskStatusNotification) -> McpResult<usize> {
        self.publish_owned_task(notification, None)
    }

    #[cfg(feature = "tasks")]
    fn publish_owned_task(
        &self,
        notification: FinalTaskStatusNotification,
        principal: Option<Sha256Digest>,
    ) -> McpResult<usize> {
        if final_subscription_event_bytes(&notification).is_none() {
            return Err(McpError::new(
                McpErrorCode::Custom(RESOURCE_EXHAUSTED_ERROR_CODE),
                "subscription event byte limit exceeded",
            ));
        }
        let task_id = notification.params.task.base().task_id.as_str();
        let targets = {
            let state = self
                .inner
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            state
                .entries
                .values()
                .filter(|entry| {
                    entry.task_principal == principal
                        && task_subscription_ids(&entry.accepted_filter)
                            .ok()
                            .flatten()
                            .is_some_and(|task_ids| {
                                task_ids
                                    .iter()
                                    .any(|candidate| candidate.as_str() == task_id)
                            })
                })
                .cloned()
                .collect::<Vec<_>>()
        };

        let mut deliveries = Vec::with_capacity(targets.len());
        for entry in targets {
            let event = tag_task_subscription_notification(&notification, &entry.subscription_id)?;
            deliveries.push((entry, event));
        }
        Ok(self.publish_prepared(deliveries, "final_task_subscription_sender"))
    }

    fn publish_prepared(
        &self,
        deliveries: Vec<(FinalSubscriptionEntry, JsonRpcRequest)>,
        panic_boundary: &'static str,
    ) -> usize {
        let mut count = 0;
        for (entry, notification) in deliveries {
            let bytes = final_subscription_event_bytes(&notification);
            let mut phase = entry
                .election
                .phase
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            match *phase {
                FinalSubscriptionPhase::ServerTerminationPending(_)
                | FinalSubscriptionPhase::PeerTerminated
                | FinalSubscriptionPhase::ServerTerminated => continue,
                FinalSubscriptionPhase::Opening
                | FinalSubscriptionPhase::OpeningDelivery
                | FinalSubscriptionPhase::Active
                | FinalSubscriptionPhase::EventDelivery(_) => {}
            }
            let mut events = entry
                .election
                .opening_events
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if entry.request_cancellation.is_cancel_requested()
                || !bytes.is_some_and(|bytes| events.try_push(notification, bytes))
            {
                events.clear();
                *phase = FinalSubscriptionPhase::PeerTerminated;
                drop(events);
                drop(phase);
                self.retire_failed_subscription(&entry);
                continue;
            }
            if *phase != FinalSubscriptionPhase::Active {
                // Opening and active callbacks share the same bounded FIFO.
                // A reentrant publisher returns after admission, without
                // recursively entering the sender or waiting for itself.
                count += 1;
                continue;
            }
            let first = events
                .pop_front()
                .expect("the active publisher just admitted its first event");
            *phase = FinalSubscriptionPhase::EventDelivery(1);
            drop(events);
            drop(phase);
            count += usize::from(self.drain_subscription_events(&entry, first, panic_boundary));
        }
        count
    }

    fn retire_failed_subscription(&self, entry: &FinalSubscriptionEntry) {
        if let Some(delivery) = &entry.terminal_delivery {
            delivery.mark_failed();
        }
        entry.request_cancellation.cancel();
        self.remove_entry(entry.registry_key);
    }

    /// The publisher that claims an idle subscription drives it synchronously.
    /// Concurrent publishers only append; they never invoke its callback in
    /// parallel. The return value counts this publisher's first event alone,
    /// since each queued event was already counted by its admitting publisher.
    fn drain_subscription_events(
        &self,
        entry: &FinalSubscriptionEntry,
        mut next: (JsonRpcRequest, usize),
        panic_boundary: &'static str,
    ) -> bool {
        let mut first = true;
        let mut first_delivered = false;
        loop {
            let (notification, bytes) = next;
            let sent = catch_extension_unwind(|| (entry.notification_sender)(notification)).is_ok();
            if !sent {
                let _ = extension_panic_error(panic_boundary);
            }
            let mut phase = entry
                .election
                .phase
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let mut events = entry
                .election
                .opening_events
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            events.finish_delivery(bytes);
            match *phase {
                FinalSubscriptionPhase::EventDelivery(1)
                    if sent && !entry.request_cancellation.is_cancel_requested() =>
                {
                    if first {
                        first_delivered = true;
                    }
                    let Some(queued) = events.pop_front() else {
                        *phase = FinalSubscriptionPhase::Active;
                        return first_delivered;
                    };
                    next = queued;
                    first = false;
                }
                FinalSubscriptionPhase::ServerTerminationPending(1)
                    if sent && !entry.request_cancellation.is_cancel_requested() =>
                {
                    events.clear();
                    *phase = FinalSubscriptionPhase::ServerTerminated;
                    drop(events);
                    drop(phase);
                    if complete_final_subscription_server_termination(
                        &entry.election,
                        &entry.subscription_id,
                        entry.modern_http_owner,
                        entry.terminal_delivery.as_ref(),
                        &entry.notification_sender,
                        &entry.request_cancellation,
                    ) {
                        first_delivered |= first;
                    } else {
                        *entry
                            .election
                            .phase
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner) =
                            FinalSubscriptionPhase::PeerTerminated;
                    }
                    return first_delivered;
                }
                FinalSubscriptionPhase::EventDelivery(_)
                | FinalSubscriptionPhase::ServerTerminationPending(_)
                | FinalSubscriptionPhase::Opening
                | FinalSubscriptionPhase::OpeningDelivery
                | FinalSubscriptionPhase::Active
                | FinalSubscriptionPhase::PeerTerminated
                | FinalSubscriptionPhase::ServerTerminated => {
                    *phase = FinalSubscriptionPhase::PeerTerminated;
                    events.clear();
                    drop(events);
                    drop(phase);
                    self.retire_failed_subscription(entry);
                    return first_delivered;
                }
            }
        }
    }

    fn terminate(&self) -> usize {
        self.terminate_with_receipt().terminated
    }

    fn terminate_with_receipt(&self) -> FinalSubscriptionTerminationReceipt {
        self.terminating.store(true, Ordering::Release);
        let entries = {
            let mut state = self
                .inner
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let entries = std::mem::take(&mut state.entries);
            state.modern_http_owners.clear();
            entries.into_values().collect::<Vec<_>>()
        };
        let mut receipt = FinalSubscriptionTerminationReceipt::default();
        for entry in entries {
            let election = Arc::clone(&entry.election);
            let request_cancellation = entry.request_cancellation.clone();
            let (terminated, terminal_delivery) = Self::terminate_removed_entry(entry);
            if terminated {
                receipt.terminated += 1;
                receipt.won_elections.push((election, request_cancellation));
            }
            if let Some(terminal_delivery) = terminal_delivery {
                receipt.terminal_deliveries.push(terminal_delivery);
            }
        }
        receipt
    }

    fn terminate_removed_entry(
        entry: FinalSubscriptionEntry,
    ) -> (bool, Option<Arc<FinalSubscriptionTerminalDelivery>>) {
        let mut phase = entry
            .election
            .phase
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        match *phase {
            FinalSubscriptionPhase::Opening => {
                if entry.request_cancellation.is_cancel_requested() {
                    *phase = FinalSubscriptionPhase::PeerTerminated;
                    entry
                        .election
                        .opening_events
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .clear();
                    if let Some(delivery) = &entry.terminal_delivery {
                        delivery.mark_failed();
                    }
                    return (false, None);
                }
                // The acknowledgement callback owns the only ordering point
                // at which terminal delivery can safely begin. Record the
                // server's winning election and let `open` finish it after the
                // callback returns, without waiting under a callback-spanning
                // lock.
                entry
                    .election
                    .opening_events
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .clear();
                *phase = FinalSubscriptionPhase::ServerTerminationPending(0);
                (true, entry.terminal_delivery)
            }
            FinalSubscriptionPhase::OpeningDelivery => {
                entry
                    .election
                    .opening_events
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .clear();
                if entry.request_cancellation.is_cancel_requested() {
                    *phase = FinalSubscriptionPhase::PeerTerminated;
                    if let Some(delivery) = &entry.terminal_delivery {
                        delivery.mark_failed();
                    }
                    return (false, None);
                }
                *phase = FinalSubscriptionPhase::ServerTerminationPending(1);
                (true, entry.terminal_delivery)
            }
            FinalSubscriptionPhase::Active => {
                if entry.request_cancellation.is_cancel_requested() {
                    *phase = FinalSubscriptionPhase::PeerTerminated;
                    return (false, None);
                }
                *phase = FinalSubscriptionPhase::ServerTerminated;
                drop(phase);
                // A terminal stdio listen queues its correlated cancellation
                // control before waking its dispatch to produce the matching
                // complete result. Modern HTTP has no in-band cancellation
                // notification: its body closure is client cancellation and
                // graceful server shutdown sends one terminal response below.
                if !complete_final_subscription_server_termination(
                    &entry.election,
                    &entry.subscription_id,
                    entry.modern_http_owner,
                    entry.terminal_delivery.as_ref(),
                    &entry.notification_sender,
                    &entry.request_cancellation,
                ) {
                    *entry
                        .election
                        .phase
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner) =
                        FinalSubscriptionPhase::PeerTerminated;
                    return (false, None);
                }
                // The parked dispatch only observes the election through its
                // request cancellation; the graceful_completion flag above is
                // ordered before this wake so the dispatch converts to the
                // terminal completion response instead of a cancelled error.
                (true, entry.terminal_delivery)
            }
            FinalSubscriptionPhase::EventDelivery(in_flight) => {
                entry
                    .election
                    .opening_events
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .clear();
                if entry.request_cancellation.is_cancel_requested() {
                    *phase = FinalSubscriptionPhase::PeerTerminated;
                    if let Some(delivery) = &entry.terminal_delivery {
                        delivery.mark_failed();
                    }
                    return (false, None);
                }
                *phase = FinalSubscriptionPhase::ServerTerminationPending(in_flight);
                (true, entry.terminal_delivery)
            }
            FinalSubscriptionPhase::ServerTerminationPending(_)
            | FinalSubscriptionPhase::PeerTerminated
            | FinalSubscriptionPhase::ServerTerminated => (false, None),
        }
    }

    /// Cancels the exact live modern HTTP listen owned by one response body.
    /// A missing or already-finished owner is deliberately a no-op and cannot
    /// affect another body that reused the same JSON-RPC request ID.
    fn cancel_modern_http_owner(&self, owner: u64) -> bool {
        let entry = {
            let mut state = self
                .inner
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let Some(entry_key) = state.modern_http_owners.remove(&owner) else {
                return false;
            };
            state.entries.remove(&entry_key)
        };
        let Some(entry) = entry else {
            return false;
        };
        let mut phase = entry
            .election
            .phase
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if matches!(
            *phase,
            FinalSubscriptionPhase::Opening
                | FinalSubscriptionPhase::OpeningDelivery
                | FinalSubscriptionPhase::Active
                | FinalSubscriptionPhase::EventDelivery(_)
        ) {
            *phase = FinalSubscriptionPhase::PeerTerminated;
            entry
                .election
                .opening_events
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .clear();
            entry.request_cancellation.cancel();
            true
        } else {
            false
        }
    }

    fn is_terminating(&self) -> bool {
        self.terminating.load(Ordering::Acquire)
    }
}

fn core_accepted_subscription_filter(requested: &SubscriptionFilter) -> SubscriptionFilter {
    SubscriptionFilter {
        prompts_list_changed: requested.prompts_list_changed.filter(|accepted| *accepted),
        resource_subscriptions: requested.resource_subscriptions.clone(),
        resources_list_changed: requested
            .resources_list_changed
            .filter(|accepted| *accepted),
        tools_list_changed: requested.tools_list_changed.filter(|accepted| *accepted),
        // Unknown extension filter keys remain schema-open but are never
        // activated by the core server execution path.
        additional: BTreeMap::new(),
    }
}

#[cfg(feature = "tasks")]
fn accepted_subscription_filter(
    requested: &SubscriptionFilter,
    accept_tasks: bool,
) -> McpResult<SubscriptionFilter> {
    let mut accepted = core_accepted_subscription_filter(requested);
    if let Some(task_ids) = task_subscription_ids(requested)
        .map_err(|_| McpError::invalid_params("invalid Tasks subscription filter"))?
    {
        if !accept_tasks {
            return Err(McpError::invalid_params(
                "Tasks subscription filter was not negotiated",
            ));
        }
        let mut seen = HashSet::new();
        let canonical = task_ids
            .into_iter()
            .filter(|task_id| seen.insert(task_id.clone()))
            .collect();
        set_task_subscription_ids(&mut accepted, canonical)
            .map_err(|_| McpError::invalid_params("invalid Tasks subscription filter"))?;
    }
    Ok(accepted)
}

#[cfg(not(feature = "tasks"))]
fn accepted_subscription_filter(
    requested: &SubscriptionFilter,
    _accept_tasks: bool,
) -> SubscriptionFilter {
    core_accepted_subscription_filter(requested)
}

/// Compares the filters that this server can actually admit, rather than their
/// raw wire shapes. In particular, disabled categories and unactivated
/// extension members cannot make an upstream acknowledgement appear narrower;
/// every admitted category plus the resource URI and Tasks ID sets must still
/// match.
#[cfg(all(feature = "proxy", feature = "tasks"))]
fn subscription_filter_admission_matches(
    expected: &SubscriptionFilter,
    acknowledged: &SubscriptionFilter,
) -> McpResult<bool> {
    let expected = accepted_subscription_filter(expected, true)?;
    let acknowledged = accepted_subscription_filter(acknowledged, true)?;
    let expected_resource_subscriptions = expected
        .resource_subscriptions
        .as_deref()
        .map(|uris| uris.iter().map(String::as_str).collect::<BTreeSet<_>>());
    let acknowledged_resource_subscriptions = acknowledged
        .resource_subscriptions
        .as_deref()
        .map(|uris| uris.iter().map(String::as_str).collect::<BTreeSet<_>>());
    #[cfg(feature = "tasks")]
    let expected_task_ids = task_subscription_ids(&expected)
        .map_err(|_| McpError::invalid_params("invalid Tasks subscription filter"))?
        .map(|task_ids| task_ids.into_iter().collect::<BTreeSet<_>>());
    #[cfg(feature = "tasks")]
    let acknowledged_task_ids = task_subscription_ids(&acknowledged)
        .map_err(|_| McpError::invalid_params("invalid Tasks subscription filter"))?
        .map(|task_ids| task_ids.into_iter().collect::<BTreeSet<_>>());
    let core_filters_match = expected.prompts_list_changed == acknowledged.prompts_list_changed
        && expected_resource_subscriptions == acknowledged_resource_subscriptions
        && expected.resources_list_changed == acknowledged.resources_list_changed
        && expected.tools_list_changed == acknowledged.tools_list_changed;
    #[cfg(feature = "tasks")]
    {
        Ok(core_filters_match && expected_task_ids == acknowledged_task_ids)
    }
    #[cfg(not(feature = "tasks"))]
    {
        Ok(core_filters_match)
    }
}

fn subscription_metadata(
    existing: Option<OpenMetadata>,
    subscription_id: &RequestId,
) -> McpResult<OpenMetadata> {
    let mut entries = existing.map_or_else(BTreeMap::new, |metadata| metadata.entries().clone());
    entries.insert(
        FINAL_SUBSCRIPTION_ID_META_KEY.to_owned(),
        serde_json::to_value(subscription_id).map_err(McpError::from)?,
    );
    OpenMetadata::try_from_entries(entries)
        .map_err(|_| McpError::invalid_params("invalid final subscription metadata"))
}

fn subscription_acknowledgement(
    subscription_id: RequestId,
    accepted_filter: SubscriptionFilter,
) -> McpResult<ServerNotification> {
    Ok(ServerNotification::SubscriptionsAcknowledged(
        FinalSubscriptionsAcknowledgedNotificationParams {
            meta: Some(subscription_metadata(None, &subscription_id)?),
            notifications: accepted_filter,
            additional: BTreeMap::new(),
        },
    ))
}

fn subscription_cancellation_notification(
    subscription_id: &RequestId,
) -> McpResult<JsonRpcRequest> {
    ServerNotification::Cancelled(FinalCancelledNotificationParams {
        request_id: subscription_id.clone(),
        reason: None,
        meta: Some(subscription_metadata(None, subscription_id)?),
        additional: BTreeMap::new(),
    })
    .encode()
    .map_err(|error| {
        McpError::internal_error(format!(
            "failed to encode final subscription cancellation: {error}"
        ))
    })
}

#[cfg(all(feature = "proxy", feature = "tasks"))]
fn catalog_filter_requests_resource_updates(filter: &SubscriptionFilter) -> bool {
    filter
        .resource_subscriptions
        .as_ref()
        .is_some_and(|uris| !uris.is_empty())
}

fn is_final_subscription_event(notification: &ServerNotification) -> bool {
    matches!(
        notification,
        ServerNotification::ResourcesListChanged(_)
            | ServerNotification::ToolsListChanged(_)
            | ServerNotification::PromptsListChanged(_)
            | ServerNotification::ResourceUpdated(_)
    )
}

fn subscription_filter_accepts(
    filter: &SubscriptionFilter,
    notification: &ServerNotification,
) -> bool {
    match notification {
        ServerNotification::ResourcesListChanged(_) => filter.resources_list_changed == Some(true),
        ServerNotification::ToolsListChanged(_) => filter.tools_list_changed == Some(true),
        ServerNotification::PromptsListChanged(_) => filter.prompts_list_changed == Some(true),
        ServerNotification::ResourceUpdated(params) => filter
            .resource_subscriptions
            .as_ref()
            .is_some_and(|uris| uris.iter().any(|uri| uri == params.uri.as_str())),
        ServerNotification::Cancelled(_)
        | ServerNotification::Progress(_)
        | ServerNotification::Message(_)
        | ServerNotification::SubscriptionsAcknowledged(_) => false,
    }
}

fn tag_subscription_notification(
    notification: &ServerNotification,
    subscription_id: &RequestId,
) -> McpResult<ServerNotification> {
    match notification {
        ServerNotification::ResourcesListChanged(params) => {
            let mut params = params.clone().unwrap_or_default();
            params.meta = Some(subscription_metadata(params.meta, subscription_id)?);
            Ok(ServerNotification::ResourcesListChanged(Some(params)))
        }
        ServerNotification::ToolsListChanged(params) => {
            let mut params = params.clone().unwrap_or_default();
            params.meta = Some(subscription_metadata(params.meta, subscription_id)?);
            Ok(ServerNotification::ToolsListChanged(Some(params)))
        }
        ServerNotification::PromptsListChanged(params) => {
            let mut params = params.clone().unwrap_or_default();
            params.meta = Some(subscription_metadata(params.meta, subscription_id)?);
            Ok(ServerNotification::PromptsListChanged(Some(params)))
        }
        ServerNotification::ResourceUpdated(params) => {
            let mut params = params.clone();
            params.meta = Some(subscription_metadata(params.meta, subscription_id)?);
            Ok(ServerNotification::ResourceUpdated(params))
        }
        ServerNotification::Cancelled(_)
        | ServerNotification::Progress(_)
        | ServerNotification::Message(_)
        | ServerNotification::SubscriptionsAcknowledged(_) => Err(McpError::invalid_params(
            "notification does not belong on a final subscription stream",
        )),
    }
}

#[cfg(feature = "tasks")]
fn tag_task_subscription_notification(
    notification: &FinalTaskStatusNotification,
    subscription_id: &RequestId,
) -> McpResult<JsonRpcRequest> {
    let mut notification = notification.clone();
    notification.params.meta = Some(subscription_metadata(
        notification.params.meta,
        subscription_id,
    )?);
    serde_json::from_value(serde_json::to_value(notification).map_err(McpError::from)?)
        .map_err(McpError::from)
}

/// One exact-2024 HTTP request admitted before it waits for the session mutex.
///
/// The generation binds cleanup to this precise admission. It prevents a late
/// response finalizer from removing a future admission that reused the same
/// wire ID.
#[cfg(feature = "legacy-2024-11-05")]
struct HttpLegacyRequestAdmission {
    generation: u64,
    cancellation: McpRequestCancellation,
    peer_cancellation_protected: bool,
}

#[derive(Default)]
#[cfg(feature = "legacy-2024-11-05")]
struct HttpLegacyRequestAdmissionsInner {
    next_generation: u64,
    entries: HashMap<CorrelationKey, HttpLegacyRequestAdmission>,
}

/// Session-scoped legacy HTTP cancellation authorities.
///
/// The target POST enters this registry before it waits for the serialized
/// adapter/session path. A separate cancellation POST can therefore select the
/// exact authority throughout admission, mutex wait, active dispatch, and
/// response finalization without taking the session mutex.
#[derive(Default)]
#[cfg(feature = "legacy-2024-11-05")]
struct HttpLegacyRequestAdmissions {
    inner: Mutex<HttpLegacyRequestAdmissionsInner>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg(feature = "legacy-2024-11-05")]
enum HttpLegacyAdmissionCancellationDisposition {
    NotOwned,
    Protected,
    Accepted,
    AlreadySettled,
}

/// Retains an HTTP admission until its target POST has completed response
/// finalization. Dropping the guard releases only its matching generation.
#[cfg(feature = "legacy-2024-11-05")]
struct HttpLegacyRequestAdmissionGuard {
    admissions: Arc<HttpLegacyRequestAdmissions>,
    key: CorrelationKey,
    generation: u64,
}

#[cfg(feature = "legacy-2024-11-05")]
impl HttpLegacyRequestAdmissions {
    fn admit(
        self: &Arc<Self>,
        request: &JsonRpcRequest,
        principal_binding: &SessionPrincipalBinding,
        fingerprint: Sha256Digest,
    ) -> Result<Option<HttpLegacyRequestAdmissionGuard>, ()> {
        if request.validate().is_err()
            || request.id.is_none()
            || request.method == "notifications/cancelled"
        {
            return Ok(None);
        }
        let request_id = request
            .id
            .as_ref()
            .expect("a correlated legacy HTTP request retains its ID");
        let key = request_id.correlation_key().map_err(|_| ())?;
        let peer_cancellation_protected = request.method == "initialize";

        let mut inner = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        // Establish the owner while the cancellation control is excluded from
        // both authentication and map lookup. A control POST therefore cannot
        // observe a bound owner without the matching per-ID authority, or an
        // authority whose owner it cannot yet verify.
        if !principal_binding.bind_or_verify(fingerprint) {
            return Err(());
        }
        if inner.entries.contains_key(&key) {
            return Err(());
        }
        let generation = inner.next_generation;
        inner.next_generation = inner.next_generation.wrapping_add(1);
        let previous = inner.entries.insert(
            key.clone(),
            HttpLegacyRequestAdmission {
                generation,
                cancellation: McpRequestCancellation::new(),
                peer_cancellation_protected,
            },
        );
        debug_assert!(previous.is_none());
        drop(inner);
        Ok(Some(HttpLegacyRequestAdmissionGuard {
            admissions: Arc::clone(self),
            key,
            generation,
        }))
    }

    fn admitted_request_cancellation(
        &self,
        request_id: &RequestId,
    ) -> Option<McpRequestCancellation> {
        let key = request_id.correlation_key().ok()?;
        self.inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .entries
            .get(&key)
            .map(|entry| entry.cancellation.clone())
    }

    fn cancel_locked(
        inner: &HttpLegacyRequestAdmissionsInner,
        request_id: &RequestId,
    ) -> HttpLegacyAdmissionCancellationDisposition {
        let Ok(key) = request_id.correlation_key() else {
            return HttpLegacyAdmissionCancellationDisposition::NotOwned;
        };
        let Some(entry) = inner.entries.get(&key) else {
            return HttpLegacyAdmissionCancellationDisposition::NotOwned;
        };
        if entry.peer_cancellation_protected {
            return HttpLegacyAdmissionCancellationDisposition::Protected;
        }
        if entry.cancellation.cancel() {
            HttpLegacyAdmissionCancellationDisposition::Accepted
        } else {
            HttpLegacyAdmissionCancellationDisposition::AlreadySettled
        }
    }

    fn cancel_all(&self) {
        let cancellations = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .entries
            .values()
            .map(|entry| entry.cancellation.clone())
            .collect::<Vec<_>>();
        for cancellation in cancellations {
            cancellation.cancel();
        }
    }

    #[cfg(test)]
    fn contains(&self, request_id: &RequestId) -> bool {
        let Ok(key) = request_id.correlation_key() else {
            return false;
        };
        self.inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .entries
            .contains_key(&key)
    }

    fn release(&self, key: &CorrelationKey, generation: u64) {
        let mut inner = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if inner
            .entries
            .get(key)
            .is_some_and(|entry| entry.generation == generation)
        {
            inner.entries.remove(key);
        }
    }
}

#[cfg(feature = "legacy-2024-11-05")]
impl Drop for HttpLegacyRequestAdmissionGuard {
    fn drop(&mut self) {
        self.admissions.release(&self.key, self.generation);
    }
}

/// Cancellation authority deliberately kept outside the session mutex.
///
/// A legacy client sends cancellation on a separate POST connection while the
/// request it targets may be queued for or running under the session lock. The
/// control frame authenticates first, then resolves the session admission map
/// before falling back to the server active-request registry.
#[derive(Clone)]
#[cfg(feature = "legacy-2024-11-05")]
struct HttpLegacyCancellationControl {
    server: Arc<Server>,
    session_id: u64,
    http_session_id: String,
    legacy_message_path: String,
    legacy_lifecycle: DualEraHttpLegacyLifecycle,
    session_principal: SessionPrincipalBinding,
    max_body_size: usize,
    admissions: Arc<HttpLegacyRequestAdmissions>,
}

#[cfg(feature = "legacy-2024-11-05")]
impl HttpLegacyCancellationControl {
    /// Revokes every exact-2024 request admitted by this SSE peer without
    /// taking the serialized `ServerHttpSession` mutex.  The transport must
    /// use this on peer close because an admitted synchronous handler may be
    /// holding that mutex while it waits to observe cancellation.
    fn cancel_all_admitted_requests(&self) {
        self.admissions.cancel_all();
    }

    fn handle(&self, cx: &Cx, request: &HttpRequest) -> Option<HttpResponse> {
        let mut notification = match admit_legacy_2024_http_post(
            request,
            &self.legacy_message_path,
            &self.http_session_id,
            self.max_body_size,
        ) {
            Ok(Legacy2024HttpPostEnvelope::ClientMessage(notification)) => notification,
            Ok(Legacy2024HttpPostEnvelope::Response(_)) => return None,
            Err(response) => return Some(response),
        };
        if notification.id.is_some() || notification.method != "notifications/cancelled" {
            return None;
        }
        Some(
            self.legacy_lifecycle
                .commit_if_live(|| {
                    let (cancellation, disposition) = {
                        // The target admission binds its owner and inserts its
                        // exact authority under this same lock. Holding it through
                        // authentication makes that transition one ordered operation.
                        let admissions = self
                            .admissions
                            .inner
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner);
                        let authorization = match transport_authorization_from_http_request(request)
                        {
                            Ok(authorization) => authorization,
                            Err(response) => return response,
                        };
                        let receipt = match self.server.preauthenticate_http_request(
                            cx,
                            &notification,
                            &authorization,
                        ) {
                            Ok(receipt) => receipt,
                            Err(response) => return response,
                        };
                        let cancellation =
                            match self.server.authenticate_cancelled_control_notification(
                                cx,
                                &self.session_principal,
                                ProtocolEra::Legacy2024,
                                &mut notification,
                                Some(&receipt),
                            ) {
                                Ok(cancellation) => cancellation,
                                Err(_) => return HttpResponse::bad_request(),
                            };
                        let request_id = Server::cancellation_wire_request_id(&cancellation);
                        let disposition =
                            HttpLegacyRequestAdmissions::cancel_locked(&admissions, request_id);
                        (cancellation, disposition)
                    };
                    if matches!(
                        disposition,
                        HttpLegacyAdmissionCancellationDisposition::NotOwned
                    ) {
                        self.server
                            .handle_cancellation_wire_notification(self.session_id, cancellation);
                    }
                    HttpResponse::new(HttpStatus::ACCEPTED)
                })
                .unwrap_or_else(|| HttpResponse::new(HttpStatus::SERVICE_UNAVAILABLE)),
        )
    }
}

#[cfg(feature = "legacy-2024-11-05")]
struct LiveHttpSession {
    /// `None` while the owning connection child is driving request-owned
    /// handler futures. Cancellation and reverse-response routing stay
    /// outside this slot so they never wait on that exclusive borrow.
    session: Mutex<Option<ServerHttpSession>>,
    session_available: Condvar,
    /// Listener or peer teardown has removed this session from admission.
    ///
    /// A request may temporarily own `session` outside the mutex. Marking the
    /// shared shell before registry evacuation ensures that request closes the
    /// owned session instead of restoring a detached live SSE body.
    closing: AtomicBool,
    cancellation: HttpLegacyCancellationControl,
    /// Reverse request correlation is intentionally outside `session`.
    ///
    /// SAFETY: an exact-2024 handler may synchronously wait for a
    /// `sampling/createMessage` or `roots/list` response while its originating
    /// POST owns the serialized session mutex. The matching response POST must
    /// therefore route through this independently synchronized registry before
    /// attempting session mutation. Every nonmatching response continues
    /// through `ServerHttpSession::handle_async`, preserving serialized adapter and
    /// session-state mutation.
    legacy_pending_requests: Arc<PendingRequests>,
}

#[cfg(feature = "legacy-2024-11-05")]
enum LiveHttpSessionTake {
    Acquired(Box<ServerHttpSession>),
    Cancelled,
    Unavailable,
}

#[cfg(feature = "legacy-2024-11-05")]
fn take_live_http_session(
    cx: &Cx,
    session: &LiveHttpSession,
    request_cancellation: Option<&McpRequestCancellation>,
) -> LiveHttpSessionTake {
    let mut slot = session
        .session
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    loop {
        if request_cancellation.is_some_and(McpRequestCancellation::is_cancel_requested) {
            return LiveHttpSessionTake::Cancelled;
        }
        if session.closing.load(Ordering::Acquire)
            || cx.is_cancel_requested()
            || !session.cancellation.legacy_lifecycle.is_live()
        {
            return LiveHttpSessionTake::Unavailable;
        }
        if let Some(owned) = slot.take() {
            return LiveHttpSessionTake::Acquired(Box::new(owned));
        }
        (slot, _) = session
            .session_available
            .wait_timeout(slot, HTTP_ACCEPT_CANCEL_POLL)
            .unwrap_or_else(std::sync::PoisonError::into_inner);
    }
}

#[cfg(feature = "legacy-2024-11-05")]
async fn take_live_http_session_async(
    cx: &Cx,
    session: &LiveHttpSession,
    request_cancellation: Option<&McpRequestCancellation>,
) -> LiveHttpSessionTake {
    loop {
        {
            let mut slot = session
                .session
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if request_cancellation.is_some_and(McpRequestCancellation::is_cancel_requested) {
                return LiveHttpSessionTake::Cancelled;
            }
            if session.closing.load(Ordering::Acquire)
                || cx.is_cancel_requested()
                || !session.cancellation.legacy_lifecycle.is_live()
            {
                return LiveHttpSessionTake::Unavailable;
            }
            if let Some(owned) = slot.take() {
                return LiveHttpSessionTake::Acquired(Box::new(owned));
            }
        }
        // Caller-owned async handlers must stay on the inbound runtime, but
        // waiting for this serialized session must yield that reactor so a
        // reverse response or cancellation connection can still run.
        asupersync::time::sleep(cx.now(), HTTP_ACCEPT_CANCEL_POLL).await;
    }
}

#[cfg(feature = "legacy-2024-11-05")]
fn restore_live_http_session(
    session: &LiveHttpSession,
    mut owned: ServerHttpSession,
) -> Vec<asupersync::runtime::TaskHandle<()>> {
    let mut slot = session
        .session
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    debug_assert!(slot.is_none());
    if session.closing.load(Ordering::Acquire) {
        drop(slot);
        let dispatches = owned.begin_close();
        session.session_available.notify_all();
        return dispatches;
    }
    *slot = Some(owned);
    drop(slot);
    session.session_available.notify_one();
    Vec::new()
}

#[cfg(feature = "legacy-2024-11-05")]
type LiveHttpSessionRegistry = Arc<Mutex<HashMap<String, Arc<LiveHttpSession>>>>;

const MODERN_HTTP_RESPONSE_BODY_TTL: Duration = Duration::from_mins(15);
const MODERN_HTTP_SESSION_REAP_INTERVAL: Duration = Duration::from_secs(30);

/// Process-wide bounds for synchronous handler dispatch bridges.
///
/// `Cx::spawn_blocking` deliberately runs inline when an embedding runtime has
/// no blocking pool. That deterministic fallback is useful in the lab, but a
/// request must not let one synchronous handler occupy the reactor that
/// accepts its cancellation or reverse response. This lazy Asupersync
/// pool supplies only that missing blocking authority; it does not own an
/// async runtime or any transport task.
const MAX_BLOCKING_DISPATCH_THREADS: usize = 64;

const MAX_BLOCKING_DISPATCHES: usize = 256;

static BLOCKING_DISPATCHES: AtomicUsize = AtomicUsize::new(0);

struct BlockingDispatchPermit;

impl Drop for BlockingDispatchPermit {
    fn drop(&mut self) {
        BLOCKING_DISPATCHES.fetch_sub(1, Ordering::AcqRel);
    }
}

fn try_reserve_blocking_dispatch() -> Option<BlockingDispatchPermit> {
    BLOCKING_DISPATCHES
        .try_update(Ordering::AcqRel, Ordering::Acquire, |current| {
            (current < MAX_BLOCKING_DISPATCHES).then_some(current + 1)
        })
        .ok()
        .map(|_| BlockingDispatchPermit)
}

fn blocking_dispatch_pool() -> asupersync::runtime::BlockingPoolHandle {
    static POOL: std::sync::OnceLock<asupersync::runtime::BlockingPool> =
        std::sync::OnceLock::new();
    POOL.get_or_init(|| asupersync::runtime::BlockingPool::new(0, MAX_BLOCKING_DISPATCH_THREADS))
        .handle()
}

struct BlockingTaskGuard(asupersync::runtime::BlockingTaskHandle);

impl Drop for BlockingTaskGuard {
    fn drop(&mut self) {
        self.0.cancel();
    }
}

#[cfg(feature = "legacy-2024-11-05")]
enum LegacyHttpBlockingDispatchOutcome {
    Response(HttpResponse),
    Panicked,
}

#[cfg(feature = "legacy-2024-11-05")]
async fn quarantine_panicked_live_http_session(
    cx: &Cx,
    sessions: &LiveHttpSessionRegistry,
    session_id: &str,
) {
    let session = sessions
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .remove(session_id);
    if let Some(session) = session {
        session.closing.store(true, Ordering::Release);
        session.session_available.notify_all();
        session.cancellation.cancel_all_admitted_requests();
        session.legacy_pending_requests.cancel_all();
        let owned = session
            .session
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .take();
        if let Some(mut owned) = owned {
            owned.close(cx).await;
        }
    }
}

#[cfg(feature = "legacy-2024-11-05")]
async fn run_live_http_legacy_blocking_dispatch<F>(
    cx: &Cx,
    sessions: &LiveHttpSessionRegistry,
    panic_session_id: Option<String>,
    blocking_dispatch_permit: BlockingDispatchPermit,
    dispatch: F,
) -> Result<HttpResponse, ()>
where
    F: FnOnce(Cx) -> HttpResponse + Send + 'static,
{
    let panic_sessions = Arc::clone(sessions);
    let mut dispatch = cx
        .spawn(move |dispatch_cx| async move {
            let blocking_cx = dispatch_cx.clone();
            let (dispatch_sender, mut dispatch_receiver) = asupersync::channel::oneshot::channel();
            let blocking_dispatch = blocking_dispatch_pool().spawn(move || {
                let _blocking_dispatch_permit = blocking_dispatch_permit;
                // A pool thread is never the async driver (bd-6rfrg).
                let _lane = fastmcp_core::runtime::enter_blocking_lane();
                let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    dispatch(blocking_cx)
                }))
                .map_or_else(
                    |_| LegacyHttpBlockingDispatchOutcome::Panicked,
                    LegacyHttpBlockingDispatchOutcome::Response,
                );
                let _ = dispatch_sender.send_blocking(outcome);
            });
            let blocking_dispatch_guard = BlockingTaskGuard(blocking_dispatch);
            // A claimed blocking task cannot be force-stopped. Keep this
            // region child alive until the pool records terminal completion,
            // even after its Cx has been cancelled. The worker sends before
            // it returns, so observing `is_done` establishes that the final
            // channel drain cannot race an in-flight send.
            while !blocking_dispatch_guard.0.is_done() {
                asupersync::time::sleep(dispatch_cx.now(), Duration::from_millis(1)).await;
                // Sleep becomes ready immediately after cancellation. Yield
                // explicitly so retained blocking work cannot monopolize a
                // current-thread runtime while the listener transfers it.
                if dispatch_cx.is_cancel_requested() {
                    asupersync::runtime::yield_now().await;
                }
            }
            let outcome = dispatch_receiver.try_recv().ok();
            drop(blocking_dispatch_guard);
            match outcome {
                Some(LegacyHttpBlockingDispatchOutcome::Response(response)) => response,
                Some(LegacyHttpBlockingDispatchOutcome::Panicked) => {
                    if let Some(session_id) = panic_session_id.as_deref() {
                        quarantine_panicked_live_http_session(
                            &dispatch_cx,
                            &panic_sessions,
                            session_id,
                        )
                        .await;
                    }
                    HttpResponse::internal_error()
                }
                None => HttpResponse::new(HttpStatus::SERVICE_UNAVAILABLE),
            }
        })
        .map_err(|_| ())?;
    dispatch.join(cx).await.map_err(|_| ())
}

/// One response-body-owned modern HTTP session.
///
/// Modern Streamable HTTP has no listener-visible session identifier. This
/// owner exists only while an SSE response body needs its request-local
/// dispatch lifecycle. The endpoint, rather than this body, owns continuation
/// state across later stateless POSTs.
struct LiveModernHttpSession {
    server: Arc<Server>,
    session: Mutex<ServerHttpSession>,
    expires_at: Mutex<Instant>,
    modern_dispatches: ModernHttpDispatchRegistry,
    /// Phase one starts listener shutdown and rejects new work without
    /// interrupting an already-enqueued terminal SSE control frame.
    closing: AtomicBool,
    /// Phase two owns destructive endpoint/dispatch teardown after the
    /// listener's bounded terminal-control drain.
    finalized: AtomicBool,
}

struct LiveModernHttpSessionRegistryState {
    /// Every admitted response body is keyed only by a local opaque
    /// generation, never by a client-visible modern session identifier.
    sessions: Mutex<HashMap<u64, Arc<LiveModernHttpSession>>>,
    /// Aborted session dispatches remain listener-owned until their task
    /// completion is observed. Dropping a task handle would detach it.
    retired_dispatches: Mutex<Vec<asupersync::runtime::TaskHandle<()>>>,
    /// Closes response-body admission before phase one evacuates the current
    /// map, so a concurrent SSE POST cannot escape listener-owned teardown.
    closing: AtomicBool,
}

impl LiveModernHttpSessionRegistryState {
    fn new() -> Self {
        Self {
            sessions: Mutex::new(HashMap::new()),
            retired_dispatches: Mutex::new(Vec::new()),
            closing: AtomicBool::new(false),
        }
    }

    fn retain_retired_dispatches(&self, dispatches: Vec<asupersync::runtime::TaskHandle<()>>) {
        self.retired_dispatches
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .extend(dispatches);
    }

    fn register_response_body(
        &self,
        generation: u64,
        session: Arc<LiveModernHttpSession>,
    ) -> Result<(), Arc<LiveModernHttpSession>> {
        if self.closing.load(Ordering::Acquire) {
            return Err(session);
        }
        let mut sessions = self
            .sessions
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if self.closing.load(Ordering::Acquire) || sessions.contains_key(&generation) {
            return Err(session);
        }
        sessions.insert(generation, session);
        Ok(())
    }

    fn take_response_body(&self, generation: u64) -> Option<Arc<LiveModernHttpSession>> {
        self.sessions
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .remove(&generation)
    }

    fn reap_retired_dispatches(&self) {
        let mut dispatches = self
            .retired_dispatches
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let mut active = Vec::with_capacity(dispatches.len());
        for mut dispatch in std::mem::take(&mut *dispatches) {
            if matches!(dispatch.try_join(), Ok(None)) {
                active.push(dispatch);
            }
        }
        *dispatches = active;
    }

    fn take_retired_dispatches(&self) -> Vec<asupersync::runtime::TaskHandle<()>> {
        std::mem::take(
            &mut *self
                .retired_dispatches
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner),
        )
    }
}

type LiveModernHttpSessionRegistry = Arc<LiveModernHttpSessionRegistryState>;

impl LiveModernHttpSession {
    fn new(session: ServerHttpSession) -> Self {
        let modern_dispatches = Arc::clone(&session.modern_dispatches);
        Self {
            server: Arc::clone(&session.server),
            session: Mutex::new(session),
            expires_at: Mutex::new(Instant::now() + MODERN_HTTP_RESPONSE_BODY_TTL),
            modern_dispatches,
            closing: AtomicBool::new(false),
            finalized: AtomicBool::new(false),
        }
    }

    fn is_expired(&self, now: Instant) -> bool {
        *self
            .expires_at
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            <= now
    }

    #[cfg(test)]
    fn is_closing(&self) -> bool {
        self.closing.load(Ordering::Acquire)
    }

    /// Starts listener/TTL shutdown without closing the response queues that
    /// still own a server-elected terminal subscription frame.
    fn begin_shutdown_invalidation(&self) {
        self.closing.store(true, Ordering::Release);
    }

    fn register_modern_dispatch(
        &self,
        dispatch: OwnedModernHttpDispatch,
    ) -> Result<(), OwnedModernHttpDispatch> {
        if self.closing.load(Ordering::Acquire) {
            return Err(dispatch);
        }
        let mut dispatches = self
            .modern_dispatches
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if self.closing.load(Ordering::Acquire) {
            drop(dispatches);
            return Err(dispatch);
        }
        dispatches.push(dispatch);
        Ok(())
    }

    fn cancel_modern_dispatch(
        &self,
        owner_generation: u64,
    ) -> Vec<asupersync::runtime::TaskHandle<()>> {
        cancel_modern_http_dispatches(
            &self.server,
            &self.modern_dispatches,
            Some(owner_generation),
        )
    }

    fn reap_modern_dispatches(&self) {
        let mut dispatches = self
            .modern_dispatches
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let mut active = Vec::with_capacity(dispatches.len());
        for mut dispatch in std::mem::take(&mut *dispatches) {
            if matches!(dispatch.task.try_join(), Ok(None)) {
                active.push(dispatch);
            }
        }
        *dispatches = active;
    }

    /// Performs phase two after the bounded terminal-control drain, or
    /// immediately for TTL/peer-close teardown where no drain is required.
    fn finish_close(&self) -> Vec<asupersync::runtime::TaskHandle<()>> {
        self.begin_shutdown_invalidation();
        if self.finalized.swap(true, Ordering::AcqRel) {
            return Vec::new();
        }
        let dispatches = cancel_modern_http_dispatches(&self.server, &self.modern_dispatches, None);
        match self.session.try_lock() {
            Ok(mut session) => {
                let _ = session.begin_close();
            }
            Err(std::sync::TryLockError::Poisoned(poisoned)) => {
                let _ = poisoned.into_inner().begin_close();
            }
            Err(std::sync::TryLockError::WouldBlock) => {
                // The detached request still owns this `Arc`; it will finish
                // its synchronous section and fail closed on session drop.
            }
        }
        dispatches
    }
}

fn close_detached_modern_http_session(
    registry: &LiveModernHttpSessionRegistry,
    session: Arc<LiveModernHttpSession>,
) {
    registry.retain_retired_dispatches(session.finish_close());
}

fn expire_live_modern_http_sessions(registry: &LiveModernHttpSessionRegistry) {
    let now = Instant::now();
    let expired = {
        let mut sessions = registry
            .sessions
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let expired_ids = sessions
            .iter()
            .filter_map(|(id, session)| session.is_expired(now).then_some(*id))
            .collect::<Vec<_>>();
        expired_ids
            .into_iter()
            .filter_map(|id| sessions.remove(&id))
            .collect::<Vec<_>>()
    };
    for session in expired {
        close_detached_modern_http_session(registry, session);
    }
    registry.reap_retired_dispatches();
}

struct HttpConnectionLimiter {
    limit: usize,
    active: AtomicUsize,
}

impl HttpConnectionLimiter {
    const fn new(limit: usize) -> Self {
        Self {
            limit,
            active: AtomicUsize::new(0),
        }
    }

    fn try_acquire(self: &Arc<Self>) -> Option<HttpConnectionPermit> {
        let mut active = self.active.load(Ordering::Acquire);
        loop {
            if active >= self.limit {
                return None;
            }
            match self.active.compare_exchange_weak(
                active,
                active + 1,
                Ordering::AcqRel,
                Ordering::Acquire,
            ) {
                Ok(_) => {
                    return Some(HttpConnectionPermit {
                        limiter: Arc::clone(self),
                    });
                }
                Err(observed) => active = observed,
            }
        }
    }
}

struct HttpConnectionPermit {
    limiter: Arc<HttpConnectionLimiter>,
}

impl Drop for HttpConnectionPermit {
    fn drop(&mut self) {
        self.limiter.active.fetch_sub(1, Ordering::AcqRel);
    }
}

/// Tracks every connection child admitted by one live HTTP listener.
///
/// `TaskHandle` drop intentionally detaches in asupersync. The listener must
/// therefore retain every handle until it has observed normal completion or
/// the listener has reported an explicit nonquiescent outcome. The enclosing
/// caller-owned `Cx` region remains the runtime owner in the latter case;
/// shutdown never transfers unrelated work to a process-global registry.
#[derive(Default)]
struct HttpConnectionChildren {
    tasks: Vec<asupersync::runtime::TaskHandle<()>>,
    /// Panic and handle-consumption failures already observed by a nonblocking
    /// settlement poll. Cancellation is expected after listener shutdown and
    /// therefore is deliberately not recorded as a failed child.
    terminal_failures: Vec<String>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum HttpConnectionShutdown {
    Quiescent,
    Nonquiescent { remaining: usize },
}

/// The state of a caller-owned nonquiescent HTTP shutdown handle.
///
/// A `Pending` result means the listener's bounded shutdown drain expired,
/// but the connection task remains owned by this handle and its enclosing
/// asupersync region. It was neither detached nor transferred to global state.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HttpShutdownSettlement {
    /// Every retained connection child has completed and been observed.
    Settled,
    /// Every retained child has reached a terminal state, but one or more
    /// children panicked or violated the handle's single-consumption contract.
    Failed { failures: usize },
    /// The retained children are still live.
    Pending { remaining: usize },
}

/// Caller-owned settlement authority for a bounded, nonquiescent HTTP stop.
///
/// This handle retains every connection child that did not cooperate with the
/// listener's shutdown cancellation before its bounded drain elapsed. Call
/// [`Self::poll_settlement`] or [`Self::settle_for`] for bounded observation,
/// or [`Self::settle`] when the caller deliberately elects to await eventual
/// quiescence. Dropping the handle does not create FastMCP global retention;
/// the caller's asupersync region remains the task owner.
#[must_use = "a nonquiescent HTTP shutdown owns child handles that must be settled"]
pub struct HttpNonquiescentShutdown {
    children: HttpConnectionChildren,
    listener_error: Option<McpError>,
}

impl HttpNonquiescentShutdown {
    /// Returns the listener failure that accompanied this shutdown, if any.
    #[must_use]
    pub fn listener_error(&self) -> Option<&McpError> {
        self.listener_error.as_ref()
    }

    /// Reaps completed children without waiting.
    #[must_use]
    pub fn poll_settlement(&mut self) -> HttpShutdownSettlement {
        self.children.reap_finished();
        if self.children.tasks.is_empty() {
            if self.children.terminal_failures.is_empty() {
                HttpShutdownSettlement::Settled
            } else {
                HttpShutdownSettlement::Failed {
                    failures: self.children.terminal_failures.len(),
                }
            }
        } else {
            HttpShutdownSettlement::Pending {
                remaining: self.children.tasks.len(),
            }
        }
    }

    /// Waits no longer than `timeout` for cooperative completion.
    pub async fn settle_for(&mut self, timeout: Duration) -> HttpShutdownSettlement {
        let deadline = Instant::now() + timeout;
        loop {
            let settlement = self.poll_settlement();
            if matches!(
                settlement,
                HttpShutdownSettlement::Settled | HttpShutdownSettlement::Failed { .. }
            ) || Instant::now() >= deadline
            {
                return settlement;
            }
            asupersync::runtime::yield_now().await;
        }
    }

    /// Waits until each retained child has reached a terminal state.
    ///
    /// This is intentionally an explicit caller choice: synchronous code can
    /// ignore cancellation indefinitely, so FastMCP never performs this
    /// unbounded join inside the public listener shutdown path.
    pub async fn settle(mut self, cx: &Cx) -> McpResult<()> {
        self.children.reap_finished();
        let mut failures = std::mem::take(&mut self.children.terminal_failures);
        for mut child in std::mem::take(&mut self.children.tasks) {
            match child.join(cx).await {
                Ok(()) | Err(asupersync::runtime::JoinError::Cancelled(_)) => {}
                Err(error) => failures.push(error.to_string()),
            }
        }
        if failures.is_empty() {
            Ok(())
        } else {
            Err(McpError::internal_error(format!(
                "nonquiescent HTTP child settlement failed: {}",
                failures.join("; ")
            )))
        }
    }
}

/// The complete outcome of [`BoundHttpServer::serve`].
///
/// Normal shutdown returns [`Self::Quiescent`]. A bounded timeout returns
/// [`Self::Nonquiescent`] and transfers the still-live child handles directly
/// to the caller, preserving structured ownership without a global registry.
#[must_use = "a nonquiescent HTTP shutdown transfers child handles that must be settled"]
pub enum HttpServerShutdown {
    /// The listener stopped and every connection child was joined.
    Quiescent,
    /// The listener stopped, but this caller now owns explicit settlement of
    /// the retained connection children.
    Nonquiescent(HttpNonquiescentShutdown),
}

impl HttpConnectionChildren {
    fn reap_finished(&mut self) {
        let mut active = Vec::with_capacity(self.tasks.len());
        for mut task in std::mem::take(&mut self.tasks) {
            match task.try_join() {
                Ok(None) => active.push(task),
                Ok(Some(())) | Err(asupersync::runtime::JoinError::Cancelled(_)) => {}
                Err(error) => self.terminal_failures.push(error.to_string()),
            }
        }
        self.tasks = active;
    }

    /// Waits only for children which cooperate with the caller's cancellation.
    ///
    /// Do not abort the remaining children when the deadline elapses.
    /// `Cx::spawn_blocking` implements soft cancellation, so aborting its
    /// wrapper would discard the result while the synchronous closure still
    /// runs. Their caller-owned region remains responsible for eventual
    /// quiescence; this listener reports the bounded nonquiescent outcome
    /// rather than creating a global orphan-retention path.
    async fn drain_cooperative_shutdown(&mut self) -> HttpConnectionShutdown {
        let deadline = Instant::now() + HTTP_CONNECTION_SHUTDOWN_TIMEOUT;
        loop {
            self.reap_finished();
            if self.tasks.is_empty() {
                return HttpConnectionShutdown::Quiescent;
            }
            if Instant::now() >= deadline {
                return HttpConnectionShutdown::Nonquiescent {
                    remaining: self.tasks.len(),
                };
            }
            asupersync::runtime::yield_now().await;
        }
    }

    async fn drain_terminal_controls(&mut self, receipt: &FinalSubscriptionTerminationReceipt) {
        let deadline = Instant::now() + HTTP_TERMINAL_DRAIN_TIMEOUT;
        while !receipt.is_settled() && Instant::now() < deadline {
            self.reap_finished();
            if self.tasks.is_empty() {
                break;
            }
            asupersync::runtime::yield_now().await;
        }
        receipt.fail_pending();
    }
}

/// Closes every exact-2024 session still retained by the live listener.
///
/// A connection abort can interrupt `serve_http_connection` before its normal
/// post-SSE removal path runs. Evacuating the registry prevents a late legacy
/// POST from observing a detached-but-still-routable session. A busy legacy
/// handler may hold its session mutex while observing the server's earlier
/// cancellation signal, so this cleanup never waits on that mutex.
#[cfg(feature = "legacy-2024-11-05")]
async fn close_live_http_sessions(cx: &Cx, sessions: &LiveHttpSessionRegistry) {
    let sessions = {
        let mut sessions = sessions
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        std::mem::take(&mut *sessions)
    };
    let mut dispatches = Vec::new();
    for session in sessions.into_values() {
        session.closing.store(true, Ordering::Release);
        session.session_available.notify_all();
        // A busy exact-2024 handler may own `session.session`.  Cancellation
        // authority is deliberately independent so listener shutdown never
        // waits on that serialized mutex before revoking admitted work.
        session.cancellation.cancel_all_admitted_requests();
        match session.session.try_lock() {
            Ok(mut session) => {
                if let Some(session) = session.as_mut() {
                    dispatches.extend(session.begin_close());
                }
            }
            Err(std::sync::TryLockError::Poisoned(poisoned)) => {
                if let Some(session) = poisoned.into_inner().as_mut() {
                    dispatches.extend(session.begin_close());
                }
            }
            Err(std::sync::TryLockError::WouldBlock) => {
                // The owning connection child is cancelled and joined below.
                // Its local `ServerHttpSession` then closes on drop without
                // reintroducing this registry entry.
            }
        }
    }
    for mut dispatch in dispatches {
        let _ = dispatch.join(cx).await;
    }
}

/// Evacuates the listener-owned modern response-body registry before waiting
/// for terminal SSE control frames to flush. Listener shutdown has already
/// invalidated MRTR continuations separately.
fn detach_live_modern_http_sessions(
    sessions: &LiveModernHttpSessionRegistry,
) -> Vec<Arc<LiveModernHttpSession>> {
    sessions.closing.store(true, Ordering::Release);
    let sessions = {
        let mut sessions = sessions
            .sessions
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        std::mem::take(&mut *sessions)
            .into_values()
            .collect::<Vec<_>>()
    };
    for session in &sessions {
        session.begin_shutdown_invalidation();
    }
    sessions
}

/// Completes modern HTTP session teardown after the terminal-result drain.
///
/// Phase one already removed the response bodies from admission. This phase
/// may now cancel live SSE dispatches without suppressing the complete result
/// that was granted the listener's bounded drain window.
async fn finish_live_modern_http_sessions(
    registry: &LiveModernHttpSessionRegistry,
    sessions: Vec<Arc<LiveModernHttpSession>>,
) -> Vec<asupersync::runtime::TaskHandle<()>> {
    let mut dispatches = registry.take_retired_dispatches();
    for session in sessions {
        dispatches.extend(session.finish_close());
    }
    let deadline = Instant::now() + HTTP_TERMINAL_DRAIN_TIMEOUT;
    let mut pending = dispatches;
    while !pending.is_empty() && Instant::now() < deadline {
        let mut active = Vec::with_capacity(pending.len());
        for mut dispatch in pending {
            if matches!(dispatch.try_join(), Ok(None)) {
                active.push(dispatch);
            }
        }
        pending = active;
        if !pending.is_empty() {
            asupersync::runtime::yield_now().await;
        }
    }
    // A dispatch which outlives this bounded terminal-control drain remains
    // caller-owned shutdown debt. Do not abort and join it here: an abort is
    // cooperative for a blocking wrapper, and joining after the deadline
    // would turn the advertised bounded listener shutdown into an unbounded
    // wait. `BoundHttpServer::serve` transfers these handles into its
    // `HttpNonquiescentShutdown` outcome instead.
    pending
}

/// Collects dispatches retired concurrently with listener shutdown.
///
/// The reaper and connection children are drained before this runs, so no
/// task can subsequently add another listener-owned dispatch to this queue.
/// Completed handles are observed here; live ones remain attached to the
/// caller-owned nonquiescent settlement outcome.
fn take_unsettled_retired_modern_http_dispatches(
    registry: &LiveModernHttpSessionRegistry,
) -> Vec<asupersync::runtime::TaskHandle<()>> {
    let mut pending = Vec::new();
    for mut dispatch in registry.take_retired_dispatches() {
        if matches!(dispatch.try_join(), Ok(None)) {
            pending.push(dispatch);
        }
    }
    pending
}

/// Clone-shared authority for one live HTTP listener shutdown.
///
/// The listener's caller-owned `Cx` makes cancellation visible immediately;
/// the atomic retains the shutdown fence after the accept loop has observed
/// that cancellation (or exited for an error). Checking both closes the race
/// where a connection could commit a response between root cancellation and
/// the accept loop publishing its terminal state.
#[derive(Clone)]
struct HttpListenerShutdown {
    listener_cx: Cx,
    requested: Arc<AtomicBool>,
}

impl HttpListenerShutdown {
    fn new(listener_cx: &Cx) -> Self {
        Self {
            listener_cx: listener_cx.clone(),
            requested: Arc::new(AtomicBool::new(false)),
        }
    }

    fn request(&self) {
        self.requested.store(true, Ordering::Release);
    }

    fn is_requested(&self) -> bool {
        self.requested.load(Ordering::Acquire) || self.listener_cx.is_cancel_requested()
    }
}

/// A bound, caller-owned HTTP server lifecycle.
///
/// The listener and every accepted connection stay in the caller's [`Cx`]
/// region. Dropping the lifecycle closes its listener; cancelling that region
/// cancels the accept loop and all of its connection children together.
pub struct BoundHttpServer {
    listener: AsyncTcpListener,
    endpoint: Arc<ServerHttpEndpoint>,
    #[cfg(feature = "legacy-2024-11-05")]
    legacy_sessions: LiveHttpSessionRegistry,
    modern_sessions: LiveModernHttpSessionRegistry,
    connection_limiter: Arc<HttpConnectionLimiter>,
}

impl BoundHttpServer {
    /// Returns the address selected by the operating system for this listener.
    pub fn local_addr(&self) -> McpResult<SocketAddr> {
        self.listener.local_addr().map_err(|error| {
            McpError::internal_error(format!("HTTP listener address unavailable: {error}"))
        })
    }

    /// Accepts real HTTP/1.1 loopback or network connections until the caller
    /// cancels the owning context.
    ///
    /// Cooperative connection children are joined during shutdown. If a
    /// synchronous handler ignores cancellation, this method returns
    /// [`HttpServerShutdown::Nonquiescent`] after
    /// the bounded connection-shutdown wait instead of claiming a clean
    /// shutdown. The caller owns the returned settlement handle and chooses a
    /// further bounded observation or eventual join.
    ///
    /// The returned future is `Send`; this crate verifies that contract so
    /// downstream runtimes need not expand the listener's internal task graph.
    #[expect(
        clippy::manual_async_fn,
        reason = "explicit Send bounds keep the listener's proof inside this crate"
    )]
    pub fn serve(self, cx: &Cx) -> impl Future<Output = McpResult<HttpServerShutdown>> + Send + '_ {
        async move {
            let server = Arc::clone(&self.endpoint.server);
            server.init_rich_logging();
            if let Some(stats) = &server.stats {
                stats.connection_opened();
            }
            if !server.run_startup_hook() {
                server.graceful_shutdown_returning();
                return Err(McpError::internal_error("HTTP server startup hook failed"));
            }
            #[cfg(feature = "tasks")]
            let hosted_task_service = match server.start_hosted_task_service(cx).await {
                Ok(hosted) => hosted,
                Err(error) => {
                    server.graceful_shutdown_returning();
                    return Err(error);
                }
            };

            let connection_scope = cx.scope();
            let connection_shutdown = HttpListenerShutdown::new(cx);
            // Expired modern sessions are reaped from this accept loop, which
            // already wakes every HTTP_ACCEPT_CANCEL_POLL. A dedicated reaper
            // task had to be aborted and joined during shutdown, and that join
            // parked the whole listener shutdown (bd-f2ndd).
            let reap_interval_nanos =
                u64::try_from(MODERN_HTTP_SESSION_REAP_INTERVAL.as_nanos()).unwrap_or(u64::MAX);
            let mut last_session_reap = cx.now();
            let mut connection_children = HttpConnectionChildren::default();
            let result = loop {
                connection_children.reap_finished();
                if cx.checkpoint().is_err() {
                    break Ok(());
                }
                #[cfg(feature = "tasks")]
                if let Some(hosted) = hosted_task_service.as_ref()
                    && let Err(error) = hosted.check_running()
                {
                    break Err(error);
                }
                let now = cx.now();
                if now.duration_since(last_session_reap) >= reap_interval_nanos {
                    last_session_reap = now;
                    expire_live_modern_http_sessions(&self.modern_sessions);
                }
                #[cfg(test)]
                lib_unit_tests::record_live_http_listener_wait();
                let accepted = match asupersync::time::timeout(
                    cx.now(),
                    HTTP_ACCEPT_CANCEL_POLL,
                    self.listener.accept(),
                )
                .await
                {
                    Ok(accepted) => accepted,
                    Err(_) => continue,
                };
                let (stream, _peer_addr) = match accepted {
                    Ok(connection) => connection,
                    Err(_error) if cx.checkpoint().is_err() => break Ok(()),
                    Err(error) => {
                        break Err(McpError::internal_error(format!(
                            "HTTP listener accept failed: {error}"
                        )));
                    }
                };
                let Some(permit) = self.connection_limiter.try_acquire() else {
                    // A capacity rejection must not wait for a slow peer to read
                    // an HTTP error response. Dropping the socket applies the
                    // configured bound without creating an unbounded population
                    // of rejection tasks.
                    drop(stream);
                    continue;
                };
                let endpoint = Arc::clone(&self.endpoint);
                #[cfg(feature = "legacy-2024-11-05")]
                let legacy_sessions = Arc::clone(&self.legacy_sessions);
                let modern_sessions = Arc::clone(&self.modern_sessions);
                let listener_shutdown = connection_shutdown.clone();
                let connection = cx
                    .spawn_in(&connection_scope, move |connection_cx| async move {
                        let _permit = permit;
                        #[cfg(feature = "legacy-2024-11-05")]
                        {
                            // Keep the nested connection future's Send proof in
                            // this crate instead of exhausting downstream crates'
                            // default trait-recursion limit during code generation.
                            let connection: std::pin::Pin<
                                Box<dyn Future<Output = ()> + Send + '_>,
                            > = Box::pin(serve_http_connection(
                                &connection_cx,
                                stream,
                                endpoint,
                                legacy_sessions,
                                modern_sessions,
                                listener_shutdown,
                            ));
                            connection.await;
                        }
                        #[cfg(not(feature = "legacy-2024-11-05"))]
                        serve_modern_http_connection(
                            &connection_cx,
                            stream,
                            endpoint,
                            modern_sessions,
                            listener_shutdown,
                        )
                        .await;
                    })
                    .map_err(|error| {
                        McpError::internal_error(format!(
                            "HTTP connection task admission failed: {error}"
                        ))
                    });
                match connection {
                    Ok(connection) => connection_children.tasks.push(connection),
                    Err(error) => break Err(error),
                }
            };
            connection_shutdown.request();
            // Closing stateless issuance is a latched registry fence, not merely a
            // purge. A handler racing shutdown therefore cannot mint a new
            // cross-POST continuation after the existing set has been invalidated.
            let _ = server.router.close_stateless_mrtr_exchanges();
            // Final subscription teardown must commit its correlated cancellation
            // controls while the response writers are still owned. Give those
            // children a bounded scheduling window to flush and close before
            // aborting any unrelated or uncooperative connection.
            let terminal_receipt = server.final_subscriptions.terminate_with_receipt();
            #[cfg(feature = "legacy-2024-11-05")]
            close_live_http_sessions(cx, &self.legacy_sessions).await;
            // Phase one closes response-body admission before any uninterruptible
            // connection-child join can begin. Leave the SSE queues alive until
            // the elected terminal response has had its bounded opportunity to
            // flush.
            let closing_modern_sessions = detach_live_modern_http_sessions(&self.modern_sessions);
            connection_children
                .drain_terminal_controls(&terminal_receipt)
                .await;
            let unsettled_modern_dispatches =
                finish_live_modern_http_sessions(&self.modern_sessions, closing_modern_sessions)
                    .await;
            // Revoke request-owned authority before waiting for the connection
            // children. Cooperative handlers observe this and join structurally;
            // an ignored cancellation becomes a reported, retained shutdown debt.
            server.cancel_active_requests(CancelKind::Shutdown, false);
            connection_children
                .tasks
                .extend(unsettled_modern_dispatches);
            let connection_shutdown = connection_children.drain_cooperative_shutdown().await;
            connection_children
                .tasks
                .extend(take_unsettled_retired_modern_http_dispatches(
                    &self.modern_sessions,
                ));
            connection_children.reap_finished();
            #[cfg(feature = "tasks")]
            let task_service_result =
                Server::settle_hosted_task_service(hosted_task_service, cx).await;
            #[cfg(not(feature = "tasks"))]
            let task_service_result: McpResult<()> = Ok(());
            server.graceful_shutdown_returning();
            let result = result.and(task_service_result);
            match (connection_shutdown, connection_children.tasks.len()) {
                (_, 0) if connection_children.terminal_failures.is_empty() => {
                    result?;
                    Ok(HttpServerShutdown::Quiescent)
                }
                (_, 0) => Err(McpError::internal_error(format!(
                    "HTTP connection shutdown observed terminal child failure(s): {}",
                    connection_children.terminal_failures.join("; ")
                ))),
                (_, remaining) => {
                    debug_assert!(remaining > 0);
                    Ok(HttpServerShutdown::Nonquiescent(HttpNonquiescentShutdown {
                        children: connection_children,
                        listener_error: result.err(),
                    }))
                }
            }
        }
    }
}

// The WebSocket adapter owns one read/write object, while the established
// dual-era server dispatcher owns independent synchronous receive and send
// halves. Keep their bridge bounded in both directions; this preserves the
// dispatcher's mature cancellation and reverse-request semantics without
// giving a slow socket an unbounded in-memory queue.
#[cfg(feature = "websocket")]
const WEBSOCKET_BRIDGE_QUEUE_CAPACITY: usize = 64;
#[cfg(feature = "websocket")]
const WEBSOCKET_HANDSHAKE_MAX_BYTES: usize = 64 * 1024;
#[cfg(feature = "websocket")]
const WEBSOCKET_DRIVER_POLL_INTERVAL: Duration = Duration::from_millis(5);
#[cfg(feature = "websocket")]
const WEBSOCKET_CONNECTION_SHUTDOWN_TIMEOUT: Duration = Duration::from_secs(5);
/// Wake `accept` often enough that a cancelled listener Cx can leave the
/// accept loop without waiting for the next inbound connection.
#[cfg(feature = "websocket")]
const WEBSOCKET_ACCEPT_CANCEL_POLL: Duration = Duration::from_millis(20);
#[cfg(feature = "websocket")]
static NEXT_WEBSOCKET_AUTH_CONNECTION_GENERATION: AtomicU64 = AtomicU64::new(1);

/// A bound, caller-owned WebSocket listener.
///
/// Each accepted connection completes HTTP Upgrade before dispatch. A
/// ModernOnly listener drives independently owned native read/write halves
/// and request child regions without a blocking worker. Auto and LegacyOnly
/// retain the split dual-era dispatcher used by synchronous stdio. Protocol
/// binding, cancellation, and authentication remain connection scoped.
#[cfg(feature = "websocket")]
pub struct BoundWebSocketServer {
    listener: AsyncTcpListener,
    server: Arc<Server>,
    path: String,
    connection_limiter: Arc<HttpConnectionLimiter>,
}

/// Result of a WebSocket listener shutdown.
#[cfg(feature = "websocket")]
#[must_use = "a nonquiescent WebSocket shutdown retains connection children that must be settled"]
pub enum WebSocketServerShutdown {
    /// The listener stopped and every accepted socket task joined.
    Quiescent,
    /// The listener stopped, but the caller retains explicit connection work.
    Nonquiescent(WebSocketNonquiescentShutdown),
}

/// Caller-owned WebSocket connection work that outlived bounded shutdown.
#[cfg(feature = "websocket")]
#[must_use = "settle retained WebSocket connection children before discarding this outcome"]
pub struct WebSocketNonquiescentShutdown {
    children: WebSocketConnectionChildren,
    server: Arc<Server>,
    listener_error: Option<McpError>,
    shutdown_complete: bool,
}

#[cfg(feature = "websocket")]
impl WebSocketNonquiescentShutdown {
    /// Number of accepted connections that still require caller-owned settlement.
    #[must_use]
    pub const fn remaining_connections(&self) -> usize {
        self.children.tasks.len()
    }

    /// Returns the listener failure that ended acceptance, when one occurred.
    #[must_use]
    pub fn listener_error(&self) -> Option<&McpError> {
        self.listener_error.as_ref()
    }

    /// Observes retained children for at most `timeout`, without detaching them.
    ///
    /// Returns `Ok(true)` only when every child completed successfully. A
    /// recorded child failure takes precedence over a listener failure after
    /// all children have been observed and cleanup has run; `Ok(false)`
    /// retains caller-owned work.
    pub async fn settle_for(&mut self, timeout: Duration) -> McpResult<bool> {
        let deadline = Instant::now() + timeout;
        while !self.children.tasks.is_empty() && Instant::now() < deadline {
            self.children.reap_finished();
            if !self.children.tasks.is_empty() {
                asupersync::runtime::yield_now().await;
            }
        }
        if self.children.tasks.is_empty() {
            let terminal_failure = self.children.terminal_failure();
            let listener_error = self.listener_error.clone();
            if !self.shutdown_complete {
                self.server.graceful_shutdown_returning();
                self.shutdown_complete = true;
            }
            if let Some(error) = terminal_failure {
                Err(error)
            } else if let Some(error) = listener_error {
                Err(error)
            } else {
                Ok(true)
            }
        } else {
            Ok(false)
        }
    }

    /// Joins every retained connection in the caller's context.
    pub async fn settle(mut self, cx: &Cx) -> McpResult<()> {
        self.children.reap_finished();
        while let Some(mut child) = self.children.tasks.pop() {
            match child.join(cx).await {
                Ok(Ok(())) | Err(asupersync::runtime::JoinError::Cancelled(_)) => {}
                Ok(Err(error)) => self.children.record_failure(error.to_string()),
                Err(error) => self.children.record_failure(error.to_string()),
            }
        }
        let terminal_failure = self.children.terminal_failure();
        if !self.shutdown_complete {
            self.server.graceful_shutdown_returning();
            self.shutdown_complete = true;
        }
        if let Some(error) = terminal_failure {
            return Err(error);
        }
        if let Some(error) = self.listener_error {
            return Err(error);
        }
        Ok(())
    }
}

#[cfg(feature = "websocket")]
impl BoundWebSocketServer {
    /// Returns the address selected by the operating system for this listener.
    pub fn local_addr(&self) -> McpResult<SocketAddr> {
        self.listener.local_addr().map_err(|error| {
            McpError::internal_error(format!("WebSocket listener address unavailable: {error}"))
        })
    }

    /// Serves HTTP Upgrade and WebSocket MCP connections until `cx` is cancelled.
    pub async fn serve(self, cx: &Cx) -> McpResult<WebSocketServerShutdown> {
        self.server.init_rich_logging();
        if let Some(stats) = &self.server.stats {
            stats.connection_opened();
        }
        if !self.server.run_startup_hook() {
            self.server.graceful_shutdown_returning();
            return Err(McpError::internal_error(
                "WebSocket server startup hook failed",
            ));
        }
        #[cfg(feature = "tasks")]
        let hosted_task_service = match self.server.start_hosted_task_service(cx).await {
            Ok(hosted) => hosted,
            Err(error) => {
                self.server.graceful_shutdown_returning();
                return Err(error);
            }
        };

        let connection_scope = cx.scope();
        let mut children = WebSocketConnectionChildren::default();
        let accept_result = loop {
            children.reap_finished();
            if cx.checkpoint().is_err() {
                break Ok(());
            }
            #[cfg(feature = "tasks")]
            if let Some(hosted) = hosted_task_service.as_ref()
                && let Err(error) = hosted.check_running()
            {
                break Err(error);
            }
            let accepted = match asupersync::time::timeout(
                cx.now(),
                WEBSOCKET_ACCEPT_CANCEL_POLL,
                self.listener.accept(),
            )
            .await
            {
                Ok(accepted) => accepted,
                Err(_) => continue,
            };
            let (stream, _) = match accepted {
                Ok(connection) => connection,
                Err(_) if cx.checkpoint().is_err() => break Ok(()),
                Err(error) => {
                    break Err(McpError::internal_error(format!(
                        "WebSocket listener accept failed: {error}"
                    )));
                }
            };
            // Acquire before spawning so an overflow peer cannot create a
            // retained connection child.  The permit moves into that child
            // and therefore covers handshake, upgraded socket, dispatch, and
            // its caller-owned nonquiescent settlement lifetime.
            let Some(permit) = self.connection_limiter.try_acquire() else {
                drop(stream);
                continue;
            };
            let server = Arc::clone(&self.server);
            let path = self.path.clone();
            let terminal_failure = Arc::clone(&children.terminal_failure);
            match cx.spawn_in(&connection_scope, move |connection_cx| async move {
                let _permit = permit;
                let result =
                    serve_websocket_connection(&connection_cx, stream, server, &path).await;
                if let Err(error) = &result {
                    terminal_failure
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .get_or_insert_with(|| error.to_string());
                }
                result
            }) {
                Ok(child) => children.tasks.push(child),
                Err(error) => {
                    break Err(McpError::internal_error(format!(
                        "WebSocket connection task admission failed: {error}"
                    )));
                }
            }
        };

        // Capture failures that completed while `accept` was parked before
        // aborting live children. Otherwise an abort could turn an already
        // terminal task into an indistinguishable cancellation outcome.
        children.reap_finished();
        for child in &mut children.tasks {
            child.abort();
        }
        let deadline = Instant::now() + WEBSOCKET_CONNECTION_SHUTDOWN_TIMEOUT;
        while !children.tasks.is_empty() && Instant::now() < deadline {
            children.reap_finished();
            if !children.tasks.is_empty() {
                asupersync::runtime::yield_now().await;
            }
        }
        #[cfg(feature = "tasks")]
        let task_service_result = Server::settle_hosted_task_service(hosted_task_service, cx).await;
        #[cfg(not(feature = "tasks"))]
        let task_service_result: McpResult<()> = Ok(());
        let accept_result = accept_result.and(task_service_result);
        if children.tasks.is_empty() {
            let terminal_failure = children.terminal_failure();
            self.server.graceful_shutdown_returning();
            if let Some(error) = terminal_failure {
                return Err(error);
            }
            accept_result?;
            Ok(WebSocketServerShutdown::Quiescent)
        } else {
            Ok(WebSocketServerShutdown::Nonquiescent(
                WebSocketNonquiescentShutdown {
                    children,
                    server: Arc::clone(&self.server),
                    listener_error: accept_result.err(),
                    shutdown_complete: false,
                },
            ))
        }
    }
}

#[cfg(feature = "websocket")]
#[derive(Default)]
struct WebSocketConnectionChildren {
    tasks: Vec<asupersync::runtime::TaskHandle<McpResult<()>>>,
    /// The first connection failure observed by a nonblocking reaper. Later
    /// failures are still drained, but cannot overwrite the original causal
    /// failure presented to the lifecycle caller.
    terminal_failure: Arc<Mutex<Option<String>>>,
}

#[cfg(feature = "websocket")]
impl WebSocketConnectionChildren {
    fn record_failure(&self, failure: String) {
        self.terminal_failure
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .get_or_insert(failure);
    }

    fn terminal_failure(&self) -> Option<McpError> {
        self.terminal_failure
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .as_ref()
            .map(|failure| {
                McpError::internal_error(format!(
                    "WebSocket connection child settlement failure: {failure}"
                ))
            })
    }

    #[cfg(test)]
    fn has_terminal_failure(&self) -> bool {
        self.terminal_failure
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .is_some()
    }

    fn reap_finished(&mut self) {
        let mut active = Vec::with_capacity(self.tasks.len());
        for mut child in std::mem::take(&mut self.tasks) {
            match child.try_join() {
                Ok(None) => active.push(child),
                Ok(Some(Ok(()))) | Err(asupersync::runtime::JoinError::Cancelled(_)) => {}
                Ok(Some(Err(error))) => self.record_failure(error.to_string()),
                Err(error) => self.record_failure(error.to_string()),
            }
        }
        self.tasks = active;
    }
}

#[cfg(feature = "websocket")]
struct PrefixedWebSocketStream {
    prefix: Vec<u8>,
    stream: AsyncTcpStream,
}

#[cfg(feature = "websocket")]
impl AsyncRead for PrefixedWebSocketStream {
    fn poll_read(
        mut self: Pin<&mut Self>,
        task_cx: &mut Context<'_>,
        buffer: &mut ReadBuf<'_>,
    ) -> Poll<std::io::Result<()>> {
        if !self.prefix.is_empty() {
            let count = self.prefix.len().min(buffer.unfilled().len());
            buffer.put_slice(&self.prefix[..count]);
            self.prefix.drain(..count);
            return Poll::Ready(Ok(()));
        }
        Pin::new(&mut self.stream).poll_read(task_cx, buffer)
    }
}

#[cfg(feature = "websocket")]
impl AsyncWrite for PrefixedWebSocketStream {
    fn poll_write(
        mut self: Pin<&mut Self>,
        task_cx: &mut Context<'_>,
        buffer: &[u8],
    ) -> Poll<std::io::Result<usize>> {
        Pin::new(&mut self.stream).poll_write(task_cx, buffer)
    }

    fn poll_flush(
        mut self: Pin<&mut Self>,
        task_cx: &mut Context<'_>,
    ) -> Poll<std::io::Result<()>> {
        Pin::new(&mut self.stream).poll_flush(task_cx)
    }

    fn poll_shutdown(
        mut self: Pin<&mut Self>,
        task_cx: &mut Context<'_>,
    ) -> Poll<std::io::Result<()>> {
        Pin::new(&mut self.stream).poll_shutdown(task_cx)
    }
}

#[cfg(feature = "websocket")]
struct WebSocketBridgeRecv {
    receiver: asupersync_mpsc::Receiver<JsonRpcMessage>,
}

#[cfg(feature = "websocket")]
impl TransportRecvHalf for WebSocketBridgeRecv {
    fn recv(&mut self, cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
        loop {
            cx.checkpoint().map_err(|_| TransportError::Cancelled)?;
            match self.receiver.try_recv() {
                Ok(message) => return Ok(message),
                Err(asupersync_mpsc::RecvError::Empty) => {
                    // This bridge is polled only by the dispatcher blocking
                    // worker. The owned async socket task retains admission
                    // and cancellation authority; a short yield keeps this
                    // compatibility boundary from parking a global thread.
                    std::thread::sleep(WEBSOCKET_DRIVER_POLL_INTERVAL);
                }
                Err(asupersync_mpsc::RecvError::Disconnected) => {
                    return Err(TransportError::Closed);
                }
                Err(asupersync_mpsc::RecvError::Cancelled) => {
                    return Err(TransportError::Cancelled);
                }
            }
        }
    }

    fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
        self.receiver.close();
        Ok(())
    }
}

#[cfg(feature = "websocket")]
struct WebSocketBridgeSend {
    sender: asupersync_mpsc::Sender<JsonRpcMessage>,
}

#[cfg(feature = "websocket")]
impl TransportSendHalf for WebSocketBridgeSend {
    fn send(&mut self, cx: &Cx, message: &JsonRpcMessage) -> Result<(), TransportError> {
        cx.checkpoint().map_err(|_| TransportError::Cancelled)?;
        let result = match self.sender.try_reserve() {
            Ok(permit) => permit.try_send(message.clone()),
            Err(asupersync_mpsc::SendError::Full(())) => {
                return Err(TransportError::Io(std::io::Error::from(
                    std::io::ErrorKind::WouldBlock,
                )));
            }
            Err(
                asupersync_mpsc::SendError::Disconnected(())
                | asupersync_mpsc::SendError::Cancelled(()),
            ) => return Err(TransportError::Closed),
        };
        result.map_err(|error| match error {
            asupersync_mpsc::SendError::Full(_) => {
                TransportError::Io(std::io::Error::from(std::io::ErrorKind::WouldBlock))
            }
            asupersync_mpsc::SendError::Disconnected(_)
            | asupersync_mpsc::SendError::Cancelled(_) => TransportError::Closed,
        })
    }

    fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
        Ok(())
    }
}

#[cfg(feature = "websocket")]
async fn serve_websocket_connection(
    cx: &Cx,
    mut stream: AsyncTcpStream,
    server: Arc<Server>,
    expected_path: &str,
) -> McpResult<()> {
    let read_timeout = server.http_config.request_read_timeout;
    let (request, trailing) = match read_websocket_handshake(cx, &mut stream, read_timeout).await {
        Ok(handshake) => handshake,
        Err(error) => {
            let rejection = if error.message == "WebSocket Authorization admission failed" {
                b"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Bearer\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
                    .to_vec()
            } else {
                asupersync::net::websocket::ServerHandshake::reject(400, "Bad Request")
            };
            let _ = stream.write_all(&rejection).await;
            return Ok(());
        }
    };
    let path = request
        .path
        .split_once('?')
        .map_or(request.path.as_str(), |(path, _)| path);
    if path != expected_path {
        stream
            .write_all(&asupersync::net::websocket::ServerHandshake::reject(
                404,
                "Not Found",
            ))
            .await
            .map_err(|_| {
                McpError::internal_error("WebSocket route rejection could not be written")
            })?;
        return Ok(());
    }
    let transport_authorization =
        TransportAuthorization::from_singleton_header(request.header("authorization"));
    let connection_generation =
        NEXT_WEBSOCKET_AUTH_CONNECTION_GENERATION.fetch_add(1, Ordering::AcqRel);
    let auth_custody = match server.authenticate_websocket_upgrade(
        cx,
        &transport_authorization,
        connection_generation,
    ) {
        Ok(receipt) => receipt,
        Err(_) => {
            stream
                .write_all(
                    b"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Bearer\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
                )
                .await
                .map_err(|_| {
                    McpError::internal_error("WebSocket authorization rejection could not be written")
                })?;
            return Ok(());
        }
    };
    let response = match asupersync::net::websocket::ServerHandshake::new().accept(&request) {
        Ok(response) => response,
        Err(_) => {
            stream
                .write_all(&asupersync::net::websocket::ServerHandshake::reject(
                    400,
                    "Bad Request",
                ))
                .await
                .map_err(|_| {
                    McpError::internal_error("WebSocket handshake rejection could not be written")
                })?;
            return Ok(());
        }
    };
    stream
        .write_all(&response.response_bytes())
        .await
        .map_err(|_| McpError::internal_error("WebSocket upgrade response could not be written"))?;
    stream
        .flush()
        .await
        .map_err(|_| McpError::internal_error("WebSocket upgrade response could not be flushed"))?;

    let transport = AsyncWsServerTransport::from_upgraded(PrefixedWebSocketStream {
        prefix: trailing,
        stream,
    });
    if server.protocol_policy == ProtocolPolicy::ModernOnly {
        return server
            .serve_modern_websocket(
                cx,
                transport,
                transport_authorization,
                auth_custody,
                connection_generation,
            )
            .await;
    }
    run_websocket_dispatch_bridge(
        cx,
        server,
        transport,
        transport_authorization,
        auth_custody,
        connection_generation,
    )
    .await
}

#[cfg(feature = "websocket")]
async fn read_websocket_handshake(
    cx: &Cx,
    stream: &mut AsyncTcpStream,
    read_timeout: Duration,
) -> McpResult<(asupersync::net::websocket::HttpRequest, Vec<u8>)> {
    let mut bytes = Vec::with_capacity(1024);
    let mut chunk = [0_u8; 1024];
    // The upgrade is an HTTP request: the listener's request-read deadline
    // keeps an idle or trickling peer from holding a connection slot.
    let deadline = cx
        .now()
        .saturating_add_nanos(u64::try_from(read_timeout.as_nanos()).unwrap_or(u64::MAX));
    loop {
        cx.checkpoint()
            .map_err(|_| McpError::internal_error("WebSocket handshake cancelled"))?;
        let now = cx.now();
        if now >= deadline {
            return Err(McpError::invalid_request(
                "WebSocket handshake was not received in time",
            ));
        }
        let wait = HTTP_ACCEPT_CANCEL_POLL.min(Duration::from_nanos(deadline.duration_since(now)));
        let Ok(read) = asupersync::time::timeout(now, wait, stream.read(&mut chunk)).await else {
            continue;
        };
        let read =
            read.map_err(|_| McpError::invalid_request("WebSocket handshake could not be read"))?;
        if read == 0 {
            return Err(McpError::invalid_request(
                "WebSocket handshake ended before completion",
            ));
        }
        if bytes
            .len()
            .checked_add(read)
            .is_none_or(|length| length > WEBSOCKET_HANDSHAKE_MAX_BYTES)
        {
            return Err(McpError::invalid_request(
                "WebSocket handshake headers exceed the limit",
            ));
        }
        bytes.extend_from_slice(&chunk[..read]);
        if let Some(header_end) = bytes.windows(4).position(|window| window == b"\r\n\r\n") {
            let header_block = &bytes[..header_end];
            if raw_websocket_upgrade_authorization_is_admissible(header_block).is_err() {
                return Err(McpError::invalid_request(
                    "WebSocket Authorization admission failed",
                ));
            }
            if raw_websocket_upgrade_headers_are_well_formed(header_block).is_err() {
                return Err(McpError::invalid_request("WebSocket handshake is invalid"));
            }
            if !raw_websocket_upgrade_origin_is_admissible(header_block) {
                return Err(McpError::invalid_request("WebSocket Origin is not allowed"));
            }
        }
        match asupersync::net::websocket::HttpRequest::parse_with_trailing(&bytes) {
            Ok((request, trailing)) => return Ok((request, trailing.to_vec())),
            Err(_) if !bytes.windows(4).any(|window| window == b"\r\n\r\n") => {}
            Err(_) => return Err(McpError::invalid_request("WebSocket handshake is invalid")),
        }
    }
}

#[cfg(feature = "websocket")]
fn raw_websocket_upgrade_headers_are_well_formed(head: &[u8]) -> Result<(), ()> {
    let head = std::str::from_utf8(head).map_err(|_| ())?;
    let mut lines = head.split("\r\n");
    if lines.next().is_none_or(str::is_empty) {
        return Err(());
    }
    for line in lines {
        let (name, _) = line.split_once(':').ok_or(())?;
        if name.is_empty()
            || !name
                .bytes()
                .all(|byte| byte.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&byte))
        {
            return Err(());
        }
    }
    Ok(())
}

/// Cross-site WebSocket hijacking protection: a browser always sends
/// `Origin` on a WebSocket upgrade, and the server-side transport has no CORS
/// allowlist, so a present `Origin` must be a loopback origin (the same
/// admission policy the HTTP routes apply by default). Non-browser clients
/// that send no `Origin` are unaffected.
#[cfg(feature = "websocket")]
fn raw_websocket_upgrade_origin_is_admissible(head: &[u8]) -> bool {
    let Ok(head) = std::str::from_utf8(head) else {
        // Left to the handshake parser's generic bounded 400 path.
        return true;
    };
    let mut origins = head.split("\r\n").skip(1).filter_map(|line| {
        line.split_once(':')
            .filter(|(name, _)| name.eq_ignore_ascii_case("origin"))
            .map(|(_, value)| value.trim())
    });
    match (origins.next(), origins.next()) {
        (None, _) => true,
        (Some(origin), None) => HttpHandlerConfig::default().admits_origin(origin),
        // A repeated Origin is ambiguous; refuse rather than pick one.
        (Some(_), Some(_)) => false,
    }
}

#[cfg(feature = "websocket")]
fn raw_websocket_upgrade_authorization_is_admissible(head: &[u8]) -> Result<(), ()> {
    let Ok(head) = std::str::from_utf8(head) else {
        // This is not an Authorization-specific admission failure; leave it
        // to the handshake parser's generic bounded 400 path.
        return Ok(());
    };
    let mut authorization = None;
    for line in head.split("\r\n").skip(1) {
        let malformed_authorization_intent = line
            .split_once(':')
            .map(|(name, _)| name.trim())
            .or_else(|| line.split_ascii_whitespace().next())
            .is_some_and(|name| name.eq_ignore_ascii_case("authorization"));
        let Some((name, value)) = line.split_once(':') else {
            if malformed_authorization_intent {
                return Err(());
            }
            continue;
        };
        let normalized_name = name.trim();
        if normalized_name.eq_ignore_ascii_case("authorization") {
            // OWS belongs after the colon, never in an HTTP field-name.
            // Treat an Authorization-shaped malformed line as an auth denial
            // so it cannot fall through to the generic Upgrade 400 path.
            if name != normalized_name
                || value.trim().is_empty()
                || authorization.replace(value).is_some()
            {
                return Err(());
            }
        }
    }
    Ok(())
}

#[cfg(feature = "websocket")]
async fn run_websocket_dispatch_bridge(
    cx: &Cx,
    server: Arc<Server>,
    mut transport: AsyncWsServerTransport<PrefixedWebSocketStream>,
    transport_authorization: TransportAuthorization,
    auth_custody: Arc<WebSocketAuthCustody>,
    connection_generation: u64,
) -> McpResult<()> {
    let (incoming_sender, incoming_receiver) =
        asupersync_mpsc::channel(WEBSOCKET_BRIDGE_QUEUE_CAPACITY);
    let (outgoing_sender, mut outgoing_receiver) =
        asupersync_mpsc::channel(WEBSOCKET_BRIDGE_QUEUE_CAPACITY);
    let dispatch_cx = cx.clone();
    let dispatcher_custody = Arc::clone(&auth_custody);
    let mut dispatcher = cx
        .spawn_blocking(move |pump_cx| {
            server.run_split_transport_returning_shared_with_dispatch_cx(
                &pump_cx,
                &dispatch_cx,
                WebSocketBridgeRecv {
                    receiver: incoming_receiver,
                },
                WebSocketBridgeSend {
                    sender: outgoing_sender,
                },
                transport_authorization,
                AuthDispatchCustody::WebSocket(dispatcher_custody),
                connection_generation,
            )
        })
        .map_err(|error| {
            McpError::internal_error(format!("WebSocket dispatch admission failed: {error}"))
        })?;

    let driver_result = 'driver: loop {
        loop {
            match outgoing_receiver.try_recv() {
                Ok(message) => transport.send(cx, &message).await.map_err(|_| {
                    McpError::internal_error("WebSocket response could not be committed")
                })?,
                Err(asupersync_mpsc::RecvError::Empty) => break,
                Err(asupersync_mpsc::RecvError::Disconnected) => break 'driver Ok(()),
                Err(asupersync_mpsc::RecvError::Cancelled) => break 'driver Ok(()),
            }
        }
        if cx.checkpoint().is_err() {
            break Ok(());
        }
        let deadline = cx.now() + WEBSOCKET_DRIVER_POLL_INTERVAL;
        match asupersync::time::timeout_at(deadline, transport.recv(cx)).await {
            Ok(Ok(mut message)) => {
                if let JsonRpcMessage::Request(request) = &mut message {
                    // Strict frame decode is the last point raw in-band
                    // credentials exist. Sanitize before traffic rendering,
                    // logs, queues, or router visibility; custody remembers a
                    // rejected mixed-source frame for its later auth fence.
                    sanitize_websocket_decoded_request(&auth_custody, request);
                }
                let permit = match incoming_sender.reserve(cx).await {
                    Ok(permit) => permit,
                    Err(
                        asupersync_mpsc::SendError::Disconnected(())
                        | asupersync_mpsc::SendError::Cancelled(()),
                    ) => break Ok(()),
                    Err(asupersync_mpsc::SendError::Full(())) => {
                        break Err(McpError::internal_error("WebSocket ingress queue is full"));
                    }
                };
                if let Err(error) = permit.try_send(message) {
                    break match error {
                        asupersync_mpsc::SendError::Full(_) => {
                            Err(McpError::internal_error("WebSocket ingress queue is full"))
                        }
                        asupersync_mpsc::SendError::Disconnected(_)
                        | asupersync_mpsc::SendError::Cancelled(_) => Ok(()),
                    };
                }
            }
            Ok(Err(TransportError::Closed | TransportError::Cancelled)) => break Ok(()),
            Ok(Err(_)) => break Err(McpError::invalid_request("WebSocket frame was rejected")),
            Err(_) => {}
        }
    };
    drop(incoming_sender);
    let _ = transport.close(cx).await;
    let dispatch_result = dispatcher.join(cx).await.map_err(|error| {
        McpError::internal_error(format!("WebSocket dispatch worker failed: {error}"))
    })?;
    match (driver_result, dispatch_result) {
        (Ok(()), Ok(())) => Ok(()),
        (Err(error), Ok(())) | (Ok(()), Err(error)) => Err(error),
        (Err(driver), Err(dispatch)) => Err(combined_run_and_close_error(driver, dispatch)),
    }
}

#[cfg(feature = "websocket")]
impl Server {
    /// Binds a turnkey WebSocket MCP listener on the caller-owned context.
    ///
    /// The upgrade route is the configured [`HttpServerConfig`] MCP path, so
    /// one server configuration cannot accidentally expose different HTTP and
    /// WebSocket entry points. This method only binds; call
    /// [`BoundWebSocketServer::serve`] to accept connections.
    pub async fn bind_websocket(
        self,
        cx: &Cx,
        addr: impl Into<String>,
    ) -> McpResult<BoundWebSocketServer> {
        cx.checkpoint()
            .map_err(|_| McpError::internal_error("WebSocket bind was cancelled"))?;
        let listener = AsyncTcpListener::bind(addr.into()).await.map_err(|error| {
            McpError::internal_error(format!("WebSocket listener bind failed: {error}"))
        })?;
        Ok(BoundWebSocketServer {
            listener,
            path: self.http_config.handler_config.base_path.clone(),
            connection_limiter: Arc::new(HttpConnectionLimiter::new(
                self.http_config.max_connections,
            )),
            server: Arc::new(self),
        })
    }

    /// Binds and serves a turnkey WebSocket MCP bridge until `cx` is cancelled.
    pub async fn serve_websocket(
        self,
        cx: &Cx,
        addr: impl Into<String>,
    ) -> McpResult<WebSocketServerShutdown> {
        self.bind_websocket(cx, addr).await?.serve(cx).await
    }

    /// Alias for [`Self::serve_websocket`] for callers that use `run_*` APIs.
    pub async fn run_websocket(
        self,
        cx: &Cx,
        addr: impl Into<String>,
    ) -> McpResult<WebSocketServerShutdown> {
        self.serve_websocket(cx, addr).await
    }
}

impl Server {
    /// Consumes this server into a live HTTP endpoint.
    ///
    /// Modern Streamable HTTP remains at the configured MCP path.
    #[cfg(not(feature = "legacy-2024-11-05"))]
    pub fn into_http_endpoint(self) -> Result<ServerHttpEndpoint, ServerHttpEndpointError> {
        validate_server_http_route_configuration(&self)?;
        let endpoint = ServerHttpEndpoint {
            server: Arc::new(self),
        };
        let _ = endpoint
            .transport_endpoint()
            .map_err(ServerHttpEndpointError::from_internal)?;
        Ok(endpoint)
    }

    /// Consumes this server into a live dual-era HTTP endpoint.
    ///
    /// `legacy_origin` is used only for the exact MCP 2024-11-05 SSE endpoint
    /// event. Modern Streamable HTTP remains at the configured MCP path.
    #[cfg(feature = "legacy-2024-11-05")]
    pub fn into_http_endpoint(
        self,
        legacy_origin: impl Into<String>,
    ) -> Result<ServerHttpEndpoint, ServerHttpEndpointError> {
        validate_server_http_route_configuration(&self)?;
        let endpoint = ServerHttpEndpoint {
            server: Arc::new(self),
            legacy_origin: legacy_origin.into(),
        };
        let _ = endpoint
            .transport_endpoint(&endpoint.legacy_origin)
            .map_err(ServerHttpEndpointError::from_internal)?;
        Ok(endpoint)
    }

    /// Binds the HTTP listener on the caller-owned [`Cx`].
    ///
    /// This performs only listener setup. Call [`BoundHttpServer::serve`] to
    /// accept connections, or use [`Self::serve_http`] for the turnkey
    /// lifecycle. In a legacy-enabled build, the exact SSE endpoint derives
    /// its advertised authority from the client's `Host` header, with the
    /// resolved local address as the fallback for direct embeddings.
    pub async fn bind_http(self, cx: &Cx, addr: impl Into<String>) -> McpResult<BoundHttpServer> {
        if cx.checkpoint().is_err() {
            return Err(McpError::request_cancelled());
        }
        let listener = AsyncTcpListener::bind(addr.into()).await.map_err(|error| {
            McpError::internal_error(format!("HTTP listener bind failed: {error}"))
        })?;
        let max_connections = self.http_config.max_connections;
        #[cfg(feature = "legacy-2024-11-05")]
        let local_addr = listener.local_addr().map_err(|error| {
            McpError::internal_error(format!("HTTP listener address unavailable: {error}"))
        })?;
        #[cfg(feature = "legacy-2024-11-05")]
        let endpoint = self
            .into_http_endpoint(format!("http://{local_addr}"))
            .map_err(|error| {
                McpError::internal_error(format!("HTTP endpoint setup failed: {error}"))
            })?;
        #[cfg(not(feature = "legacy-2024-11-05"))]
        let endpoint = self.into_http_endpoint().map_err(|error| {
            McpError::internal_error(format!("HTTP endpoint setup failed: {error}"))
        })?;
        Ok(BoundHttpServer {
            listener,
            endpoint: Arc::new(endpoint),
            #[cfg(feature = "legacy-2024-11-05")]
            legacy_sessions: Arc::new(Mutex::new(HashMap::new())),
            modern_sessions: Arc::new(LiveModernHttpSessionRegistryState::new()),
            connection_limiter: Arc::new(HttpConnectionLimiter::new(max_connections)),
        })
    }

    /// Binds and accepts a turnkey HTTP server on the caller's context. This
    /// method never creates or owns an async runtime.
    pub async fn serve_http(
        self,
        cx: &Cx,
        addr: impl Into<String>,
    ) -> McpResult<HttpServerShutdown> {
        self.bind_http(cx, addr).await?.serve(cx).await
    }
}

impl ServerHttpEndpoint {
    /// Opens one independently bounded live HTTP session.
    ///
    /// Repeated calls through the returned embedding handle share modern
    /// mutable component state. Turnkey live ingress calls this method afresh
    /// for each stateless POST. Eligible MRTR continuations are represented by
    /// router-owned opaque, single-use state and may be resumed by a later
    /// stateless POST only when its operation and principal bindings match.
    pub fn open_session(&self, cx: &Cx) -> Result<ServerHttpSession, ServerHttpEndpointError> {
        #[cfg(feature = "legacy-2024-11-05")]
        let session = self.open_session_with_legacy_origin(cx, &self.legacy_origin);
        #[cfg(not(feature = "legacy-2024-11-05"))]
        let session = self.open_session_modern(cx);
        session.map_err(ServerHttpEndpointError::from_internal)
    }

    #[cfg(feature = "legacy-2024-11-05")]
    fn transport_endpoint(
        &self,
        legacy_origin: &str,
    ) -> Result<DualEraHttpEndpoint, DualEraHttpEndpointError> {
        let mut config = DualEraHttpEndpointConfig::new(
            self.server.http_config.legacy_sse_path.clone(),
            self.server.http_config.legacy_message_path.clone(),
            legacy_origin,
        );
        config.legacy_request_capacity = self.server.http_config.request_capacity;
        DualEraHttpEndpoint::new(
            HttpRequestHandler::with_config(self.server.http_config.handler_config.clone()),
            config,
        )
    }

    #[cfg(not(feature = "legacy-2024-11-05"))]
    fn transport_endpoint(&self) -> Result<DualEraHttpEndpoint, DualEraHttpEndpointError> {
        let mut config = DualEraHttpEndpointConfig::new();
        config.request_capacity = self.server.http_config.request_capacity;
        DualEraHttpEndpoint::new(
            HttpRequestHandler::with_config(self.server.http_config.handler_config.clone()),
            config,
        )
    }

    #[cfg(feature = "legacy-2024-11-05")]
    fn open_session_with_legacy_origin(
        &self,
        cx: &Cx,
        legacy_origin: &str,
    ) -> Result<ServerHttpSession, DualEraHttpEndpointError> {
        let endpoint = self.transport_endpoint(legacy_origin)?;
        self.open_session_from_transport(cx, endpoint)
    }

    #[cfg(not(feature = "legacy-2024-11-05"))]
    fn open_session_modern(&self, cx: &Cx) -> Result<ServerHttpSession, DualEraHttpEndpointError> {
        let endpoint = self.transport_endpoint()?;
        self.open_session_from_transport(cx, endpoint)
    }

    fn open_session_from_transport(
        &self,
        cx: &Cx,
        endpoint: DualEraHttpEndpoint,
    ) -> Result<ServerHttpSession, DualEraHttpEndpointError> {
        let _ = cx;
        let endpoint_session = Arc::new(Mutex::new(endpoint.open_session()?));
        #[cfg(feature = "legacy-2024-11-05")]
        let (legacy_session_id, legacy_lifecycle) = {
            let session = endpoint_session
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            (session.session_id().to_owned(), session.legacy_lifecycle())
        };
        #[cfg(feature = "legacy-2024-11-05")]
        let legacy_session =
            Session::new(self.server.info.clone(), self.server.capabilities.clone());
        #[cfg(feature = "legacy-2024-11-05")]
        let legacy_binding = runtime_legacy_binding(legacy_session.id());
        #[cfg(feature = "legacy-2024-11-05")]
        let legacy_pending_requests = Arc::new(
            PendingRequests::with_max_in_flight_for_exact_legacy(
                self.server.max_bidirectional_requests_per_connection,
            )
            .expect("ServerBuilder validates the bidirectional request limit"),
        );
        #[cfg(feature = "legacy-2024-11-05")]
        let notification_sender: NotificationSender = {
            let endpoint_session = Arc::clone(&endpoint_session);
            Arc::new(move |notification| {
                let _ = endpoint_session
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .publish_legacy_message(&JsonRpcMessage::Request(notification));
            })
        };
        #[cfg(feature = "legacy-2024-11-05")]
        let legacy_request_sender = RequestSender::new(Arc::clone(&legacy_pending_requests), {
            let endpoint_session = Arc::clone(&endpoint_session);
            Arc::new(move |message| {
                endpoint_session
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .publish_legacy_message(message)
                    .map_err(|error| error.to_string())?;
                Ok(())
            })
        });
        #[cfg(feature = "legacy-2024-11-05")]
        let legacy_runtime = LiveLegacy2024ConnectionRuntime::new(
            legacy_session.state().clone(),
            notification_sender,
            Some(legacy_request_sender),
            self.server.logging.level,
        );
        Ok(ServerHttpSession {
            server: Arc::clone(&self.server),
            endpoint_session,
            #[cfg(feature = "legacy-2024-11-05")]
            legacy_session_id,
            #[cfg(feature = "legacy-2024-11-05")]
            legacy_lifecycle,
            #[cfg(feature = "legacy-2024-11-05")]
            legacy_session,
            #[cfg(feature = "legacy-2024-11-05")]
            legacy_binding,
            #[cfg(feature = "legacy-2024-11-05")]
            legacy_adapter: None,
            #[cfg(feature = "legacy-2024-11-05")]
            legacy_active_request: Arc::new(Mutex::new(None)),
            #[cfg(feature = "legacy-2024-11-05")]
            legacy_request_cx: Arc::new(Mutex::new(cx.clone())),
            #[cfg(feature = "legacy-2024-11-05")]
            legacy_admissions: Arc::new(HttpLegacyRequestAdmissions::default()),
            #[cfg(feature = "legacy-2024-11-05")]
            legacy_auth_receipt: Arc::new(Mutex::new(None)),
            #[cfg(feature = "legacy-2024-11-05")]
            legacy_sse_open_fingerprint: None,
            #[cfg(feature = "legacy-2024-11-05")]
            legacy_pending_requests,
            #[cfg(feature = "legacy-2024-11-05")]
            legacy_runtime,
            modern_connection: Arc::new(ModernConnection::new_request_local()),
            modern_dispatches: Arc::new(Mutex::new(Vec::new())),
            selected_era: None,
            closed: false,
        })
    }

    #[cfg(feature = "legacy-2024-11-05")]
    fn open_session_for_legacy_sse(
        &self,
        cx: &Cx,
        request: &HttpRequest,
    ) -> Result<ServerHttpSession, DualEraHttpEndpointError> {
        let legacy_origin = request
            .header("host")
            .and_then(legacy_origin_from_host)
            .unwrap_or_else(|| self.legacy_origin.clone());
        self.open_session_with_legacy_origin(cx, &legacy_origin)
    }
}

/// Private proof that native ingress evaluated authentication for one exact,
/// strict-admitted modern request.  It is intentionally neither serializable
/// nor publicly constructible: only this module can carry it from admission
/// to the request context that dispatch owns.
#[derive(Clone)]
struct AuthAdmissionReceipt {
    method: String,
    request_id: Option<RequestId>,
    sanitized_params: Option<serde_json::Value>,
    fingerprint: Sha256Digest,
    authenticated: Option<AuthContext>,
}

impl AuthAdmissionReceipt {
    fn commit(
        &self,
        ctx: &McpContext,
        inbound: &InboundRequestContext,
        request: &mut JsonRpcRequest,
    ) -> Result<Sha256Digest, McpError> {
        if self.method != request.method
            || request.id != self.request_id
            || !inbound
                .auth_request(&request.method, request.params.as_ref())
                .credential_sources_are_admissible()
        {
            return Err(McpError::new(
                McpErrorCode::ResourceForbidden,
                "Authentication failed",
            ));
        }
        request.params = self.sanitized_params.clone();
        let committed = match &self.authenticated {
            Some(auth) => ctx.set_auth(auth.clone()),
            None => ctx.commit_anonymous_auth(),
        };
        if committed {
            Ok(self.fingerprint.clone())
        } else {
            Err(Server::request_context_error(ctx).unwrap_or_else(|| {
                McpError::internal_error("authentication admission was already committed")
            }))
        }
    }

    /// Commits this receipt onto an exact-2024 request context.
    ///
    /// Legacy HTTP has no [`InboundRequestContext`]; method and wire-id
    /// equality are the binding between pre-admission and dispatch.
    #[cfg(feature = "legacy-2024-11-05")]
    fn commit_legacy(
        &self,
        ctx: &McpContext,
        request: &JsonRpcRequest,
    ) -> Result<Sha256Digest, McpError> {
        if self.method != request.method || request.id != self.request_id {
            return Err(McpError::new(
                McpErrorCode::ResourceForbidden,
                "Authentication failed",
            ));
        }
        let committed = match &self.authenticated {
            Some(auth) => ctx.set_auth(auth.clone()),
            None => ctx.commit_anonymous_auth(),
        };
        if committed {
            Ok(self.fingerprint.clone())
        } else {
            Err(Server::request_context_error(ctx).unwrap_or_else(|| {
                McpError::internal_error("authentication admission was already committed")
            }))
        }
    }
}

/// Immutable, connection-owned WebSocket authentication facts.  Unlike an
/// HTTP receipt, this is never an arbitrary request receipt: the exact
/// accepted connection generation must be supplied at every frame dispatch.
#[cfg(feature = "websocket")]
struct WebSocketAuthCustody {
    connection_generation: u64,
    fingerprint: Sha256Digest,
    authenticated: Option<AuthContext>,
    rejected_inband_request_ids: Mutex<HashSet<u64>>,
}

// The WebSocket arm is an Arc handle by design; the Http receipt is the
// wide variant and both are moved once per admission.
#[allow(clippy::large_enum_variant)]
#[derive(Clone)]
enum AuthDispatchCustody {
    Http(AuthAdmissionReceipt),
    #[cfg(feature = "websocket")]
    WebSocket(Arc<WebSocketAuthCustody>),
}

impl AuthDispatchCustody {
    fn commit(
        &self,
        ctx: &McpContext,
        inbound: &InboundRequestContext,
        request: &mut JsonRpcRequest,
        // Underscore-prefixed because non-websocket builds never read it; the
        // websocket arm does, so the binding stays named for that arm.
        #[allow(clippy::used_underscore_binding)] _websocket_connection_generation: Option<u64>,
    ) -> Result<Sha256Digest, McpError> {
        match self {
            Self::Http(receipt) => receipt.commit(ctx, inbound, request),
            #[cfg(feature = "websocket")]
            Self::WebSocket(custody) => {
                if _websocket_connection_generation != Some(custody.connection_generation)
                    || custody
                        .rejected_inband_request_ids
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .remove(&request_id_to_u64(request.id.as_ref()))
                    || !inbound
                        .auth_request(&request.method, request.params.as_ref())
                        .credential_sources_are_admissible()
                {
                    return Err(McpError::new(
                        McpErrorCode::ResourceForbidden,
                        "Authentication failed",
                    ));
                }
                // Frame decode/admission has just produced this request;
                // strip before traffic rendering, middleware, logs, or router.
                auth::strip_recognized_access_credentials(&mut request.params);
                let committed = match &custody.authenticated {
                    Some(auth) => ctx.set_auth(auth.clone()),
                    None => ctx.commit_anonymous_auth(),
                };
                if committed {
                    Ok(custody.fingerprint)
                } else {
                    Err(Server::request_context_error(ctx).unwrap_or_else(|| {
                        McpError::internal_error("authentication admission was already committed")
                    }))
                }
            }
        }
    }

    #[cfg(feature = "legacy-2024-11-05")]
    fn commit_legacy_connection(&self, ctx: &McpContext) -> Result<Sha256Digest, McpError> {
        let (authenticated, fingerprint) = match self {
            Self::Http(receipt) => (receipt.authenticated.clone(), receipt.fingerprint.clone()),
            #[cfg(feature = "websocket")]
            Self::WebSocket(custody) => {
                (custody.authenticated.clone(), custody.fingerprint.clone())
            }
        };
        let committed = match authenticated {
            Some(auth) => ctx.set_auth(auth),
            None => ctx.commit_anonymous_auth(),
        };
        if committed {
            Ok(fingerprint)
        } else {
            Err(Server::request_context_error(ctx).unwrap_or_else(|| {
                McpError::internal_error("authentication admission was already committed")
            }))
        }
    }

    #[cfg(feature = "legacy-2024-11-05")]
    fn connection_fingerprint(&self) -> Sha256Digest {
        match self {
            Self::Http(receipt) => receipt.fingerprint.clone(),
            #[cfg(feature = "websocket")]
            Self::WebSocket(custody) => custody.fingerprint.clone(),
        }
    }
}

#[cfg(feature = "websocket")]
fn sanitize_websocket_decoded_request(
    custody: &WebSocketAuthCustody,
    request: &mut JsonRpcRequest,
) {
    let original = request.params.clone();
    auth::strip_recognized_access_credentials(&mut request.params);
    if request.params != original {
        custody
            .rejected_inband_request_ids
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .insert(request_id_to_u64(request.id.as_ref()));
    }
}

impl ServerHttpSession {
    /// Returns the exact opaque session value required by the legacy POST URI.
    #[must_use]
    #[cfg(feature = "legacy-2024-11-05")]
    pub fn legacy_session_id(&self) -> &str {
        &self.legacy_session_id
    }

    /// Routes and dispatches one modern or exact-2024 HTTP request on the caller's `Cx`.
    ///
    /// The caller drives this future on its runtime. This entry does not
    /// construct or re-enter a runtime, so request-owned children can progress
    /// while the handler awaits them.
    pub async fn handle_async(
        &mut self,
        cx: &Cx,
        request: HttpRequest,
    ) -> Result<ServerHttpEndpointResponse, ServerHttpEndpointError> {
        self.handle_with_modern_request_cancellation_async(cx, request, None, false, None)
            .await
            .map_err(ServerHttpEndpointError::from_internal)
    }

    #[cfg(feature = "legacy-2024-11-05")]
    async fn handle_preclassified_unmatched_legacy_response(
        &mut self,
        cx: &Cx,
        request: HttpRequest,
        _verified: IngressVerifiedLegacyResponse,
    ) -> Result<ServerHttpEndpointResponse, ServerHttpEndpointError> {
        self.handle_with_modern_request_cancellation_async(cx, request, None, true, None)
            .await
            .map_err(ServerHttpEndpointError::from_internal)
    }

    async fn handle_with_modern_request_cancellation_async(
        &mut self,
        cx: &Cx,
        request: HttpRequest,
        modern_request_cancellation: Option<McpRequestCancellation>,
        legacy_response_preclassified_unmatched: bool,
        legacy_auth_receipt: Option<AuthAdmissionReceipt>,
    ) -> Result<ServerHttpEndpointResponse, DualEraHttpEndpointError> {
        let transport_authorization = match transport_authorization_from_http_request(&request) {
            Ok(authorization) => authorization,
            Err(response) => return Ok(ServerHttpEndpointResponse::Immediate(response)),
        };
        self.handle_with_modern_request_cancellation_and_transport_authorization_async(
            cx,
            request,
            transport_authorization,
            modern_request_cancellation,
            legacy_response_preclassified_unmatched,
            legacy_auth_receipt,
        )
        .await
    }

    #[cfg_attr(
        not(feature = "legacy-2024-11-05"),
        allow(clippy::unused_async, clippy::unused_async_trait_impl)
    )]
    async fn handle_with_modern_request_cancellation_and_transport_authorization_async(
        &mut self,
        cx: &Cx,
        request: HttpRequest,
        transport_authorization: TransportAuthorization,
        modern_request_cancellation: Option<McpRequestCancellation>,
        legacy_response_preclassified_unmatched: bool,
        legacy_auth_receipt: Option<AuthAdmissionReceipt>,
    ) -> Result<ServerHttpEndpointResponse, DualEraHttpEndpointError> {
        #[cfg(not(feature = "legacy-2024-11-05"))]
        let _ = (legacy_response_preclassified_unmatched, legacy_auth_receipt);
        self.reap_modern_dispatches();
        let mut request = request;
        if request.path == self.server.http_config.health_path && request.method == HttpMethod::Get
        {
            return Ok(ServerHttpEndpointResponse::Immediate(
                HttpResponse::ok().with_json(&serde_json::json!({"status": "ok"})),
            ));
        }

        // DNS-rebinding protection for every MCP route, modern and exact-2024
        // alike: a present `Origin` must be loopback or explicitly allowed,
        // otherwise HTTP 403 before any parsing, authentication, or dispatch.
        if let Some(origin) = request.header("origin")
            && !self.server.http_config.handler_config.admits_origin(origin)
        {
            return Ok(ServerHttpEndpointResponse::Immediate(HttpResponse::new(
                HttpStatus::FORBIDDEN,
            )));
        }

        let is_modern = request.method == HttpMethod::Post
            && request.path == self.server.http_config.handler_config.base_path;
        let mut raw_params = None;
        let mut http_parameter_headers = None;
        let mut auth_receipt = None;
        #[cfg(feature = "legacy-2024-11-05")]
        let is_legacy = (request.method == HttpMethod::Get
            && request.path == self.server.http_config.legacy_sse_path)
            || (request.method == HttpMethod::Post
                && request.path == self.server.http_config.legacy_message_path);
        #[cfg(not(feature = "legacy-2024-11-05"))]
        if matches!(self.server.protocol_policy, ProtocolPolicy::LegacyOnly) {
            return Ok(ServerHttpEndpointResponse::Immediate(HttpResponse::new(
                HttpStatus::BAD_REQUEST,
            )));
        }
        #[cfg(feature = "legacy-2024-11-05")]
        if (is_modern && matches!(self.server.protocol_policy, ProtocolPolicy::LegacyOnly))
            || (is_legacy && matches!(self.server.protocol_policy, ProtocolPolicy::ModernOnly))
        {
            return Ok(ServerHttpEndpointResponse::Immediate(HttpResponse::new(
                HttpStatus::BAD_REQUEST,
            )));
        }
        #[cfg(feature = "legacy-2024-11-05")]
        let legacy_post_admission = if request.method == HttpMethod::Post
            && request.path == self.server.http_config.legacy_message_path
        {
            match admit_legacy_2024_http_post(
                &request,
                &self.server.http_config.legacy_message_path,
                self.legacy_session_id(),
                self.server.http_config.handler_config.max_body_size,
            ) {
                Ok(admitted) => Some(admitted),
                Err(response) => {
                    return Ok(ServerHttpEndpointResponse::Immediate(response));
                }
            }
        } else {
            None
        };
        if is_modern {
            if request.header("mcp-session-id").is_some() {
                return Ok(ServerHttpEndpointResponse::Immediate(
                    HttpResponse::bad_request(),
                ));
            }
            let (prepared_request, admitted_request, admitted_raw_params) =
                match self.prepare_modern_http_request(request) {
                    Ok(prepared) => prepared,
                    Err(response) => return Ok(ServerHttpEndpointResponse::Immediate(response)),
                };
            request = prepared_request;
            raw_params = admitted_raw_params;
            http_parameter_headers = Some(http_admission::http_parameter_headers(&request.headers));
            auth_receipt = match self.preauthenticate_modern_http_request(
                cx,
                &admitted_request,
                &transport_authorization,
            ) {
                Ok(receipt) => Some(AuthDispatchCustody::Http(receipt)),
                Err(response) => return Ok(ServerHttpEndpointResponse::Immediate(response)),
            };
        }
        #[cfg(feature = "legacy-2024-11-05")]
        let ingress_verified_legacy_response = legacy_response_preclassified_unmatched
            && matches!(
                legacy_post_admission,
                Some(Legacy2024HttpPostEnvelope::Response(_))
            );
        #[cfg(feature = "legacy-2024-11-05")]
        if is_legacy && !ingress_verified_legacy_response {
            let admitted_request = match &legacy_post_admission {
                Some(Legacy2024HttpPostEnvelope::ClientMessage(request)) => Some(request),
                _ => None,
            };
            let receipt = match legacy_auth_receipt {
                Some(receipt) => {
                    // Recheck the exact admitted payload after waiting for
                    // exclusive session ownership. A receipt never authorizes
                    // a different method, request, or notification.
                    if !admitted_request.is_some_and(|request| {
                        receipt.method == request.method
                            && receipt.request_id == request.id
                            && receipt.sanitized_params == request.params
                    }) {
                        return Ok(ServerHttpEndpointResponse::Immediate(
                            native_http_authentication_rejection(),
                        ));
                    }
                    receipt
                }
                None => match self.preauthenticate_legacy_http_request(
                    cx,
                    admitted_request,
                    &transport_authorization,
                ) {
                    Ok(receipt) => receipt,
                    Err(response) => return Ok(ServerHttpEndpointResponse::Immediate(response)),
                },
            };
            if matches!(
                legacy_post_admission,
                Some(Legacy2024HttpPostEnvelope::Response(_))
            ) && !self
                .legacy_session
                .principal_binding()
                .verify_existing(receipt.fingerprint.clone())
            {
                return Ok(ServerHttpEndpointResponse::Immediate(
                    native_http_authentication_rejection(),
                ));
            }
            // GET `/sse` has no JSON-RPC body, so the receipt cannot be
            // committed onto a later POST. Retain the opener fingerprint so
            // `install_legacy_generation` can bind the session owner. POST
            // `/messages` (including reverse responses) must not overwrite
            // or claim that opener identity.
            if request.method == HttpMethod::Get
                && request.path == self.server.http_config.legacy_sse_path
            {
                self.legacy_sse_open_fingerprint = Some(receipt.fingerprint.clone());
            }
            let mut stored = self
                .legacy_auth_receipt
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            *stored = admitted_request.is_some().then_some(receipt);
        }
        #[cfg(feature = "legacy-2024-11-05")]
        let request_era = if is_modern {
            Some(ProtocolEra::Modern2026)
        } else if is_legacy {
            Some(ProtocolEra::Legacy2024)
        } else {
            None
        };
        #[cfg(not(feature = "legacy-2024-11-05"))]
        let request_era = is_modern.then_some(ProtocolEra::Modern2026);
        if request_era.is_some_and(|era| self.selected_era.is_some_and(|selected| selected != era))
        {
            // Reject before modern admission or legacy adapter dispatch: a
            // retained public session is one era's mutable namespace, never
            // a bridge between exact-2024 and final HTTP state.
            return Ok(ServerHttpEndpointResponse::Immediate(
                HttpResponse::bad_request(),
            ));
        }
        // The first admitted HTTP era irrevocably owns this public session.
        // Modern requests retain the existing recognition-time pin; exact
        // legacy POSTs pin only after strict admission, and legacy GET pins
        // only after it successfully creates the response body below.
        #[cfg(feature = "legacy-2024-11-05")]
        let defer_legacy_era_selection = matches!(request_era, Some(ProtocolEra::Legacy2024));
        #[cfg(not(feature = "legacy-2024-11-05"))]
        let defer_legacy_era_selection = false;
        if let Some(era) = request_era.filter(|_| !defer_legacy_era_selection) {
            self.selected_era.get_or_insert(era);
        }
        #[cfg(feature = "legacy-2024-11-05")]
        if let Some(Legacy2024HttpPostEnvelope::Response(response)) = legacy_post_admission {
            let lifecycle = self.legacy_lifecycle.clone();
            let result = lifecycle
                .commit_if_live(|| {
                    self.selected_era.get_or_insert(ProtocolEra::Legacy2024);
                    if legacy_response_preclassified_unmatched {
                        self.handle_unmatched_legacy_reverse_response(response)
                    } else {
                        self.handle_legacy_reverse_response(response)
                    }
                })
                .unwrap_or_else(|| {
                    ServerHttpEndpointResponse::Immediate(HttpResponse::new(
                        HttpStatus::SERVICE_UNAVAILABLE,
                    ))
                });
            return Ok(result);
        }
        let endpoint_response = self
            .endpoint_session
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .handle(cx, request)?;
        #[cfg(feature = "legacy-2024-11-05")]
        if defer_legacy_era_selection
            && (matches!(
                &endpoint_response,
                DualEraHttpEndpointResponse::LegacySse(_)
            ) || matches!(
                &endpoint_response,
                DualEraHttpEndpointResponse::Immediate(response)
                    if response.status == HttpStatus::ACCEPTED
            ))
        {
            self.selected_era.get_or_insert(ProtocolEra::Legacy2024);
        }
        if is_modern {
            return self
                .handle_modern(
                    cx,
                    endpoint_response,
                    transport_authorization,
                    raw_params,
                    http_parameter_headers,
                    auth_receipt,
                    modern_request_cancellation,
                )
                .await;
        }
        #[cfg(feature = "legacy-2024-11-05")]
        return self.handle_legacy(cx, endpoint_response).await;
        #[cfg(not(feature = "legacy-2024-11-05"))]
        {
            let _ = endpoint_response;
            Ok(ServerHttpEndpointResponse::Immediate(HttpResponse::new(
                HttpStatus::NOT_FOUND,
            )))
        }
    }

    fn prepare_modern_http_request(
        &self,
        mut request: HttpRequest,
    ) -> Result<(HttpRequest, JsonRpcRequest, Option<Arc<str>>), HttpResponse> {
        if rejects_final_client_notification_http_ingress(
            &request.body,
            self.server.http_config.handler_config.max_body_size,
        ) {
            return Err(HttpResponse::bad_request());
        }
        let admitted = self.admit_modern_http_request(&request)?;
        let raw_params = admitted.raw_params().map(Arc::<str>::from);
        if admit_final_client_notification_ingress(admitted.request()).is_err() {
            return Err(HttpResponse::bad_request());
        }
        if let Some(response) = self
            .server
            .preflight_modern_http_required_capability(admitted.request())
        {
            return Err(HttpResponse::new(HttpStatus::BAD_REQUEST).with_json(&response));
        }
        let request_requires_sse = admitted.request().method == SUBSCRIPTIONS_LISTEN
            || self
                .server
                .modern_request_requires_owned_sse(admitted.request());
        let request_accepts_sse = http_request_accepts_sse(&request);

        // The strict admission authority has chosen the request-local
        // representation. Preserve that decision when the transport admits
        // the already-validated request a second time.
        request.headers.insert(
            "accept".to_owned(),
            match admitted.representation() {
                ResponseRepresentation::Json => "application/json",
                ResponseRepresentation::RequestScopedSse => "text/event-stream",
            }
            .to_owned(),
        );
        if !request_requires_sse {
            return Ok((request, admitted.request().clone(), raw_params));
        }
        if !request_accepts_sse {
            return Err(HttpResponse::new(HttpStatus::NOT_ACCEPTABLE));
        }
        // The transport defaults a dual-acceptable request to JSON.
        // Request-scoped final notifications instead require the
        // connection-owned SSE sender, so select that accepted form before
        // the request enters the transport ingress queue.
        request
            .headers
            .insert("accept".to_owned(), "text/event-stream".to_owned());
        Ok((request, admitted.request().clone(), raw_params))
    }

    /// Authenticates a strict modern HTTP request before it can pin a public
    /// session era, allocate an SSE body, or enter dispatch.  The returned
    /// receipt carries the sole successful provider evaluation into the fresh
    /// request context that dispatch owns; failed admission has no session,
    /// handler, middleware, or log side effects.
    fn preauthenticate_modern_http_request(
        &self,
        cx: &Cx,
        request: &JsonRpcRequest,
        transport_authorization: &TransportAuthorization,
    ) -> Result<AuthAdmissionReceipt, HttpResponse> {
        self.server
            .preauthenticate_http_request(cx, request, transport_authorization)
    }

    /// Authenticates an exact-2024 HTTP GET `/sse` or POST `/messages`
    /// request before the session era can pin or dispatch can run. GET uses a
    /// synthetic request identity because the SSE open has no JSON-RPC body.
    #[cfg(feature = "legacy-2024-11-05")]
    fn preauthenticate_legacy_http_request(
        &self,
        cx: &Cx,
        request: Option<&JsonRpcRequest>,
        transport_authorization: &TransportAuthorization,
    ) -> Result<AuthAdmissionReceipt, HttpResponse> {
        let synthetic = request
            .is_none()
            .then(|| JsonRpcRequest::new("legacy/sse", None, RequestId::Number(0)));
        let admitted = request
            .or(synthetic.as_ref())
            .expect("synthetic fills GET /sse");
        self.preauthenticate_modern_http_request(cx, admitted, transport_authorization)
    }

    fn admit_modern_http_request(
        &self,
        request: &HttpRequest,
    ) -> Result<AdmittedModernPost, HttpResponse> {
        let headers = request
            .headers
            .iter()
            .map(|(name, value)| (name.clone(), value.clone()))
            .collect::<Vec<_>>();

        admit_modern_http_post(
            &self.server.http_config.handler_config,
            request.method.as_str(),
            &request.path,
            &headers,
            &request.body,
        )
    }

    /// Installs every exact-2024 server-issued capability for one live SSE
    /// body generation. Reconnect must replace, rather than revive, these
    /// objects: retained providers and request senders otherwise close over
    /// the mutable transport session and could publish into the fresh body.
    #[cfg(feature = "legacy-2024-11-05")]
    fn install_legacy_generation(&mut self, cx: &Cx) {
        self.legacy_admissions.cancel_all();
        self.legacy_pending_requests.cancel_all();
        *self
            .legacy_auth_receipt
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = None;
        if let Some(active_request) = take_live_legacy_active_request(&self.legacy_active_request) {
            active_request.cancellation.cancel();
        }
        if let Some(adapter) = self.legacy_adapter.as_mut() {
            let _ = adapter.close(self.legacy_binding);
        }
        self.legacy_adapter = None;

        self.legacy_session =
            Session::new(self.server.info.clone(), self.server.capabilities.clone());
        self.legacy_binding = runtime_legacy_binding(self.legacy_session.id());
        self.legacy_active_request = Arc::new(Mutex::new(None));
        self.legacy_request_cx = Arc::new(Mutex::new(cx.clone()));
        self.legacy_admissions = Arc::new(HttpLegacyRequestAdmissions::default());

        let pending_requests = Arc::new(
            PendingRequests::with_max_in_flight_for_exact_legacy(
                self.server.max_bidirectional_requests_per_connection,
            )
            .expect("ServerBuilder validates the bidirectional request limit"),
        );
        let lifecycle = self.legacy_lifecycle.clone();
        let notification_sender: NotificationSender = {
            let endpoint_session = Arc::clone(&self.endpoint_session);
            let lifecycle = lifecycle.clone();
            Arc::new(move |notification| {
                let _ = lifecycle.commit_if_live(|| {
                    endpoint_session
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .publish_legacy_message_committed(&JsonRpcMessage::Request(notification))
                });
            })
        };
        let request_sender = RequestSender::new(Arc::clone(&pending_requests), {
            let endpoint_session = Arc::clone(&self.endpoint_session);
            Arc::new(move |message| {
                lifecycle
                    .commit_if_live(|| {
                        endpoint_session
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner)
                            .publish_legacy_message_committed(message)
                    })
                    .ok_or_else(|| "Legacy SSE generation is closed".to_owned())?
                    .map_err(|error| error.to_string())
            })
        });
        self.legacy_pending_requests = pending_requests;
        self.legacy_runtime = LiveLegacy2024ConnectionRuntime::new(
            self.legacy_session.state().clone(),
            notification_sender,
            Some(request_sender),
            self.server.logging.level,
        );
    }

    /// Returns a transport-backed roots provider after exact-2024 roots
    /// capability negotiation has completed for this HTTP connection.
    #[must_use]
    #[cfg(feature = "legacy-2024-11-05")]
    pub fn legacy_roots_provider(&self) -> Option<TransportRootsProvider> {
        if !self.legacy_adapter.as_ref().is_some_and(|adapter| {
            let snapshot = adapter.snapshot();
            snapshot.operating_transition_count == 1 && snapshot.close_release_count == 0
        }) {
            return None;
        }
        self.legacy_runtime
            .supports_roots
            .load(Ordering::Acquire)
            .then(|| self.legacy_runtime.request_sender.clone())
            .flatten()
            .map(|sender| {
                TransportRootsProvider::new(
                    McpContext::new(
                        self.legacy_request_cx
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner)
                            .clone(),
                        0,
                    ),
                    sender,
                )
            })
    }

    /// Delivers an exact `notifications/resources/updated` message to this
    /// live legacy HTTP connection when it subscribed to `uri`.
    ///
    /// Returns `false` without emitting a message when the connection has not
    /// subscribed to the URI, has not completed legacy initialization, or its
    /// SSE stream is not live.
    #[cfg(feature = "legacy-2024-11-05")]
    pub fn notify_legacy_resource_updated(&mut self, uri: &str) -> bool {
        let Some(adapter) = self.legacy_adapter.as_mut() else {
            return false;
        };
        if adapter
            .snapshot()
            .subscriptions
            .binary_search_by(|item| item.as_str().cmp(uri))
            .is_err()
        {
            return false;
        }
        let Ok(Legacy2024Outbound::ReverseNotification(notification)) = adapter.make_notification(
            self.legacy_binding,
            "notifications/resources/updated",
            Some(serde_json::json!({ "uri": uri })),
        ) else {
            return false;
        };
        let Ok(notification) = serde_json::from_value::<JsonRpcRequest>(notification) else {
            return false;
        };
        self.endpoint_session
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .publish_legacy_message(&JsonRpcMessage::Request(notification))
            .is_ok()
    }

    #[cfg(feature = "legacy-2024-11-05")]
    fn handle_legacy_reverse_response(
        &mut self,
        response: JsonRpcResponse,
    ) -> ServerHttpEndpointResponse {
        let disposition = self
            .legacy_pending_requests
            .route_response_with_disposition(&response);
        if matches!(
            disposition,
            bidirectional::PendingResponseDisposition::Delivered
                | bidirectional::PendingResponseDisposition::RetiredGeneric
        ) {
            return ServerHttpEndpointResponse::Immediate(HttpResponse::new(HttpStatus::ACCEPTED));
        }

        self.handle_unmatched_legacy_reverse_response(response)
    }

    #[cfg(feature = "legacy-2024-11-05")]
    fn handle_unmatched_legacy_reverse_response(
        &mut self,
        response: JsonRpcResponse,
    ) -> ServerHttpEndpointResponse {
        let accepted_by_adapter = self.legacy_adapter.as_mut().is_some_and(|adapter| {
            legacy_adapter_accept_response(adapter, self.legacy_binding, &response)
        });
        if !accepted_by_adapter {
            return ServerHttpEndpointResponse::Immediate(HttpResponse::bad_request());
        }
        if let Some(adapter) = self.legacy_adapter.as_ref() {
            sync_live_legacy_runtime_from_adapter(&self.legacy_runtime, adapter);
            self.legacy_session
                .restore_log_level(self.legacy_runtime.log_level());
        }
        ServerHttpEndpointResponse::Immediate(HttpResponse::new(HttpStatus::ACCEPTED))
    }

    async fn handle_modern(
        &mut self,
        cx: &Cx,
        endpoint_response: DualEraHttpEndpointResponse,
        transport_authorization: TransportAuthorization,
        raw_params: Option<Arc<str>>,
        http_parameter_headers: Option<Arc<[(String, String)]>>,
        auth_receipt: Option<AuthDispatchCustody>,
        modern_request_cancellation: Option<McpRequestCancellation>,
    ) -> Result<ServerHttpEndpointResponse, DualEraHttpEndpointError> {
        let request = self
            .endpoint_session
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .recv_modern_request(cx)?;

        // Final Streamable HTTP cancellation is response-body closure. A
        // separate notifications/cancelled POST has no request-body authority
        // and is rejected instead of being correlated by JSON-RPC ID.
        if request.method == "notifications/cancelled" {
            return Ok(ServerHttpEndpointResponse::Immediate(
                HttpResponse::bad_request(),
            ));
        }

        if request.method == SUBSCRIPTIONS_LISTEN {
            let DualEraHttpEndpointResponse::ModernSse(sse) = endpoint_response else {
                return Ok(ServerHttpEndpointResponse::Immediate(
                    HttpResponse::bad_request(),
                ));
            };
            let sender = sse.sender();
            let request_cancellation = sender.request_cancellation();
            let owner_generation = next_modern_http_stream_generation();
            let terminal_delivery = Arc::new(FinalSubscriptionTerminalDelivery::default());
            let inbound = InboundRequestContext::with_modern_connection_and_transport_authorization(
                cx.clone(),
                request_id_to_u64(request.id.as_ref()),
                InboundRequestTransport::Http,
                &self.modern_connection,
                transport_authorization,
            );
            let dispatch = spawn_modern_sse_dispatch(
                cx,
                Arc::clone(&self.server),
                owner_generation,
                inbound,
                request,
                raw_params,
                auth_receipt,
                sender,
                Arc::clone(&terminal_delivery),
                None,
            )?;
            self.modern_dispatches
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(OwnedModernHttpDispatch {
                    owner_generation,
                    request_cancellation: request_cancellation.clone(),
                    task: dispatch,
                });
            return Ok(ServerHttpEndpointResponse::ModernSse(
                ServerHttpSseResponse::new(sse, request_cancellation, terminal_delivery),
            ));
        }

        let inbound = InboundRequestContext::with_modern_connection_and_transport_authorization(
            cx.clone(),
            request_id_to_u64(request.id.as_ref()),
            InboundRequestTransport::Http,
            &self.modern_connection,
            transport_authorization,
        );
        let inbound = match http_parameter_headers {
            Some(headers) => inbound.with_http_parameter_headers(headers),
            None => inbound,
        };

        match endpoint_response {
            DualEraHttpEndpointResponse::ModernJson(pending) => {
                if self.server.modern_request_requires_owned_sse(&request) {
                    return Ok(ServerHttpEndpointResponse::Immediate(HttpResponse::new(
                        HttpStatus::NOT_ACCEPTABLE,
                    )));
                }
                // JSON selects the response representation, not a synchronous
                // handler contract. Use the same owned dispatcher as SSE so
                // async extensions (including proxy Tasks controls) can yield
                // on the caller's runtime and core handlers own their region.
                let response = Arc::clone(&self.server)
                    .dispatch_with_protocol_policy_owned(
                        self.server.protocol_policy,
                        &inbound,
                        request,
                        raw_params,
                        auth_receipt,
                        None,
                        None,
                        modern_request_cancellation.unwrap_or_default(),
                        None,
                        Arc::new(|_| {}),
                    )
                    .await;
                if let Some(response) = response {
                    if let Some(rejection) = canonical_http_error_status_response(&response) {
                        return Ok(ServerHttpEndpointResponse::Immediate(rejection));
                    }
                    self.endpoint_session
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .send_modern_json_response(cx, response)?;
                    let response = pending
                        .try_response()?
                        .expect("a committed modern JSON response must be retrievable");
                    Ok(ServerHttpEndpointResponse::Immediate(response))
                } else {
                    Ok(ServerHttpEndpointResponse::Immediate(HttpResponse::new(
                        HttpStatus::ACCEPTED,
                    )))
                }
            }
            DualEraHttpEndpointResponse::ModernSse(sse) => {
                let request_cancellation = sse.sender().request_cancellation();
                let transport_cancellation = sse.cancellation();
                // Progress finalization and the terminal response share this
                // request-owned serializer. It keeps a transient transport
                // commit gate collision from being mistaken for peer closure
                // or allowing the response to overtake the coalesced update.
                let terminal_commit = Arc::new(Mutex::new(()));
                // A notification callback has no result channel into router
                // dispatch. Retain its commit failure explicitly so an
                // exhausted `WouldBlock` cannot be mistaken for a harmless
                // dropped progress/log frame and followed by a terminal
                // response.
                let notification_commit_failed = Arc::new(AtomicBool::new(false));
                let terminal_delivery = Arc::new(FinalSubscriptionTerminalDelivery::default());
                // The final outcome is the sole authority for the terminal
                // HTTP status. Retain request-scoped progress and log frames
                // until that outcome is known, so any canonical -32021 from
                // middleware, a tool, or another final gate becomes a 400
                // without committing an SSE event first.
                let deferred_notifications = Arc::new(Mutex::new(Vec::new()));
                let committed_notification_sender: NotificationSender = {
                    let endpoint_session = Arc::clone(&self.endpoint_session);
                    let notification_cx = cx.clone();
                    let transport_cancellation = transport_cancellation.clone();
                    let request_cancellation = request_cancellation.clone();
                    let terminal_commit = Arc::clone(&terminal_commit);
                    let notification_commit_failed = Arc::clone(&notification_commit_failed);
                    let terminal_delivery = Arc::clone(&terminal_delivery);
                    Arc::new(move |notification| {
                        if notification_commit_failed.load(Ordering::Acquire) {
                            return;
                        }
                        let _terminal_commit = terminal_commit
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner);
                        let sent = retry_http_sse_commit(
                            &notification_cx,
                            &request_cancellation,
                            || {
                                #[cfg(test)]
                                if take_forced_http_sse_would_block_commit() {
                                    return Err(DualEraHttpEndpointError::Transport(
                                        TransportError::Io(std::io::Error::new(
                                            std::io::ErrorKind::WouldBlock,
                                            "forced final HTTP commit contention",
                                        )),
                                    ));
                                }
                                endpoint_session
                                    .lock()
                                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                                    .send_modern_sse_notification(
                                        &notification_cx,
                                        &transport_cancellation,
                                        notification.clone(),
                                    )
                            },
                            retryable_http_sse_endpoint_error,
                        );
                        if sent.is_err() {
                            notification_commit_failed.store(true, Ordering::Release);
                            terminal_delivery.mark_failed();
                            request_cancellation.cancel();
                        }
                    })
                };
                let notification_sender: NotificationSender = {
                    let deferred_notifications = Arc::clone(&deferred_notifications);
                    Arc::new(move |notification| {
                        deferred_notifications
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner)
                            .push(notification);
                    })
                };
                let response = Arc::clone(&self.server)
                    .dispatch_with_protocol_policy_owned(
                        self.server.protocol_policy,
                        &inbound,
                        request,
                        None,
                        auth_receipt,
                        None,
                        None,
                        request_cancellation.clone(),
                        None,
                        notification_sender,
                    )
                    .await;
                if let Some(rejection) = response
                    .as_ref()
                    .and_then(canonical_http_error_status_response)
                {
                    return Ok(ServerHttpEndpointResponse::Immediate(rejection));
                }
                let deferred_notifications = std::mem::take(
                    &mut *deferred_notifications
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner),
                );
                for notification in deferred_notifications {
                    committed_notification_sender(notification);
                }
                if notification_commit_failed.load(Ordering::Acquire) {
                    terminal_delivery.mark_failed();
                    return Err(DualEraHttpEndpointError::Transport(TransportError::Io(
                        std::io::Error::other(
                            "modern HTTP progress or log commit failed before terminal response",
                        ),
                    )));
                }
                if let Some(response) = response {
                    let _terminal_commit = terminal_commit
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    retry_http_sse_commit(
                        cx,
                        &request_cancellation,
                        || {
                            self.endpoint_session
                                .lock()
                                .unwrap_or_else(std::sync::PoisonError::into_inner)
                                .send_modern_sse_response(
                                    cx,
                                    &transport_cancellation,
                                    response.clone(),
                                )
                        },
                        retryable_http_sse_endpoint_error,
                    )?;
                }
                Ok(ServerHttpEndpointResponse::ModernSse(
                    ServerHttpSseResponse::new(sse, request_cancellation, terminal_delivery),
                ))
            }
            DualEraHttpEndpointResponse::Immediate(response) => {
                debug_assert!(request.id.is_none());
                Ok(ServerHttpEndpointResponse::Immediate(response))
            }
            #[cfg(feature = "legacy-2024-11-05")]
            DualEraHttpEndpointResponse::LegacySse(_) => {
                unreachable!("the modern route cannot create a legacy SSE response")
            }
        }
    }

    /// Admits a modern SSE body without synchronously dispatching its request.
    ///
    /// The socket writer owns this body and its request-owned dispatch child.
    /// Long-lived subscriptions can stream after pre-admission, while ordinary
    /// request-scoped SSE defers its wire representation until the final
    /// outcome has elected it.
    ///
    /// `modern_request_cancellation` is the connection-owned cancellation
    /// domain for a request whose representation is elected as JSON here. That
    /// dispatch completes inline, before any SSE response owner exists, so the
    /// caller must observe its peer while awaiting this method (#76).
    async fn begin_modern_sse(
        &mut self,
        cx: &Cx,
        request: HttpRequest,
        transport_authorization: TransportAuthorization,
        modern_request_cancellation: Option<McpRequestCancellation>,
    ) -> Result<
        Result<
            (
                JsonRpcRequest,
                DualEraHttpSseResponse,
                Option<Arc<str>>,
                AuthDispatchCustody,
            ),
            // Boxed so this Result stays small (bd-cmvwm): the response enum
            // is hundreds of bytes and only the refusal path pays the box.
            Box<ServerHttpEndpointResponse>,
        >,
        DualEraHttpEndpointError,
    > {
        if matches!(self.server.protocol_policy, ProtocolPolicy::LegacyOnly) {
            return Ok(Err(Box::new(ServerHttpEndpointResponse::Immediate(
                HttpResponse::new(HttpStatus::BAD_REQUEST),
            ))));
        }
        let (request, admitted_request, raw_params) =
            match self.prepare_modern_http_request(request) {
                Ok(request) => request,
                Err(response) => {
                    return Ok(Err(Box::new(ServerHttpEndpointResponse::Immediate(
                        response,
                    ))));
                }
            };
        let auth_receipt = match self.preauthenticate_modern_http_request(
            cx,
            &admitted_request,
            &transport_authorization,
        ) {
            Ok(receipt) => AuthDispatchCustody::Http(receipt),
            Err(response) => {
                return Ok(Err(Box::new(ServerHttpEndpointResponse::Immediate(
                    response,
                ))));
            }
        };
        let http_parameter_headers = http_admission::http_parameter_headers(&request.headers);
        let endpoint_response = match self
            .endpoint_session
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .handle(cx, request)
        {
            Ok(endpoint_response) => endpoint_response,
            // The transport refuses to construct an SSE body for a frame
            // whose shape cannot own one (an id-less notification, or a
            // request that already selected a JSON response) before the
            // endpoint's own rejection arm can run; peers get the same
            // graceful 400 the non-streaming arm produces.
            Err(DualEraHttpEndpointError::Transport(TransportError::Io(error)))
                if error.kind() == std::io::ErrorKind::InvalidInput =>
            {
                return Ok(Err(Box::new(ServerHttpEndpointResponse::Immediate(
                    HttpResponse::bad_request(),
                ))));
            }
            Err(error) => return Err(error),
        };
        let DualEraHttpEndpointResponse::ModernSse(sse) = endpoint_response else {
            return self
                .handle_modern(
                    cx,
                    endpoint_response,
                    transport_authorization,
                    raw_params,
                    Some(http_parameter_headers),
                    Some(auth_receipt),
                    modern_request_cancellation,
                )
                .await
                .map(|response| Err(Box::new(response)));
        };
        let request = self
            .endpoint_session
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .recv_modern_request(cx)?;
        if request.method == "notifications/cancelled" {
            return Ok(Err(Box::new(ServerHttpEndpointResponse::Immediate(
                HttpResponse::bad_request(),
            ))));
        }
        Ok(Ok((request, sse, raw_params, auth_receipt)))
    }

    #[cfg(feature = "legacy-2024-11-05")]
    async fn handle_legacy(
        &mut self,
        cx: &Cx,
        endpoint_response: DualEraHttpEndpointResponse,
    ) -> Result<ServerHttpEndpointResponse, DualEraHttpEndpointError> {
        let response = match endpoint_response {
            DualEraHttpEndpointResponse::LegacySse(sse) => {
                let (session_id, lifecycle) = {
                    let endpoint = self
                        .endpoint_session
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    (
                        endpoint.session_id().to_owned(),
                        endpoint.legacy_lifecycle(),
                    )
                };
                self.legacy_session_id = session_id;
                self.legacy_lifecycle = lifecycle;
                self.install_legacy_generation(cx);
                if let Some(fingerprint) = self.legacy_sse_open_fingerprint.take()
                    && !self
                        .legacy_session
                        .principal_binding()
                        .bind_or_verify(fingerprint)
                {
                    return Ok(ServerHttpEndpointResponse::Immediate(HttpResponse::new(
                        HttpStatus::UNAUTHORIZED,
                    )));
                }
                return Ok(ServerHttpEndpointResponse::LegacySse(sse));
            }
            DualEraHttpEndpointResponse::Immediate(response) => response,
            DualEraHttpEndpointResponse::ModernJson(_)
            | DualEraHttpEndpointResponse::ModernSse(_) => {
                unreachable!("the legacy route cannot create a modern response")
            }
        };

        let Some(request) = self
            .endpoint_session
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .take_legacy_request()
        else {
            return Ok(ServerHttpEndpointResponse::Immediate(response));
        };

        *self
            .legacy_request_cx
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = cx.clone();
        let adapter = match self.legacy_adapter.as_mut() {
            Some(adapter) => adapter,
            None => {
                let adapter = self
                    .server
                    .install_legacy_2024_adapter(
                        self.legacy_binding,
                        HttpLegacy2024RuntimeHandler {
                            server: Arc::clone(&self.server),
                            session_id: self.legacy_binding.generation(),
                            session_principal: self.legacy_session.principal_binding(),
                            active_request: Arc::clone(&self.legacy_active_request),
                            request_cx: Arc::clone(&self.legacy_request_cx),
                            runtime: self.legacy_runtime.clone(),
                            legacy_admissions: Arc::clone(&self.legacy_admissions),
                            auth_receipt: Arc::clone(&self.legacy_auth_receipt),
                        },
                    )
                    .map_err(|error| {
                        DualEraHttpEndpointError::Transport(TransportError::Io(
                            std::io::Error::other(error.to_string()),
                        ))
                    })?;
                self.legacy_adapter.insert(adapter)
            }
        };
        let legacy_response = legacy_adapter_response_async(adapter, self.legacy_binding, &request)
            .await
            .map_err(|error| {
                DualEraHttpEndpointError::Transport(TransportError::Io(std::io::Error::other(
                    error.to_string(),
                )))
            })?;
        sync_live_legacy_runtime_from_adapter(&self.legacy_runtime, adapter);
        self.legacy_session
            .restore_log_level(self.legacy_runtime.log_level());
        let active_request = take_live_legacy_active_request(&self.legacy_active_request);
        if request.method == "notifications/cancelled" && request.id.is_none() {
            let fingerprint = self
                .legacy_auth_receipt
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .as_ref()
                .map(|receipt| receipt.fingerprint.clone());
            // Control frames must not cancel unless they prove the already-bound
            // SSE opener. An unbound session or a different principal is ignored.
            if fingerprint.is_some_and(|fingerprint| {
                self.legacy_session
                    .principal_binding()
                    .verify_existing(fingerprint)
            }) && let Ok(params) = parse_params::<CancelledParams>(request.params.clone())
            {
                self.server
                    .handle_cancelled_notification(self.legacy_binding.generation(), params);
            }
        }
        let Some(legacy_response) = legacy_response else {
            return Ok(ServerHttpEndpointResponse::Immediate(response));
        };
        let handled = legacy_handled_response(legacy_response, active_request, cx);
        handled
            .send_with(&mut self.legacy_session, |response| {
                self.endpoint_session
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .publish_legacy_message(&JsonRpcMessage::Response(response.clone()))
                    .map_err(|error| {
                        TransportError::Io(std::io::Error::other(error.to_string()))
                    })?;
                Ok(())
            })
            .map_err(DualEraHttpEndpointError::from)?;
        Ok(ServerHttpEndpointResponse::Immediate(response))
    }

    /// Closes this session, joins every owned modern dispatch, and releases its
    /// exact legacy lifecycle state.
    ///
    /// This is the structured settlement boundary. Callers that admitted a
    /// modern SSE dispatch must await it before dropping the session.
    pub async fn close(&mut self, cx: &Cx) {
        let dispatches = self.begin_close();
        for mut task in dispatches {
            let _ = task.join(cx).await;
        }
    }

    fn begin_close(&mut self) -> Vec<asupersync::runtime::TaskHandle<()>> {
        if self.closed {
            return Vec::new();
        }
        self.closed = true;
        if !self.modern_connection.is_ephemeral() {
            self.modern_connection.disconnect();
        }
        let dispatches = cancel_modern_http_dispatches(&self.server, &self.modern_dispatches, None);
        #[cfg(feature = "legacy-2024-11-05")]
        self.legacy_admissions.cancel_all();
        #[cfg(feature = "legacy-2024-11-05")]
        if let Some(adapter) = self.legacy_adapter.as_mut() {
            let _ = adapter.close(self.legacy_binding);
        }
        self.endpoint_session
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .close();
        dispatches
    }

    fn reap_modern_dispatches(&mut self) {
        let mut dispatches = self
            .modern_dispatches
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let mut active = Vec::with_capacity(dispatches.len());
        for mut dispatch in std::mem::take(&mut *dispatches) {
            if matches!(dispatch.task.try_join(), Ok(None)) {
                active.push(dispatch);
            }
        }
        *dispatches = active;
    }

    #[cfg(test)]
    fn has_modern_dispatches(&self) -> bool {
        !self
            .modern_dispatches
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .is_empty()
    }

    #[cfg(feature = "legacy-2024-11-05")]
    fn cancellation_control(&self) -> HttpLegacyCancellationControl {
        HttpLegacyCancellationControl {
            server: Arc::clone(&self.server),
            session_id: self.legacy_binding.generation(),
            http_session_id: self.legacy_session_id.clone(),
            legacy_message_path: self.server.http_config.legacy_message_path.clone(),
            legacy_lifecycle: self.legacy_lifecycle.clone(),
            session_principal: self.legacy_session.principal_binding(),
            max_body_size: self.server.http_config.handler_config.max_body_size,
            admissions: Arc::clone(&self.legacy_admissions),
        }
    }
}

impl Drop for ServerHttpSession {
    fn drop(&mut self) {
        // A synchronous destructor cannot drive the caller-owned asupersync
        // runtime. Fail closed by revoking every exact transport/MCP authority
        // in `begin_close`, aborting its task, and consuming any terminal
        // result already available. Pending cancelled tasks remain owned by
        // their structured runtime region; unlike the former process-global
        // queue, this path retains no cross-session work and claims no join
        // guarantee. `close(&Cx).await` is the required joined boundary.
        for mut task in self.begin_close() {
            let _ = task.try_join();
        }
    }
}

#[cfg(feature = "legacy-2024-11-05")]
fn legacy_origin_from_host(host: &str) -> Option<String> {
    if host.is_empty()
        || host.bytes().any(|byte| {
            byte.is_ascii_whitespace()
                || matches!(byte, b'/' | b'?' | b'#' | b'\\' | b'\r' | b'\n' | b'\0')
        })
    {
        return None;
    }
    Some(format!("http://{host}"))
}

fn h1_request_to_transport(
    request: &asupersync::http::h1::Request,
) -> Result<HttpRequest, HttpResponse> {
    let method = match &request.method {
        Http1Method::Get => HttpMethod::Get,
        Http1Method::Post => HttpMethod::Post,
        Http1Method::Put => HttpMethod::Put,
        Http1Method::Delete => HttpMethod::Delete,
        Http1Method::Options => HttpMethod::Options,
        Http1Method::Head => HttpMethod::Head,
        Http1Method::Patch => HttpMethod::Patch,
        Http1Method::Connect | Http1Method::Trace | Http1Method::Extension(_) => {
            return Err(HttpResponse::new(HttpStatus::METHOD_NOT_ALLOWED));
        }
    };
    let (path, query) = request
        .uri
        .split_once('?')
        .map_or((request.uri.as_str(), ""), |(path, query)| (path, query));
    if !path.starts_with('/')
        || path
            .bytes()
            .any(|byte| matches!(byte, b'\r' | b'\n' | b'\0'))
    {
        return Err(HttpResponse::bad_request());
    }
    let mut transport = HttpRequest::new(method, path).with_body(request.body.clone());
    for (name, value) in &request.headers {
        if name
            .bytes()
            .chain(value.bytes())
            .any(|byte| matches!(byte, b'\r' | b'\n' | b'\0'))
        {
            return Err(HttpResponse::bad_request());
        }
        let normalized_name = name.to_ascii_lowercase();
        if normalized_name == "accept" {
            if let Some(accept) = transport.headers.get_mut(&normalized_name) {
                accept.push(',');
                accept.push_str(value);
            } else {
                transport = transport.with_header(name, value);
            }
        } else if transport.headers.contains_key(&normalized_name) {
            // Only list-valued Accept fields are merged. Every routing,
            // security, and singleton header remains cardinality-strict.
            return Err(HttpResponse::bad_request());
        } else {
            transport = transport.with_header(name, value);
        }
    }
    if !query.is_empty() {
        for pair in query.split('&') {
            let Some((name, value)) = pair.split_once('=') else {
                return Err(HttpResponse::bad_request());
            };
            if name.is_empty()
                || name
                    .bytes()
                    .chain(value.bytes())
                    .any(|byte| matches!(byte, b'\r' | b'\n' | b'\0'))
                || transport.query.contains_key(name)
            {
                return Err(HttpResponse::bad_request());
            }
            transport = transport.with_query(name, value);
        }
    }
    Ok(transport)
}

/// Captures exactly one native `Authorization` field before the H1 request is
/// decoded into the transport representation.  The raw H1 field sequence is
/// the only ingress that can represent duplicate case variants, so reject it
/// here rather than silently dropping custody before transport authorization.
fn h1_transport_authorization(
    request: &asupersync::http::h1::Request,
) -> Result<TransportAuthorization, HttpResponse> {
    if let Some((_, query)) = request.uri.split_once('?')
        && auth::query_has_access_credentials(query)
    {
        return Err(native_http_credential_location_rejection());
    }
    let mut singleton = None;
    for (name, value) in &request.headers {
        if name.eq_ignore_ascii_case("authorization") {
            if singleton.replace(value.as_str()).is_some() {
                return Err(native_http_authentication_rejection());
            }
        }
    }
    Ok(TransportAuthorization::from_singleton_header(singleton))
}

/// Retains the same singleton rule for direct public `HttpRequest` ingress.
/// Native H1 performs this check before conversion; direct callers can build a
/// header map themselves and must receive the identical case-insensitive
/// rejection rather than an order-dependent credential choice.
fn transport_authorization_from_http_request(
    request: &HttpRequest,
) -> Result<TransportAuthorization, HttpResponse> {
    if request
        .query
        .keys()
        .any(|name| auth::query_has_access_credentials(name))
    {
        return Err(native_http_credential_location_rejection());
    }
    let mut singleton = None;
    for (name, value) in &request.headers {
        if name.eq_ignore_ascii_case("authorization") {
            if singleton.replace(value.as_str()).is_some() {
                return Err(native_http_authentication_rejection());
            }
        }
    }
    Ok(TransportAuthorization::from_singleton_header(singleton))
}

/// Produces the bounded native HTTP authentication challenge used before any
/// public-session or SSE-body mutation.  It intentionally carries no provider
/// detail and never reflects a credential.
fn native_http_authentication_rejection() -> HttpResponse {
    HttpResponse::new(HttpStatus::UNAUTHORIZED).with_header("www-authenticate", "Bearer")
}

/// A fixed migration diagnostic: neither the source name nor its value is
/// reflected, and no provider has been invoked for this credential location.
fn native_http_credential_location_rejection() -> HttpResponse {
    native_http_authentication_rejection().with_json(&serde_json::json!({
        "error": "invalid_request",
        "message": "HTTP credentials must use the Authorization header"
    }))
}

fn oauth_http_no_store(response: HttpResponse) -> HttpResponse {
    response
        .with_header("cache-control", "no-store")
        .with_header("pragma", "no-cache")
}

fn oauth_http_error(error: OAuthError) -> HttpResponse {
    let status = match &error {
        OAuthError::ServerError(_) | OAuthError::TemporarilyUnavailable(_) => {
            HttpStatus::SERVICE_UNAVAILABLE
        }
        _ => HttpStatus::BAD_REQUEST,
    };
    // OAuth error descriptions may contain implementation detail. The public
    // route exposes only the standardized error code.
    oauth_http_no_store(
        HttpResponse::new(status).with_json(&serde_json::json!({ "error": error.error_code() })),
    )
}

/// RFC 6749 section 5.2 requires a matching challenge only when failed client
/// authentication used the Authorization header. Form and public-client
/// failures remain HTTP 400 without inviting a different authentication method.
fn oauth_http_client_authentication_error(
    error: OAuthError,
    used_basic_authorization: bool,
) -> HttpResponse {
    match &error {
        OAuthError::InvalidClient(_) if used_basic_authorization => {
            oauth_http_client_authentication_rejection()
        }
        _ => oauth_http_error(error),
    }
}

fn oauth_http_invalid_request() -> HttpResponse {
    oauth_http_no_store(
        HttpResponse::bad_request().with_json(&serde_json::json!({ "error": "invalid_request" })),
    )
}

fn oauth_http_method_not_allowed(allow: &'static str) -> HttpResponse {
    oauth_http_no_store(
        HttpResponse::new(HttpStatus::METHOD_NOT_ALLOWED).with_header("allow", allow),
    )
}

fn oauth_http_client_authentication_rejection() -> HttpResponse {
    oauth_http_no_store(
        HttpResponse::new(HttpStatus::UNAUTHORIZED)
            .with_header("www-authenticate", "Basic realm=\"oauth\"")
            .with_json(&serde_json::json!({ "error": "invalid_client" })),
    )
}

/// Selects one credential location before any OAuth state mutation. Basic
/// username/password components use OAuth form decoding, not raw HTTP Basic
/// text (RFC 6749 section 2.3.1). Decoding is bounded before allocation and all
/// intermediate credential buffers are zeroized on success and rejection.
fn oauth_http_client_credentials(
    admission: &mut OAuthParameterAdmission,
    authorization: Option<&str>,
) -> Result<(String, Option<String>, oauth::TokenEndpointAuthMethod), HttpResponse> {
    let Some(authorization) = authorization else {
        let client_id = oauth_required_parameter(admission, OAuthParameterName::ClientId)
            .map_err(oauth_http_error)?;
        let client_secret_present = admission
            .parameters()
            .iter()
            .any(|parameter| parameter.is_defined() && parameter.name() == "client_secret");
        let client_secret = admission
            .take_defined_value(OAuthParameterName::ClientSecret)
            .map(|value| value.into_string())
            .or_else(|| client_secret_present.then(String::new));
        let method = if client_secret.is_some() {
            oauth::TokenEndpointAuthMethod::ClientSecretPost
        } else {
            oauth::TokenEndpointAuthMethod::None
        };
        return Ok((client_id, client_secret, method));
    };

    // Keep the raw parameter inventory: empty client_id/client_secret fields
    // are omitted from the taking surface but still conflict with Basic.
    if admission.parameters().iter().any(|parameter| {
        parameter.is_defined() && matches!(parameter.name(), "client_id" | "client_secret")
    }) {
        return Err(oauth_http_invalid_request());
    }
    let authorization = authorization.trim_matches([' ', '\t']);
    let scheme = authorization.split_ascii_whitespace().next().unwrap_or("");
    if !scheme.eq_ignore_ascii_case("basic") {
        return Err(oauth_http_invalid_request());
    }
    let (scheme, encoded) = authorization
        .split_once(' ')
        .ok_or_else(oauth_http_client_authentication_rejection)?;
    if !scheme.eq_ignore_ascii_case("basic") {
        return Err(oauth_http_client_authentication_rejection());
    }
    let encoded = encoded.trim_start_matches(' ');
    // Every UTF-8 byte can expand to three percent-encoded bytes; add the
    // Basic colon and padded base64 expansion. This also bounds malformed
    // headers without allocating their decoded representation.
    const MAX_BASIC_DECODED_BYTES: usize =
        3 * (oauth::MAX_OAUTH_CLIENT_ID_BYTES + oauth::MAX_OAUTH_CLIENT_CREDENTIAL_BYTES) + 1;
    const MAX_BASIC_ENCODED_BYTES: usize = 4 * MAX_BASIC_DECODED_BYTES.div_ceil(3);
    if encoded.is_empty() || encoded.len() > MAX_BASIC_ENCODED_BYTES {
        return Err(oauth_http_client_authentication_rejection());
    }
    use base64::Engine as _;
    let mut decoded = zeroize::Zeroizing::new(Vec::with_capacity(encoded.len().div_ceil(4) * 3));
    base64::engine::general_purpose::STANDARD
        .decode_vec(encoded, &mut decoded)
        .map_err(|_| oauth_http_client_authentication_rejection())?;
    if decoded.len() > MAX_BASIC_DECODED_BYTES {
        return Err(oauth_http_client_authentication_rejection());
    }
    let colon = decoded
        .iter()
        .position(|byte| *byte == b':')
        .ok_or_else(oauth_http_client_authentication_rejection)?;
    let client_id = zeroize::Zeroizing::new(
        oauth::decode_oauth_form_component(&decoded[..colon], oauth::MAX_OAUTH_CLIENT_ID_BYTES)
            .map_err(|_| oauth_http_client_authentication_rejection())?,
    );
    let client_secret = zeroize::Zeroizing::new(
        oauth::decode_oauth_form_component(
            &decoded[colon + 1..],
            oauth::MAX_OAUTH_CLIENT_CREDENTIAL_BYTES,
        )
        .map_err(|_| oauth_http_client_authentication_rejection())?,
    );
    if client_id.is_empty()
        || client_id.chars().any(char::is_control)
        || client_secret.chars().any(char::is_control)
    {
        return Err(oauth_http_client_authentication_rejection());
    }
    // An empty Basic password stays Some(""): it cannot downgrade to a
    // public client's no-secret authentication in the underlying verifier.
    Ok((
        client_id.to_string(),
        Some(client_secret.to_string()),
        oauth::TokenEndpointAuthMethod::ClientSecretBasic,
    ))
}

fn h1_oauth_singleton_header<'a>(
    request: &'a asupersync::http::h1::Request,
    expected_name: &str,
) -> Result<Option<&'a str>, HttpResponse> {
    let mut singleton = None;
    for (name, value) in &request.headers {
        if name.eq_ignore_ascii_case(expected_name) {
            if singleton.replace(value.as_str()).is_some() {
                return Err(oauth_http_invalid_request());
            }
        }
    }
    Ok(singleton)
}

fn oauth_json_content_type(request: &asupersync::http::h1::Request) -> Result<(), HttpResponse> {
    let Some(content_type) = h1_oauth_singleton_header(request, "content-type")? else {
        return Err(HttpResponse::new(HttpStatus(415)));
    };
    if !content_type
        .trim_matches([' ', '\t'])
        .eq_ignore_ascii_case("application/json")
    {
        return Err(HttpResponse::new(HttpStatus(415)));
    }
    Ok(())
}

fn oauth_form_content_type(request: &asupersync::http::h1::Request) -> Result<(), HttpResponse> {
    let Some(content_type) = h1_oauth_singleton_header(request, "content-type")? else {
        return Err(HttpResponse::new(HttpStatus(415)));
    };
    if !content_type
        .trim_matches([' ', '\t'])
        .eq_ignore_ascii_case("application/x-www-form-urlencoded")
    {
        return Err(HttpResponse::new(HttpStatus(415)));
    }
    Ok(())
}

fn oauth_required_parameter(
    admission: &mut OAuthParameterAdmission,
    name: OAuthParameterName,
) -> Result<String, OAuthError> {
    admission
        .take_defined_value(name)
        .map(|value| value.into_string())
        .ok_or_else(|| {
            OAuthError::InvalidRequest("required OAuth parameter is missing".to_string())
        })
}

fn oauth_authorization_request(
    admission: &mut OAuthParameterAdmission,
) -> Result<AuthorizationRequest, OAuthError> {
    let code_challenge_method =
        oauth_required_parameter(admission, OAuthParameterName::CodeChallengeMethod)?;
    let code_challenge_method =
        CodeChallengeMethod::parse(&code_challenge_method).ok_or_else(|| {
            OAuthError::InvalidRequest("unsupported code_challenge_method".to_string())
        })?;
    let scopes = admission
        .take_defined_value(OAuthParameterName::Scope)
        .map(|value| {
            value
                .into_string()
                .split_ascii_whitespace()
                .map(str::to_owned)
                .collect()
        })
        .unwrap_or_default();
    Ok(AuthorizationRequest {
        response_type: oauth_required_parameter(admission, OAuthParameterName::ResponseType)?,
        client_id: oauth_required_parameter(admission, OAuthParameterName::ClientId)?,
        redirect_uri: oauth_required_parameter(admission, OAuthParameterName::RedirectUri)?,
        resource: admission
            .take_defined_value(OAuthParameterName::Resource)
            .map(|value| value.into_string()),
        scopes,
        state: admission
            .take_defined_value(OAuthParameterName::State)
            .map(|value| value.into_string()),
        code_challenge: oauth_required_parameter(admission, OAuthParameterName::CodeChallenge)?,
        code_challenge_method,
    })
}

fn oauth_token_request(
    admission: &mut OAuthParameterAdmission,
    client_id: String,
    client_secret: Option<String>,
    client_authentication_method: oauth::TokenEndpointAuthMethod,
    development_client_credentials_enabled: bool,
) -> Result<TokenRequest, OAuthError> {
    let grant_type = oauth_required_parameter(admission, OAuthParameterName::GrantType)?;
    let machine_grant =
        development_client_credentials_enabled && grant_type == "client_credentials";
    if machine_grant
        && admission.parameters().iter().any(|parameter| {
            matches!(
                parameter.name(),
                "code"
                    | "redirect_uri"
                    | "code_verifier"
                    | "refresh_token"
                    | "client_assertion"
                    | "client_assertion_type"
            )
        })
    {
        return Err(OAuthError::InvalidRequest(
            "machine requests must use only the configured client authentication method"
                .to_string(),
        ));
    }
    let scopes = admission
        .take_defined_value(OAuthParameterName::Scope)
        .map(|value| {
            let value = value.into_string();
            if machine_grant {
                // RFC 6749 scope is a nonempty SP-separated sequence. Do not
                // normalize tabs, repeated spaces or leading/trailing spaces
                // into an authorized machine request.
                if value.split(' ').any(|scope| {
                    scope.is_empty()
                        || !scope
                            .bytes()
                            .all(|byte| matches!(byte, 0x21 | 0x23..=0x5B | 0x5D..=0x7E))
                }) {
                    return Err(OAuthError::InvalidScope(
                        "invalid machine scope syntax".to_string(),
                    ));
                }
            }
            Ok(value.split_ascii_whitespace().map(str::to_owned).collect())
        })
        .transpose()?;
    Ok(TokenRequest {
        grant_type,
        code: admission
            .take_defined_value(OAuthParameterName::Code)
            .map(|value| value.into_string()),
        redirect_uri: admission
            .take_defined_value(OAuthParameterName::RedirectUri)
            .map(|value| value.into_string()),
        client_id,
        client_secret,
        client_authentication_method,
        code_verifier: admission
            .take_defined_value(OAuthParameterName::CodeVerifier)
            .map(|value| value.into_string()),
        refresh_token: admission
            .take_defined_value(OAuthParameterName::RefreshToken)
            .map(|value| value.into_string()),
        scopes,
        resource: admission
            .take_defined_value(OAuthParameterName::Resource)
            .map(|value| value.into_string()),
    })
}

/// OIDC Core 5.3 UserInfo: the discovery document's `userinfo_endpoint`
/// (bd-vej30). The access token is accepted only as an RFC 6750 Bearer
/// `Authorization` header; failures carry the RFC 6750 challenge and never
/// reflect the credential.
#[cfg(feature = "builtin-auth-server")]
fn oidc_userinfo_response(
    oidc: &crate::oauth::OidcHttpRoutes,
    request: &asupersync::http::h1::Request,
    authorization_header: Option<&str>,
    raw_query: &str,
) -> HttpResponse {
    if !matches!(request.method, Http1Method::Get | Http1Method::Post) {
        return oauth_http_method_not_allowed("GET, POST");
    }
    if !raw_query.is_empty() || !request.body.is_empty() {
        return oauth_http_invalid_request();
    }
    let bearer = authorization_header.and_then(|header| {
        let (scheme, token) = header.trim().split_once(' ')?;
        let token = token.trim_start();
        (scheme.eq_ignore_ascii_case("bearer")
            && !token.is_empty()
            && !token.contains(char::is_whitespace))
        .then_some(token)
    });
    let Some(token) = bearer else {
        return oidc_userinfo_challenge(HttpStatus::UNAUTHORIZED, None);
    };
    match oidc.provider().userinfo(token) {
        Ok(claims) => oauth_http_no_store(HttpResponse::ok().with_json(&claims)),
        Err(oidc::OidcError::MissingOpenIdScope) => {
            oidc_userinfo_challenge(HttpStatus::FORBIDDEN, Some("insufficient_scope"))
        }
        Err(_) => oidc_userinfo_challenge(HttpStatus::UNAUTHORIZED, Some("invalid_token")),
    }
}

#[cfg(feature = "builtin-auth-server")]
fn oidc_userinfo_challenge(status: HttpStatus, error: Option<&'static str>) -> HttpResponse {
    let Some(error) = error else {
        return oauth_http_no_store(
            HttpResponse::new(status).with_header("www-authenticate", "Bearer"),
        );
    };
    oauth_http_no_store(
        HttpResponse::new(status)
            .with_header("www-authenticate", format!("Bearer error=\"{error}\""))
            .with_json(&serde_json::json!({ "error": error })),
    )
}

fn dispatch_oauth_h1_request(
    routes: &OAuthHttpRoutes,
    request: &asupersync::http::h1::Request,
    raw_path: &str,
    raw_query: &str,
) -> HttpResponse {
    let authorization_header = match h1_oauth_singleton_header(request, "authorization") {
        Ok(header) => header,
        Err(response) => return response,
    };
    if raw_path == routes.metadata_path() {
        if authorization_header.is_some() || request.uri.contains('?') || !request.body.is_empty() {
            return oauth_http_invalid_request();
        }
        if !matches!(request.method, Http1Method::Get) {
            return oauth_http_method_not_allowed("GET");
        }
        return match routes.authorization_server_metadata() {
            Ok(metadata) => oauth_http_no_store(HttpResponse::ok().with_json(&metadata)),
            Err(_) => oauth_http_no_store(HttpResponse::new(HttpStatus::SERVICE_UNAVAILABLE)),
        };
    }
    #[cfg(feature = "builtin-auth-server")]
    if let Some(oidc) = routes.oidc_routes() {
        if raw_path == oidc.userinfo_path() {
            return oidc_userinfo_response(oidc, request, authorization_header, raw_query);
        }
        if raw_path == oidc.discovery_path() || raw_path == oidc.jwks_path() {
            if authorization_header.is_some() || !raw_query.is_empty() || !request.body.is_empty() {
                return oauth_http_invalid_request();
            }
            if !matches!(request.method, Http1Method::Get) {
                return oauth_http_method_not_allowed("GET");
            }
            if raw_path == oidc.discovery_path() {
                return oauth_http_no_store(
                    HttpResponse::ok().with_json(
                        &oidc
                            .provider()
                            .discovery_document(routes.public_endpoint_base()),
                    ),
                );
            }
            return oidc
                .provider()
                .published_jwks_document(oidc.jwks_uri())
                .map(|body| {
                    oauth_http_no_store(
                        HttpResponse::ok()
                            .with_header("content-type", "application/jwk-set+json")
                            .with_body(body),
                    )
                })
                .unwrap_or_else(|_| HttpResponse::new(HttpStatus::SERVICE_UNAVAILABLE));
        }
    }
    if raw_path == routes.authorization_path() {
        if authorization_header.is_some() {
            return oauth_http_invalid_request();
        }
        if !matches!(request.method, Http1Method::Get) {
            return oauth_http_method_not_allowed("GET");
        }
        if !request.body.is_empty() {
            return oauth_http_invalid_request();
        }
        let mut admission = match OAuthParameterAdmission::admit(
            OAuthParameterEndpoint::AuthorizationQuery,
            raw_query.as_bytes(),
        ) {
            Ok(admission) => admission,
            Err(_) => return oauth_http_invalid_request(),
        };
        let authorization = match oauth_authorization_request(&mut admission) {
            Ok(authorization) => authorization,
            Err(error) => return oauth_http_error(error),
        };
        return match routes.server().authorize(&authorization) {
            Ok((_code, redirect)) => oauth_http_no_store(
                HttpResponse::new(HttpStatus(303)).with_header("location", redirect),
            ),
            Err(error) => routes
                .server()
                .authorization_error_redirect(&authorization, &error)
                .map(|redirect| {
                    oauth_http_no_store(
                        HttpResponse::new(HttpStatus(303)).with_header("location", redirect),
                    )
                })
                .unwrap_or_else(|| oauth_http_error(error)),
        };
    }

    if routes.registration_path() == Some(raw_path) {
        if authorization_header.is_some() || !raw_query.is_empty() {
            return oauth_http_invalid_request();
        }
        if !matches!(request.method, Http1Method::Post) {
            return oauth_http_method_not_allowed("POST");
        }
        if let Err(response) = oauth_json_content_type(request) {
            return oauth_http_no_store(response);
        }
        if admit_security_document(SecurityDocumentKind::ClientRegistration, &request.body).is_err()
        {
            return oauth_http_invalid_request();
        }
        let registration =
            match serde_json::from_slice::<NativePublicClientRegistrationRequest>(&request.body) {
                Ok(registration) => registration,
                Err(_) => return oauth_http_invalid_request(),
            };
        return match routes.server().register_native_public_client(registration) {
            Ok(response) => {
                oauth_http_no_store(HttpResponse::new(HttpStatus(201)).with_json(&response))
            }
            Err(error) => oauth_http_error(error),
        };
    }

    if !raw_query.is_empty() {
        return oauth_http_invalid_request();
    }
    if raw_path == routes.token_path() {
        if !matches!(request.method, Http1Method::Post) {
            return oauth_http_method_not_allowed("POST");
        }
        if let Err(response) = oauth_form_content_type(request) {
            return oauth_http_no_store(response);
        }
        let mut admission = match OAuthParameterAdmission::admit(
            OAuthParameterEndpoint::TokenForm,
            &request.body,
        ) {
            Ok(admission) => admission,
            Err(_) => return oauth_http_invalid_request(),
        };
        let (client_id, client_secret, client_authentication_method) =
            match oauth_http_client_credentials(&mut admission, authorization_header) {
                Ok(credentials) => credentials,
                Err(response) => return response,
            };
        let token = match oauth_token_request(
            &mut admission,
            client_id,
            client_secret,
            client_authentication_method,
            routes.server().development_client_credentials_enabled(),
        ) {
            Ok(token) => token,
            Err(error) => return oauth_http_error(error),
        };
        return match routes.server().token(&token) {
            Ok(response) => oauth_http_no_store(HttpResponse::ok().with_json(&response)),
            Err(error) => {
                oauth_http_client_authentication_error(error, authorization_header.is_some())
            }
        };
    }

    if !matches!(request.method, Http1Method::Post) {
        return oauth_http_method_not_allowed("POST");
    }
    if let Err(response) = oauth_form_content_type(request) {
        return oauth_http_no_store(response);
    }
    let mut admission =
        match OAuthParameterAdmission::admit(OAuthParameterEndpoint::RevocationForm, &request.body)
        {
            Ok(admission) => admission,
            Err(_) => return oauth_http_invalid_request(),
        };
    let token = match oauth_required_parameter(&mut admission, OAuthParameterName::Token) {
        Ok(token) => token,
        Err(error) => return oauth_http_error(error),
    };
    let (client_id, client_secret, client_authentication_method) =
        match oauth_http_client_credentials(&mut admission, authorization_header) {
            Ok(credentials) => credentials,
            Err(response) => return response,
        };
    match routes.server().revoke(
        &token,
        &client_id,
        client_secret.as_deref(),
        client_authentication_method,
    ) {
        Ok(()) => oauth_http_no_store(HttpResponse::ok()),
        Err(error) => oauth_http_client_authentication_error(error, authorization_header.is_some()),
    }
}

/// Immutable route facts needed before the generic HTTP/1 decoder accepts a
/// request body. Keeping this separate from the OAuth server prevents the
/// listener's MCP-sized body allowance from becoming an OAuth body allowance.
#[derive(Clone)]
struct OAuthNativeH1RouteLimits {
    metadata: String,
    authorization: String,
    token: String,
    revocation: String,
    registration: Option<String>,
    #[cfg(feature = "builtin-auth-server")]
    oidc_discovery: Option<String>,
    #[cfg(feature = "builtin-auth-server")]
    oidc_jwks: Option<String>,
    #[cfg(feature = "builtin-auth-server")]
    oidc_userinfo: Option<String>,
}

impl OAuthNativeH1RouteLimits {
    fn from_routes(routes: &OAuthHttpRoutes) -> Self {
        Self {
            metadata: routes.metadata_path().to_owned(),
            authorization: routes.authorization_path().to_owned(),
            token: routes.token_path().to_owned(),
            revocation: routes.revocation_path().to_owned(),
            registration: routes.registration_path().map(str::to_owned),
            #[cfg(feature = "builtin-auth-server")]
            oidc_discovery: routes
                .oidc_routes()
                .map(|oidc| oidc.discovery_path().to_owned()),
            #[cfg(feature = "builtin-auth-server")]
            oidc_jwks: routes.oidc_routes().map(|oidc| oidc.jwks_path().to_owned()),
            #[cfg(feature = "builtin-auth-server")]
            oidc_userinfo: routes
                .oidc_routes()
                .map(|oidc| oidc.userinfo_path().to_owned()),
        }
    }

    fn body_limit_for_path(&self, path: &str) -> Option<usize> {
        if path == self.metadata || path == self.authorization || {
            #[cfg(feature = "builtin-auth-server")]
            {
                self.oidc_discovery.as_deref() == Some(path)
                    || self.oidc_jwks.as_deref() == Some(path)
                    || self.oidc_userinfo.as_deref() == Some(path)
            }
            #[cfg(not(feature = "builtin-auth-server"))]
            {
                false
            }
        } {
            Some(0)
        } else if path == self.token || path == self.revocation {
            Some(oauth::MAX_OAUTH_FORM_BODY_BYTES)
        } else if self.registration.as_deref() == Some(path) {
            Some(MAX_CLIENT_REGISTRATION_BYTES)
        } else {
            None
        }
    }
}

/// Pre-body routing state for [`NativeHttp1Codec`].
#[derive(Clone, Copy, PartialEq, Eq)]
enum NativeHttp1PreBodyAdmission {
    AwaitingHead,
    Complete,
}

/// Native HTTP/1 codec with a route-aware OAuth pre-body limit.
///
/// The generic codec still owns all HTTP parsing and MCP's configured body
/// limit. This wrapper only examines a complete unconsumed request head before
/// delegating, so OAuth `Content-Length` and transfer-encoding admission can
/// fail before the generic decoder allocates a body at the larger MCP limit.
struct NativeHttp1Codec {
    inner: Http1Codec,
    oauth_limits: Option<OAuthNativeH1RouteLimits>,
    pre_body_admission: NativeHttp1PreBodyAdmission,
}

impl NativeHttp1Codec {
    fn new(max_body_size: usize, routes: Option<&OAuthHttpRoutes>) -> Self {
        Self {
            inner: Http1Codec::new().max_body_size(max_body_size),
            oauth_limits: routes.map(OAuthNativeH1RouteLimits::from_routes),
            pre_body_admission: NativeHttp1PreBodyAdmission::AwaitingHead,
        }
    }

    fn pre_admit_oauth_body(&mut self, source: &BytesMut) -> Result<(), Http1DecodeError> {
        if self.pre_body_admission == NativeHttp1PreBodyAdmission::Complete {
            return Ok(());
        }
        let Some(head_end) = source.windows(4).position(|window| window == b"\r\n\r\n") else {
            return Ok(());
        };
        // The underlying codec remains the sole authority for malformed HTTP.
        // A non-UTF-8 or malformed head is left for it to reject.
        let Ok(head) = std::str::from_utf8(&source[..head_end]) else {
            return Ok(());
        };
        let Some(request_line) = head.split("\r\n").next() else {
            return Ok(());
        };
        let mut request_line_parts = request_line.split(' ');
        let Some(_method) = request_line_parts.next() else {
            return Ok(());
        };
        let Some(target) = request_line_parts.next() else {
            return Ok(());
        };
        let raw_path = target.split_once('?').map_or(target, |(path, _)| path);
        let Some(limits) = self.oauth_limits.as_ref() else {
            self.pre_body_admission = NativeHttp1PreBodyAdmission::Complete;
            return Ok(());
        };
        let Some(body_limit) = limits.body_limit_for_path(raw_path) else {
            self.pre_body_admission = NativeHttp1PreBodyAdmission::Complete;
            return Ok(());
        };
        if raw_path == limits.authorization {
            let query = target.split_once('?').map_or("", |(_, query)| query);
            if query.len() > oauth::MAX_OAUTH_AUTHORIZATION_QUERY_BYTES {
                return Err(Http1DecodeError::BodyTooLarge);
            }
        }

        for line in head.split("\r\n").skip(1) {
            let Some((name, value)) = line.split_once(':') else {
                continue;
            };
            if name.eq_ignore_ascii_case("transfer-encoding") {
                // An OAuth route has a small, fixed body budget. Rejecting a
                // streaming transfer before the generic decoder starts
                // buffering preserves that budget without constraining MCP.
                return Err(Http1DecodeError::BodyTooLarge);
            }
            if name.eq_ignore_ascii_case("content-length")
                && value
                    .trim()
                    .parse::<usize>()
                    .is_ok_and(|length| length > body_limit)
            {
                return Err(Http1DecodeError::BodyTooLarge);
            }
        }
        self.pre_body_admission = NativeHttp1PreBodyAdmission::Complete;
        Ok(())
    }
}

impl Decoder for NativeHttp1Codec {
    type Item = asupersync::http::h1::Request;
    type Error = Http1DecodeError;

    fn decode(&mut self, source: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        self.pre_admit_oauth_body(source)?;
        let request = self.inner.decode(source)?;
        if request.is_some() {
            self.pre_body_admission = NativeHttp1PreBodyAdmission::AwaitingHead;
        }
        Ok(request)
    }
}

impl Encoder<Http1Response> for NativeHttp1Codec {
    type Error = Http1DecodeError;

    fn encode(
        &mut self,
        response: Http1Response,
        destination: &mut BytesMut,
    ) -> Result<(), Self::Error> {
        self.inner.encode(response, destination)
    }
}

fn native_http1_codec(endpoint: &ServerHttpEndpoint) -> NativeHttp1Codec {
    NativeHttp1Codec::new(
        endpoint.server.http_config.handler_config.max_body_size,
        endpoint.server.oauth_http_routes.as_ref(),
    )
}

async fn next_native_http1_request(
    cx: &Cx,
    listener_shutdown: &HttpListenerShutdown,
    framed: &mut Framed<AsyncTcpStream, NativeHttp1Codec>,
    read_timeout: Duration,
) -> Option<Result<asupersync::http::h1::Request, Http1DecodeError>> {
    // Every wait below is bounded by this one deadline, so an idle or
    // trickling peer is closed and its connection slot released.
    let deadline = cx
        .now()
        .saturating_add_nanos(u64::try_from(read_timeout.as_nanos()).unwrap_or(u64::MAX));
    loop {
        if listener_shutdown.is_requested() || cx.checkpoint().is_err() {
            return None;
        }
        let now = cx.now();
        if now >= deadline {
            return None;
        }
        let wait = HTTP_ACCEPT_CANCEL_POLL.min(Duration::from_nanos(deadline.duration_since(now)));
        if let Ok(request) = asupersync::time::timeout(now, wait, framed.next()).await {
            return request;
        }
    }
}

/// Handles an OAuth-only route before MCP's transport conversion can merge
/// query fields or discard raw header cardinality. Returns true only when the
/// request path was one of the installed immutable OAuth routes.
async fn serve_oauth_h1_request<T>(
    cx: &Cx,
    listener_shutdown: &HttpListenerShutdown,
    framed: &mut Framed<T, NativeHttp1Codec>,
    endpoint: &ServerHttpEndpoint,
    request: &asupersync::http::h1::Request,
) -> bool
where
    T: asupersync::io::AsyncWrite + Unpin,
{
    let Some(routes) = endpoint.server.oauth_http_routes.as_ref() else {
        return false;
    };
    let (raw_path, raw_query) = request
        .uri
        .split_once('?')
        .map_or((request.uri.as_str(), ""), |(path, query)| (path, query));
    if !routes.has_path(raw_path) {
        return false;
    }

    if cx.checkpoint().is_err() {
        let _ = send_h1_response(
            cx,
            listener_shutdown,
            framed,
            HttpResponse::new(HttpStatus::SERVICE_UNAVAILABLE),
        )
        .await;
        return true;
    }
    // RFC 8414 metadata is derived only from immutable, bounded configuration.
    // It never invokes consent, authentication, signing, or issuer state, so
    // discovery remains available without occupying a blocking worker.
    if raw_path == routes.metadata_path() {
        let response = dispatch_oauth_h1_request(routes, request, raw_path, raw_query);
        let _ = send_h1_response(cx, listener_shutdown, framed, response).await;
        return true;
    }
    let routes = routes.clone();
    let request = request.clone();
    let raw_path = raw_path.to_owned();
    let raw_query = raw_query.to_owned();
    let response = match cx.spawn_blocking(move |route_cx| {
        if route_cx.checkpoint().is_err() {
            return HttpResponse::new(HttpStatus::SERVICE_UNAVAILABLE);
        }
        dispatch_oauth_h1_request(&routes, &request, &raw_path, &raw_query)
    }) {
        Ok(mut dispatch) => match dispatch.join(cx).await {
            Ok(response) => response,
            Err(_) => HttpResponse::internal_error(),
        },
        Err(_) => HttpResponse::internal_error(),
    };
    let _ = send_h1_response(cx, listener_shutdown, framed, response).await;
    true
}

fn h1_response(mut response: HttpResponse) -> Http1Response {
    response
        .headers
        .retain(|name, _| !name.eq_ignore_ascii_case("connection"));
    response = response.with_header("connection", "close");
    let mut h1 = Http1Response::new(response.status.0, "", response.body);
    for (name, value) in response.headers {
        h1 = h1.with_header(name, value);
    }
    h1
}

async fn send_h1_response<T>(
    cx: &Cx,
    listener_shutdown: &HttpListenerShutdown,
    framed: &mut Framed<T, NativeHttp1Codec>,
    response: HttpResponse,
) -> Result<(), ()>
where
    T: asupersync::io::AsyncWrite + Unpin,
{
    // The listener's shutdown cancellation owns every ordinary H1 connection.
    // Unlike SSE terminal controls, an immediate response has no protected
    // drain phase and must never begin a new wire write after cancellation.
    if listener_shutdown.is_requested() {
        return Err(());
    }
    cx.checkpoint().map_err(|_| ())?;
    framed.send(h1_response(response)).map_err(|_| ())?;
    // `Framed::send` only accepts the response into its codec buffer; the
    // socket commit happens while closing. Re-check so a shutdown that wins
    // between encoding and that commit suppresses the buffered response.
    if listener_shutdown.is_requested() {
        return Err(());
    }
    cx.checkpoint().map_err(|_| ())?;
    std::future::poll_fn(|task_cx| {
        if listener_shutdown.is_requested() || cx.is_cancel_requested() {
            // Drop the framed connection with its buffered response rather
            // than allowing a shutdown-cancelled task to commit it.
            return std::task::Poll::Ready(Ok(()));
        }
        framed.poll_close(task_cx)
    })
    .await
    .map_err(|_| ())
}

/// Writes the one pre-representation rejection that a modern SSE request can
/// elect after dispatch.  This path deliberately owns a raw write half: the
/// request body has already been split so peer closure can cancel dispatch
/// while the outcome is still unknown.
async fn send_h1_bad_request_response<W>(
    cx: &Cx,
    listener_shutdown: &HttpListenerShutdown,
    writer: &mut W,
    response: &HttpResponse,
) -> Result<(), ()>
where
    W: asupersync::io::AsyncWrite + Unpin,
{
    if response.status != HttpStatus::BAD_REQUEST {
        return Err(());
    }
    let mut head = b"HTTP/1.1 400 Bad Request\r\n".to_vec();
    for (name, value) in &response.headers {
        if name.eq_ignore_ascii_case("connection")
            || name.eq_ignore_ascii_case("content-length")
            || name.eq_ignore_ascii_case("transfer-encoding")
        {
            continue;
        }
        if name
            .bytes()
            .chain(value.bytes())
            .any(|byte| matches!(byte, b'\r' | b'\n' | b'\0'))
        {
            return Err(());
        }
        head.extend_from_slice(name.as_bytes());
        head.extend_from_slice(b": ");
        head.extend_from_slice(value.as_bytes());
        head.extend_from_slice(b"\r\n");
    }
    head.extend_from_slice(format!("content-length: {}\r\n", response.body.len()).as_bytes());
    head.extend_from_slice(b"connection: close\r\n\r\n");
    head.extend_from_slice(&response.body);
    if listener_shutdown.is_requested() {
        return Err(());
    }
    cx.checkpoint().map_err(|_| ())?;
    writer.write_all(&head).await.map_err(|_| ())?;
    writer.flush().await.map_err(|_| ())
}

fn sse_response_head(response: &HttpResponse) -> Result<Vec<u8>, ()> {
    let mut head = format!("HTTP/1.1 {} OK\r\n", response.status.0).into_bytes();
    for (name, value) in &response.headers {
        if name.eq_ignore_ascii_case("connection") {
            continue;
        }
        if name
            .bytes()
            .chain(value.bytes())
            .any(|byte| matches!(byte, b'\r' | b'\n' | b'\0'))
        {
            return Err(());
        }
        head.extend_from_slice(name.as_bytes());
        head.extend_from_slice(b": ");
        head.extend_from_slice(value.as_bytes());
        head.extend_from_slice(b"\r\n");
    }
    head.extend_from_slice(b"transfer-encoding: chunked\r\nconnection: close\r\n\r\n");
    Ok(head)
}

#[cfg(feature = "legacy-2024-11-05")]
async fn send_legacy_sse_stream(
    cx: &Cx,
    stream: AsyncTcpStream,
    response: DualEraHttpLegacySseResponse,
) -> Result<(), ()> {
    let (mut peer_reader, mut stream) = stream.into_split();
    let (peer_closed_sender, mut peer_closed_receiver) = oneshot::channel();
    let mut peer_watch = cx
        .spawn(move |_peer_cx| async move {
            let mut byte = [0_u8; 1];
            // The SSE GET request is fully decoded before this point. Any
            // later read completion (EOF, error, or unexpected bytes) closes
            // this one-way body without waiting for an application event to
            // cause a write-side error.
            let _ = peer_reader.read(&mut byte).await;
            let _ = peer_closed_sender.send_blocking(());
        })
        .map_err(|_| ())?;
    let result = async {
        stream
            .write_all(&sse_response_head(response.response())?)
            .await
            .map_err(|_| ())?;
        stream.flush().await.map_err(|_| ())?;
        // Park on the channel's registered receive waker so publication wakes
        // this writer directly. Race peer closure through its own wake-driven
        // signal so an idle stream still tears down promptly.
        let mut response = response;
        loop {
            let next = {
                let mut next_event = Box::pin(response.recv_event_async(cx));
                let mut peer_closed = Box::pin(peer_closed_receiver.recv(cx));
                std::future::poll_fn(|task_cx| {
                    if peer_closed.as_mut().poll(task_cx).is_ready() {
                        return std::task::Poll::Ready(None);
                    }
                    match next_event.as_mut().poll(task_cx) {
                        std::task::Poll::Ready(event) => std::task::Poll::Ready(Some(event)),
                        std::task::Poll::Pending => std::task::Poll::Pending,
                    }
                })
                .await
            };
            let Some(event) = next else {
                break;
            };
            let event = match event {
                Ok(event) => event,
                Err(_) => break,
            };
            let bytes = event.to_bytes().map_err(|_| ())?;
            let prefix = format!("{:X}\r\n", bytes.len());
            stream.write_all(prefix.as_bytes()).await.map_err(|_| ())?;
            stream.write_all(&bytes).await.map_err(|_| ())?;
            stream.write_all(b"\r\n").await.map_err(|_| ())?;
            stream.flush().await.map_err(|_| ())?;
        }
        let _ = stream.write_all(b"0\r\n\r\n").await;
        let _ = stream.flush().await;
        Ok(())
    }
    .await;
    peer_watch.abort();
    let _ = peer_watch.join(cx).await;
    result
}

enum ModernSseDispatchElection {
    Stream,
    Immediate(HttpResponse),
    Failed,
}

enum ModernSseNotificationDelivery {
    Pending(Vec<JsonRpcRequest>),
    Admitted,
    Streaming,
}

/// A transport-owned signal invoked only after final router handler admission.
/// Application contexts cannot construct or invoke this HTTP representation gate.
pub(crate) type FinalHandlerAdmission = Arc<dyn Fn() + Send + Sync>;

struct ModernSseNotificationGate {
    delivery: Mutex<ModernSseNotificationDelivery>,
    subscription_request: bool,
    outcome_gate: Option<Arc<ModernSseOutcomeGate>>,
    terminal_delivery: Arc<FinalSubscriptionTerminalDelivery>,
    committed_sender: NotificationSender,
    commit_failed: Arc<AtomicBool>,
    stream_admitted: Arc<AtomicBool>,
}

impl ModernSseNotificationGate {
    fn publish(&self, notification: JsonRpcRequest) {
        if final_subscription_terminal_notification(&notification) {
            self.terminal_delivery.mark_control_not_required();
            return;
        }
        if self.commit_failed.load(Ordering::Acquire) {
            return;
        }
        let mut delivery = self
            .delivery
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        match &mut *delivery {
            ModernSseNotificationDelivery::Streaming => {
                drop(delivery);
                (self.committed_sender)(notification);
                return;
            }
            ModernSseNotificationDelivery::Admitted => {
                (self.committed_sender)(notification);
            }
            ModernSseNotificationDelivery::Pending(pending) => {
                let acknowledgement = self.subscription_request
                    && final_subscription_acknowledgement_notification(&notification);
                if !acknowledgement {
                    pending.push(notification);
                    return;
                }
                let deferred = std::mem::take(pending);
                // Keep concurrent publishers behind the acknowledgement and
                // the frames already waiting for that subscription boundary.
                (self.committed_sender)(notification);
                if !self.finish_stream_admission(&mut delivery) {
                    return;
                }
                for notification in deferred {
                    (self.committed_sender)(notification);
                }
                return;
            }
        }
        self.finish_stream_admission(&mut delivery);
    }

    fn admit_handler(&self) {
        if self.subscription_request || self.commit_failed.load(Ordering::Acquire) {
            return;
        }
        let mut delivery = self
            .delivery
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let ModernSseNotificationDelivery::Pending(pending) = &mut *delivery else {
            return;
        };
        if pending.is_empty() {
            // Admission alone does not commit an HTTP representation. A
            // canonical error can still elect JSON 400 until a frame exists.
            *delivery = ModernSseNotificationDelivery::Admitted;
            return;
        }
        let mut deferred = std::mem::take(pending).into_iter();
        if let Some(notification) = deferred.next() {
            (self.committed_sender)(notification);
        }
        // The writer must be able to drain its bounded queue before the
        // remainder is committed. Admission still follows one real frame.
        if !self.finish_stream_admission(&mut delivery) {
            return;
        }
        for notification in deferred {
            (self.committed_sender)(notification);
        }
    }

    fn finish_stream_admission(&self, delivery: &mut ModernSseNotificationDelivery) -> bool {
        if self.commit_failed.load(Ordering::Acquire) {
            self.terminal_delivery.mark_failed();
            if let Some(outcome_gate) = &self.outcome_gate {
                outcome_gate.elect(ModernSseDispatchElection::Failed);
            }
            return false;
        }
        *delivery = ModernSseNotificationDelivery::Streaming;
        let elected = self
            .outcome_gate
            .as_ref()
            .is_none_or(|gate| gate.elect(ModernSseDispatchElection::Stream));
        if elected {
            // HTTP has no in-band cancellation control. Once the body starts,
            // its one terminal response owns the remaining settlement.
            if self.outcome_gate.is_some() {
                self.terminal_delivery.mark_control_not_required();
            }
            self.stream_admitted.store(true, Ordering::Release);
        }
        elected
    }

    fn take_pending(&self) -> Vec<JsonRpcRequest> {
        match &mut *self
            .delivery
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
        {
            ModernSseNotificationDelivery::Pending(pending) => std::mem::take(pending),
            ModernSseNotificationDelivery::Admitted | ModernSseNotificationDelivery::Streaming => {
                Vec::new()
            }
        }
    }
}

enum ModernSseOutcomeGateState {
    AwaitingElection(oneshot::Sender<ModernSseDispatchElection>),
    Elected { stream: bool },
}

/// A one-time dispatch-to-writer handoff for one live modern SSE request.
///
/// The sender is taken exactly once by the request-owned dispatcher. The
/// writer waits on the paired cancel-safe oneshot rather than polling shared
/// state. Peer body closure wins before an election, while an already-ready
/// election remains authoritative when cancellation becomes ready alongside
/// the writer's poll.
struct ModernSseOutcomeGate {
    state: Mutex<ModernSseOutcomeGateState>,
}

impl ModernSseOutcomeGate {
    fn new() -> (Arc<Self>, oneshot::Receiver<ModernSseDispatchElection>) {
        let (sender, receiver) = oneshot::channel();
        (
            Arc::new(Self {
                state: Mutex::new(ModernSseOutcomeGateState::AwaitingElection(sender)),
            }),
            receiver,
        )
    }

    /// Delivers one final representation election and reports whether this
    /// caller linearized it. A failed send still counts as won: the receiver
    /// may already have observed peer cancellation, but no later caller may
    /// substitute a different representation.
    fn elect(&self, election: ModernSseDispatchElection) -> bool {
        let sender = {
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if matches!(&*state, ModernSseOutcomeGateState::Elected { .. }) {
                return false;
            }
            let stream = matches!(&election, ModernSseDispatchElection::Stream);
            let ModernSseOutcomeGateState::AwaitingElection(sender) =
                std::mem::replace(&mut *state, ModernSseOutcomeGateState::Elected { stream })
            else {
                return false;
            };
            sender
        };
        let _ = sender.send_blocking(election);
        true
    }

    fn stream_admitted(&self) -> bool {
        matches!(
            &*self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner),
            ModernSseOutcomeGateState::Elected { stream: true }
        )
    }
}

async fn await_modern_sse_dispatch_election(
    cx: &Cx,
    request_cancellation: &McpRequestCancellation,
    receiver: &mut oneshot::Receiver<ModernSseDispatchElection>,
) -> Result<ModernSseDispatchElection, ()> {
    let mut election = std::pin::pin!(receiver.recv(cx));
    let mut cancelled = std::pin::pin!(request_cancellation.cancelled());
    std::future::poll_fn(|task_cx| match election.as_mut().poll(task_cx) {
        std::task::Poll::Ready(Ok(election)) => std::task::Poll::Ready(Ok(election)),
        std::task::Poll::Ready(Err(_)) => std::task::Poll::Ready(Err(())),
        std::task::Poll::Pending if cancelled.as_mut().poll(task_cx).is_ready() => {
            std::task::Poll::Ready(Err(()))
        }
        std::task::Poll::Pending => std::task::Poll::Pending,
    })
    .await
}

fn spawn_modern_sse_dispatch(
    cx: &Cx,
    server: Arc<Server>,
    http_stream_generation: u64,
    inbound: InboundRequestContext,
    request: JsonRpcRequest,
    raw_params: Option<Arc<str>>,
    auth_receipt: Option<AuthDispatchCustody>,
    response_sender: StreamableHttpRequestResponseSender,
    terminal_delivery: Arc<FinalSubscriptionTerminalDelivery>,
    outcome_gate: Option<Arc<ModernSseOutcomeGate>>,
) -> Result<asupersync::runtime::TaskHandle<()>, DualEraHttpEndpointError> {
    let policy = server.protocol_policy;
    let notification_response_sender = response_sender.clone();
    let notification_terminal_delivery = Arc::clone(&terminal_delivery);
    let terminal_commit = Arc::new(Mutex::new(()));
    cx.spawn(move |request_cx| async move {
        let inbound = inbound.with_cx(request_cx.clone());
        let cancellation = response_sender.request_cancellation();
        let subscription_request = request.method == SUBSCRIPTIONS_LISTEN;
        let mut duplicate_response = None;
        let _active_request = match request.id.clone() {
            Some(id) => match ActiveRequestGuard::try_new_with_cancellation(
                Arc::clone(&server.active_requests),
                http_stream_generation,
                id.clone(),
                request_cx.clone(),
                cancellation.clone(),
            ) {
                Ok(guard) => Some(guard),
                Err(_) => {
                    duplicate_response = Some(JsonRpcResponse::error(
                        Some(id),
                        JsonRpcError {
                            code: McpErrorCode::InvalidRequest.into(),
                            message: "Request id is already active".to_owned(),
                            data: None,
                        },
                    ));
                    None
                }
            },
            None => None,
        };
        let notification_cx = request_cx.clone();
        let notification_cancellation = response_sender.request_cancellation();
        let notification_terminal_commit = Arc::clone(&terminal_commit);
        let notification_commit_failed = Arc::new(AtomicBool::new(false));
        let notification_commit_failed_for_sender = Arc::clone(&notification_commit_failed);
        let committed_notification_sender: NotificationSender = Arc::new(move |notification| {
            let terminal_control = final_subscription_terminal_notification(&notification);
            // Modern HTTP never puts `notifications/cancelled` on its SSE
            // body. The registry elects a response-only terminal sequence
            // for this request body, but keep the transport boundary strict
            // if a future caller reaches this sender with such a control
            // frame.
            if terminal_control {
                notification_terminal_delivery.mark_control_not_required();
                return;
            }
            if notification_commit_failed_for_sender.load(Ordering::Acquire) {
                return;
            }
            let _terminal_commit = notification_terminal_commit
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let sent = retry_http_sse_commit(
                &notification_cx,
                &notification_cancellation,
                || {
                    notification_response_sender
                        .send_notification(&notification_cx, notification.clone())
                },
                retryable_http_sse_transport_error,
            );
            if sent.is_err() {
                // Exhausted transient contention is a delivery failure just as a
                // hard transport error is. Mark the response body terminal and
                // suppress every later log/response frame rather than silently
                // dropping progress and violating the final-frame ordering.
                notification_commit_failed_for_sender.store(true, Ordering::Release);
                notification_terminal_delivery.mark_failed();
                notification_cancellation.cancel();
            }
        });
        // `Stream` is the live writer's linearized admission point. A later
        // canonical -32021 may replace the terminal response only after this
        // point; before it, the same error still elects an HTTP JSON 400.
        let stream_admitted = Arc::new(AtomicBool::new(false));
        // Subscriptions admit at their acknowledgement. Ordinary live HTTP
        // requests admit at the router's handler boundary, keeping middleware
        // and parameter-header rejections ahead of the first SSE frame.
        let deferred_notifications = (subscription_request || outcome_gate.is_some()).then(|| {
            Arc::new(ModernSseNotificationGate {
                delivery: Mutex::new(ModernSseNotificationDelivery::Pending(Vec::new())),
                subscription_request,
                outcome_gate: outcome_gate.clone(),
                terminal_delivery: Arc::clone(&terminal_delivery),
                committed_sender: Arc::clone(&committed_notification_sender),
                commit_failed: Arc::clone(&notification_commit_failed),
                stream_admitted: Arc::clone(&stream_admitted),
            })
        });
        let notification_sender: NotificationSender = match &deferred_notifications {
            Some(deferred_notifications) => {
                let deferred_notifications = Arc::clone(deferred_notifications);
                Arc::new(move |notification| {
                    deferred_notifications.publish(notification);
                })
            }
            None => Arc::clone(&committed_notification_sender),
        };
        let handler_admission = deferred_notifications
            .as_ref()
            .filter(|_| outcome_gate.is_some() && !subscription_request)
            .map(|gate| {
                let gate = Arc::clone(gate);
                Arc::new(move || gate.admit_handler()) as FinalHandlerAdmission
            });
        let response = match duplicate_response {
            Some(response) => Some(response),
            None => {
                Arc::clone(&server)
                    .dispatch_with_protocol_policy_owned_and_handler_admission(
                        policy,
                        &inbound,
                        request,
                        raw_params,
                        auth_receipt,
                        None,
                        Some(http_stream_generation),
                        cancellation.clone(),
                        Some(Arc::clone(&terminal_delivery)),
                        notification_sender,
                        handler_admission,
                    )
                    .await
            }
        };
        let mut canonical_after_stream_admission = false;
        if let (Some(outcome_gate), Some(rejection)) = (
            outcome_gate.as_ref(),
            response
                .as_ref()
                .and_then(canonical_http_error_status_response),
        ) {
            if outcome_gate.elect(ModernSseDispatchElection::Immediate(rejection)) {
                return;
            }
            if outcome_gate.stream_admitted() {
                canonical_after_stream_admission = true;
            } else {
                // An earlier failed election cannot safely commit a response
                // after its body has retired.
                return;
            }
        }
        if outcome_gate.is_none()
            && subscription_request
            && response
                .as_ref()
                .is_some_and(is_canonical_missing_required_client_capability_response)
            && stream_admitted.load(Ordering::Acquire)
        {
            // The typed in-process endpoint has no alternate HTTP
            // representation to elect, but after acknowledgement it has the
            // same one-terminal-response obligation as a live Stream body.
            canonical_after_stream_admission = true;
        }
        if let Some(deferred_notifications) = deferred_notifications {
            for notification in deferred_notifications.take_pending() {
                committed_notification_sender(notification);
            }
        }
        if notification_commit_failed.load(Ordering::Acquire) {
            terminal_delivery.mark_failed();
            if let Some(outcome_gate) = &outcome_gate {
                outcome_gate.elect(ModernSseDispatchElection::Failed);
            }
            return;
        }
        let mut terminal_commit_failed = false;
        if let Some(response) = response {
            let graceful_completion = final_subscription_completion_response(&response);
            let elected_terminal_response = graceful_completion || canonical_after_stream_admission;
            // The server-side graceful election cancels this request as its
            // dispatch wake, which claims the finalization race; its elected
            // terminal response is the sanctioned final frame and must still
            // flush. A canonical error substituted after `Stream` has the
            // same delivery contract. Every other response drops once
            // cancellation won.
            if cancellation.begin_finalization() || elected_terminal_response {
                let _terminal_commit = terminal_commit
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                if elected_terminal_response {
                    // This is deliberately before the queue commit: graceful
                    // shutdown waits for the writer to flush this terminal
                    // response, and a failed commit converts it to failed
                    // delivery rather than pretending it settled.
                    terminal_delivery.mark_completion_enqueued();
                }
                let sent = if elected_terminal_response {
                    // A server-owned shutdown may have cancelled the
                    // listener's root context. Its elected terminal response
                    // is the only final HTTP frame, so mask the commit while
                    // the peer still owns the body.
                    request_cx.masked(|| {
                        retry_http_sse_commit(
                            &request_cx,
                            &cancellation,
                            || response_sender.send_response(&request_cx, response.clone()),
                            retryable_http_sse_transport_error,
                        )
                    })
                } else {
                    retry_http_sse_commit(
                        &request_cx,
                        &cancellation,
                        || response_sender.send_response(&request_cx, response.clone()),
                        retryable_http_sse_transport_error,
                    )
                };
                if sent.is_err() {
                    // The terminal response has no error channel after the
                    // SSE body is admitted. Retire the body explicitly so a
                    // bounded `WouldBlock` does not leave it pending forever.
                    terminal_delivery.mark_failed();
                    cancellation.cancel();
                    terminal_commit_failed = true;
                }
            } else {
                // Peer cancel after Stream admission drops the JSON-RPC
                // result. Settle the HTTP receipt here so listener drain
                // does not wait for a complete that this path never sends.
                terminal_delivery.mark_failed();
                terminal_commit_failed = true;
            }
        }
        if let Some(outcome_gate) = &outcome_gate {
            outcome_gate.elect(if terminal_commit_failed {
                ModernSseDispatchElection::Failed
            } else {
                ModernSseDispatchElection::Stream
            });
        }
    })
    .map_err(|error| {
        DualEraHttpEndpointError::Transport(TransportError::Io(std::io::Error::other(format!(
            "modern HTTP request dispatch admission failed: {error}"
        ))))
    })
}

async fn send_modern_sse_stream(
    cx: &Cx,
    listener_shutdown: &HttpListenerShutdown,
    stream: AsyncTcpStream,
    server: Arc<Server>,
    live_session: &LiveModernHttpSession,
    modern_sessions: &LiveModernHttpSessionRegistry,
    http_stream_generation: u64,
    inbound: InboundRequestContext,
    request: JsonRpcRequest,
    raw_params: Option<Arc<str>>,
    auth_receipt: Option<AuthDispatchCustody>,
    response: DualEraHttpSseResponse,
) -> Result<(), ()> {
    let sender = response.sender();
    let ordinary_request = request.method != SUBSCRIPTIONS_LISTEN;
    let request_cancellation = sender.request_cancellation();
    let terminal_delivery = Arc::new(FinalSubscriptionTerminalDelivery::default());
    // Every modern SSE representation waits for this request-owned election.
    // A durable subscription elects `Stream` only after its dynamic middleware
    // and admission acknowledgement succeed; ordinary requests elect after
    // handler admission commits a notification or their final response is queued.
    let (outcome_gate, mut outcome_receiver) = ModernSseOutcomeGate::new();
    // H1 request input is complete before this request-owned response starts.
    // A clean peer write-half EOF is therefore ordinary request completion,
    // not cancellation of the still-owned response body. TCP cannot tell that
    // half-close from a full close through this read side alone; output writes
    // are the only definitive disconnect signal for this SSE response.
    let (_reader, mut writer) = stream.into_split();

    let dispatch = match spawn_modern_sse_dispatch(
        cx,
        Arc::clone(&server),
        http_stream_generation,
        inbound,
        request,
        raw_params,
        auth_receipt,
        sender,
        Arc::clone(&terminal_delivery),
        Some(Arc::clone(&outcome_gate)),
    ) {
        Ok(dispatch) => dispatch,
        Err(_) => return Err(()),
    };
    let dispatch = OwnedModernHttpDispatch {
        owner_generation: http_stream_generation,
        request_cancellation: request_cancellation.clone(),
        task: dispatch,
    };
    if let Err(dispatch) = live_session.register_modern_dispatch(dispatch) {
        server
            .final_subscriptions
            .cancel_modern_http_owner(dispatch.owner_generation);
        dispatch.request_cancellation.cancel();
        dispatch.task.abort();
        modern_sessions.retain_retired_dispatches(vec![dispatch.task]);
        return Err(());
    }

    let result = async {
        match await_modern_sse_dispatch_election(cx, &request_cancellation, &mut outcome_receiver)
            .await?
        {
            ModernSseDispatchElection::Stream => {}
            ModernSseDispatchElection::Immediate(response) => {
                return send_h1_bad_request_response(cx, listener_shutdown, &mut writer, &response)
                    .await;
            }
            ModernSseDispatchElection::Failed => return Err(()),
        }
        let response_head = sse_response_head(response.response())?;
        writer.write_all(&response_head).await.map_err(|_| ())?;
        writer.flush().await.map_err(|_| ())?;
        let mut last_frame_write = cx.now();
        loop {
            // A failed request-scoped progress/log/terminal commit retires
            // this body even when response finalization had already claimed
            // the request cancellation token.
            if terminal_delivery.is_settled() {
                return Err(());
            }
            match pop_sse_body_event(&response) {
                Ok(Some(event)) => {
                    let terminal_control = final_subscription_terminal_event(&event);
                    let terminal_response = final_subscription_terminal_response_event(&event);
                    let bytes = event.to_bytes().map_err(|_| ())?;
                    let prefix = format!("{:X}\r\n", bytes.len());
                    writer.write_all(prefix.as_bytes()).await.map_err(|_| ())?;
                    writer.write_all(&bytes).await.map_err(|_| ())?;
                    writer.write_all(b"\r\n").await.map_err(|_| ())?;
                    writer.flush().await.map_err(|_| ())?;
                    last_frame_write = cx.now();
                    if terminal_control {
                        terminal_delivery.mark_drained();
                    }
                    if terminal_response {
                        terminal_delivery.mark_completion_drained();
                    }
                    if terminal_delivery.is_settled() {
                        break;
                    }
                }
                Ok(None) if response.is_finished() => break,
                Ok(None)
                    if request_cancellation.is_cancel_requested()
                        && !terminal_delivery.is_committed() =>
                {
                    // Peer/session cancel with no graceful complete in flight.
                    // Stream election marks control not-required, so do not
                    // wait for a control frame that modern HTTP never writes.
                    // Fail the receipt now so two live as_proxy catalog+Tasks
                    // SSE POSTs do not burn the full drain budget.
                    terminal_delivery.mark_failed();
                    break;
                }
                Ok(None) => {
                    // A cancelled listener Cx must not park on its timer: two
                    // live catalog+Tasks writers would busy-loop or hang and
                    // starve the dispatch that still owes the elected complete.
                    if cx.checkpoint().is_err() {
                        if !terminal_delivery.is_settled() {
                            // The connection region is already cancelled, so
                            // dispatch cannot flush an unelected complete or
                            // a RequestCancelled that already left the body.
                            // Fail now instead of burning the drain budget.
                            terminal_delivery.mark_failed();
                            break;
                        }
                        asupersync::runtime::yield_now().await;
                    } else {
                        if ordinary_request
                            && cx.now().duration_since(last_frame_write) >= 2_000_000_000
                        {
                            // A quiet handler still needs an output write to
                            // observe a peer that has closed its response body.
                            // One inert comment line every two idle seconds
                            // detects that closure without treating a legal
                            // request write-half EOF as cancellation. No blank
                            // line is added: this consumes one caller keepalive
                            // line and cannot create an MCP event or reset an
                            // ordinary response's progress-based idle deadline.
                            // Subscriptions retain their separate long-lived
                            // activity and keepalive policies.
                            writer.write_all(b"2\r\n:\n\r\n").await.map_err(|_| ())?;
                            writer.flush().await.map_err(|_| ())?;
                            last_frame_write = cx.now();
                        }
                        asupersync::time::sleep(cx.now(), Duration::from_millis(1)).await;
                    }
                }
                Err(DualEraHttpEndpointError::Transport(TransportError::Closed))
                    if response.is_finished() =>
                {
                    break;
                }
                Err(_) => return Err(()),
            }
        }
        writer.write_all(b"0\r\n\r\n").await.map_err(|_| ())?;
        writer.flush().await.map_err(|_| ())
    }
    .await;

    if result.is_err() {
        terminal_delivery.mark_failed();
        modern_sessions
            .retain_retired_dispatches(live_session.cancel_modern_dispatch(http_stream_generation));
    } else if !terminal_delivery.is_settled() {
        // Writing the chunked trailer can succeed after the peer already
        // dropped. That must not leave a graceful-election receipt open for
        // the full HTTP_TERMINAL_DRAIN_TIMEOUT — two live SSE POSTs would
        // then blow the fixture teardown bound.
        terminal_delivery.mark_failed();
    }
    live_session.reap_modern_dispatches();
    result
}

fn next_modern_http_stream_generation() -> u64 {
    loop {
        let generation = NEXT_MODERN_HTTP_STREAM_GENERATION.fetch_add(1, Ordering::Relaxed);
        if generation != 0 {
            return generation;
        }
    }
}

fn next_live_modern_http_response_body_generation() -> u64 {
    loop {
        let generation =
            NEXT_LIVE_MODERN_HTTP_RESPONSE_BODY_GENERATION.fetch_add(1, Ordering::Relaxed);
        if generation != 0 {
            return generation;
        }
    }
}

fn http_endpoint_response_to_static(cx: &Cx, response: ServerHttpEndpointResponse) -> HttpResponse {
    match response {
        ServerHttpEndpointResponse::Immediate(response) => response,
        ServerHttpEndpointResponse::ModernSse(sse) => {
            let mut response = sse.response().clone();
            match sse.recv_event(cx).and_then(|event| {
                event
                    .to_bytes()
                    .map_err(DualEraHttpEndpointError::from)
                    .map_err(ServerHttpEndpointError::from_internal)
            }) {
                Ok(body) => response = response.with_body(body),
                Err(_) => response = HttpResponse::internal_error(),
            }
            response
        }
        #[cfg(feature = "legacy-2024-11-05")]
        ServerHttpEndpointResponse::LegacySse(_) => HttpResponse::internal_error(),
    }
}

#[cfg(feature = "legacy-2024-11-05")]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct IngressVerifiedLegacyResponse;

#[cfg(feature = "legacy-2024-11-05")]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LiveHttpLegacyDispatchMode {
    Blocking,
    BlockingPreclassifiedResponse(IngressVerifiedLegacyResponse),
    CallerOwnedAsync,
}

#[cfg(feature = "legacy-2024-11-05")]
struct HttpLegacyIngressAdmission {
    // Notifications have no correlated cancellation guard, but still carry
    // their authenticated decision across the session-ownership wait.
    _request_guard: Option<HttpLegacyRequestAdmissionGuard>,
    auth_receipt: AuthAdmissionReceipt,
}

#[cfg(feature = "legacy-2024-11-05")]
enum LiveHttpLegacyIngress {
    Dispatch {
        admission: Option<Box<HttpLegacyIngressAdmission>>,
        mode: LiveHttpLegacyDispatchMode,
    },
    Immediate(HttpResponse),
}

#[cfg(feature = "legacy-2024-11-05")]
fn admit_live_http_legacy_request(
    cx: &Cx,
    endpoint: &ServerHttpEndpoint,
    legacy_sessions: &LiveHttpSessionRegistry,
    request: &HttpRequest,
    transport_authorization: &TransportAuthorization,
) -> Result<LiveHttpLegacyIngress, HttpResponse> {
    if request.method != HttpMethod::Post
        || request.path != endpoint.server.http_config.legacy_message_path
    {
        return Ok(LiveHttpLegacyIngress::Dispatch {
            admission: None,
            mode: LiveHttpLegacyDispatchMode::Blocking,
        });
    }
    let Some(session_id) = request.query.get("session_id") else {
        return Err(HttpResponse::new(HttpStatus::NOT_FOUND));
    };
    let session = legacy_sessions
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .get(session_id)
        .cloned()
        .ok_or_else(|| HttpResponse::new(HttpStatus::NOT_FOUND))?;
    let admitted = admit_legacy_2024_http_post(
        request,
        &session.cancellation.legacy_message_path,
        &session.cancellation.http_session_id,
        session.cancellation.max_body_size,
    )?;
    let Legacy2024HttpPostEnvelope::ClientMessage(message) = admitted else {
        let Legacy2024HttpPostEnvelope::Response(response) = admitted else {
            unreachable!("legacy POST admission has exactly two envelope variants");
        };
        let auth_probe = JsonRpcRequest::new("legacy/sse", None, RequestId::Number(0));
        let receipt = session.cancellation.server.preauthenticate_http_request(
            cx,
            &auth_probe,
            transport_authorization,
        )?;
        if !session
            .cancellation
            .session_principal
            .verify_existing(receipt.fingerprint)
        {
            return Err(native_http_authentication_rejection());
        }
        // Route a correlated response on the connection reactor before it can
        // queue behind the blocking handler that emitted the reverse request.
        // An unmatched response must still enter the serialized fallback, but
        // that condvar wait belongs on the bounded bridge pool rather than the
        // caller-owned reactor; otherwise the peer cannot post cancellation.
        let disposition = session
            .cancellation
            .legacy_lifecycle
            .commit_if_live(|| {
                session
                    .legacy_pending_requests
                    .route_response_with_disposition(&response)
            })
            .ok_or_else(|| HttpResponse::new(HttpStatus::SERVICE_UNAVAILABLE))?;
        return if matches!(
            disposition,
            bidirectional::PendingResponseDisposition::Delivered
                | bidirectional::PendingResponseDisposition::RetiredGeneric
        ) {
            Ok(LiveHttpLegacyIngress::Immediate(HttpResponse::new(
                HttpStatus::ACCEPTED,
            )))
        } else {
            Ok(LiveHttpLegacyIngress::Dispatch {
                admission: None,
                mode: LiveHttpLegacyDispatchMode::BlockingPreclassifiedResponse(
                    IngressVerifiedLegacyResponse,
                ),
            })
        };
    };
    if message.id.is_none() && message.method == "notifications/cancelled" {
        return Ok(LiveHttpLegacyIngress::Immediate(
            session
                .cancellation
                .handle(cx, request)
                .unwrap_or_else(HttpResponse::bad_request),
        ));
    }
    let dispatch_mode = if endpoint
        .server
        .router
        .legacy_request_uses_transport_owned_async_dispatch(&message)
    {
        LiveHttpLegacyDispatchMode::CallerOwnedAsync
    } else {
        LiveHttpLegacyDispatchMode::Blocking
    };
    let receipt = session.cancellation.server.preauthenticate_http_request(
        cx,
        &message,
        transport_authorization,
    )?;
    let admission = session
        .cancellation
        .legacy_lifecycle
        .commit_if_live(|| {
            session.cancellation.admissions.admit(
                &message,
                &session.cancellation.session_principal,
                receipt.fingerprint,
            )
        })
        .ok_or_else(|| HttpResponse::new(HttpStatus::SERVICE_UNAVAILABLE))?
        .map_err(|()| HttpResponse::bad_request())?;
    Ok(LiveHttpLegacyIngress::Dispatch {
        admission: Some(Box::new(HttpLegacyIngressAdmission {
            _request_guard: admission,
            auth_receipt: receipt,
        })),
        mode: dispatch_mode,
    })
}

/// Re-decodes an already-admitted body to recover its request ID for an
/// admission error response.
///
/// Admission rejections after envelope decode are returned only once the
/// strict, bounded JSON-RPC request decode has succeeded. Re-decoding with the
/// same configured bound retains the admitted request ID without widening the
/// listener's parsing surface.
fn admitted_request_id(body: &[u8], max_body_size: usize) -> Option<RequestId> {
    let mut codec = Codec::new();
    codec.set_max_message_size(max_body_size);
    codec
        .decode_complete_message(body)
        .ok()
        .and_then(|message| match message {
            JsonRpcMessage::Request(request) => request.id,
            JsonRpcMessage::Response(_) => None,
        })
}

fn protocol_admission_error_response(
    body: &[u8],
    admission: fastmcp_protocol::RequestAdmissionError,
    max_body_size: usize,
) -> HttpResponse {
    let id = admitted_request_id(body, max_body_size);
    let (message, data) = match &admission {
        fastmcp_protocol::RequestAdmissionError::HeaderMismatch(error) => (
            http_admission::HEADER_MISMATCH_MESSAGE,
            error.canonical_error_data(),
        ),
        fastmcp_protocol::RequestAdmissionError::UnsupportedProtocolVersion(error) => (
            "Unsupported MCP protocol version",
            Some(error.canonical_error_data()),
        ),
    };
    let response = JsonRpcResponse::error(
        id,
        JsonRpcError {
            code: admission.jsonrpc_error_code().into(),
            message: message.to_owned(),
            data,
        },
    );
    HttpResponse::new(HttpStatus(admission.http_status())).with_json(&response)
}

fn http_endpoint_error_response(
    request: &HttpRequest,
    error: ServerHttpEndpointError,
    max_body_size: usize,
) -> HttpResponse {
    match error {
        ServerHttpEndpointError::Http(HttpError::ProtocolAdmission(admission)) => {
            protocol_admission_error_response(&request.body, admission, max_body_size)
        }
        _ => HttpResponse::bad_request(),
    }
}

async fn dispatch_modern_http_request(
    cx: &Cx,
    endpoint: &ServerHttpEndpoint,
    modern_sessions: &LiveModernHttpSessionRegistry,
    request: HttpRequest,
) -> HttpResponse {
    let transport_authorization = match transport_authorization_from_http_request(&request) {
        Ok(authorization) => authorization,
        Err(response) => return response,
    };
    dispatch_modern_http_request_with_cancellation_and_transport_authorization(
        cx,
        endpoint,
        modern_sessions,
        request,
        transport_authorization,
        None,
    )
    .await
}

async fn dispatch_modern_http_request_with_cancellation_and_transport_authorization(
    cx: &Cx,
    endpoint: &ServerHttpEndpoint,
    modern_sessions: &LiveModernHttpSessionRegistry,
    request: HttpRequest,
    transport_authorization: TransportAuthorization,
    request_cancellation: Option<McpRequestCancellation>,
) -> HttpResponse {
    let error_request = request.clone();
    if request.header("mcp-session-id").is_some() {
        return HttpResponse::bad_request();
    }
    modern_sessions.reap_retired_dispatches();
    let mut session = match endpoint.open_session(cx) {
        Ok(session) => session,
        Err(_) => return HttpResponse::internal_error(),
    };
    session
        .handle_with_modern_request_cancellation_and_transport_authorization_async(
            cx,
            request,
            transport_authorization,
            request_cancellation,
            false,
            None,
        )
        .await
        .map_err(ServerHttpEndpointError::from_internal)
        .map(|response| http_endpoint_response_to_static(cx, response))
        .unwrap_or_else(|error| {
            http_endpoint_error_response(
                &error_request,
                error,
                endpoint.server.http_config.handler_config.max_body_size,
            )
        })
}

/// Dispatches one ordinary modern JSON request while its connection owns the
/// cancellation authority. The request has already been fully decoded.
///
/// A clean write-half EOF is ordinary H1 request completion: the peer is
/// waiting to read this response. Unexpected extra bytes (pipelining into a
/// single-request connection) abandon the response body. Full close is
/// observed when the later response write fails, matching modern SSE.
async fn serve_modern_json_http_connection(
    cx: &Cx,
    stream: AsyncTcpStream,
    endpoint: Arc<ServerHttpEndpoint>,
    modern_sessions: LiveModernHttpSessionRegistry,
    listener_shutdown: HttpListenerShutdown,
    request: HttpRequest,
    transport_authorization: TransportAuthorization,
) {
    let (mut peer_reader, writer) = stream.into_split();
    let request_cancellation = McpRequestCancellation::new();
    let peer_cancellation = request_cancellation.clone();
    let mut peer_watch = match cx.spawn(move |peer_cx| async move {
        let mut probe = [0_u8; 1];
        match peer_reader.read(&mut probe).await {
            Ok(0) => {}
            Ok(_) => {
                peer_cancellation.cancel();
            }
            Err(_) if !peer_cx.is_cancel_requested() => {
                peer_cancellation.cancel();
            }
            Err(_) => {}
        }
    }) {
        Ok(peer_watch) => peer_watch,
        Err(_) => return,
    };

    // Keep the dispatch under a joined connection child, but let it yield.
    // spawn_blocking can run inline without a caller-owned blocking pool;
    // blocking there would prevent the owned handler's children from running.
    let request_endpoint = Arc::clone(&endpoint);
    let request_modern_sessions = Arc::clone(&modern_sessions);
    let dispatch_cancellation = request_cancellation.clone();
    let mut dispatch = match cx.spawn(move |request_cx| async move {
        dispatch_modern_http_request_with_cancellation_and_transport_authorization(
            &request_cx,
            &request_endpoint,
            &request_modern_sessions,
            request,
            transport_authorization,
            Some(dispatch_cancellation),
        )
        .await
    }) {
        Ok(dispatch) => dispatch,
        Err(_) => {
            request_cancellation.cancel();
            peer_watch.abort();
            let _ = peer_watch.join(cx).await;
            return;
        }
    };
    let response = match dispatch.join(cx).await {
        Ok(response) => response,
        Err(_) => HttpResponse::internal_error(),
    };
    peer_watch.abort();
    let _ = peer_watch.join(cx).await;

    let mut response_framed = Framed::new(writer, native_http1_codec(&endpoint));
    let _ = send_h1_response(cx, &listener_shutdown, &mut response_framed, response).await;
}

#[cfg(feature = "legacy-2024-11-05")]
fn dispatch_http_request(
    cx: &Cx,
    endpoint: &ServerHttpEndpoint,
    legacy_sessions: &LiveHttpSessionRegistry,
    modern_sessions: &LiveModernHttpSessionRegistry,
    request: HttpRequest,
    legacy_admission: Option<Box<HttpLegacyIngressAdmission>>,
    legacy_dispatch_mode: LiveHttpLegacyDispatchMode,
) -> HttpResponse {
    // Drive the dispatch on the caller's runtime handles, as modern owned
    // dispatch does, and not inside `fastmcp_core::block_on`. The live arm
    // runs this on a blocking-pool thread, and the synchronous tool it reaches
    // runs inline here. A handler that bridges `ctx.sample` with `block_on`
    // would otherwise nest a second bridge on this thread, which panics, so
    // the reverse request was never sent and the peer waited on SSE for it
    // (bd-f2ndd, bd-6rfrg).
    poll_on_cx(
        cx,
        dispatch_http_request_async(
            cx,
            endpoint,
            legacy_sessions,
            modern_sessions,
            request,
            legacy_admission,
            legacy_dispatch_mode,
        ),
    )
}

#[cfg(feature = "legacy-2024-11-05")]
async fn dispatch_http_request_async(
    cx: &Cx,
    endpoint: &ServerHttpEndpoint,
    legacy_sessions: &LiveHttpSessionRegistry,
    modern_sessions: &LiveModernHttpSessionRegistry,
    request: HttpRequest,
    legacy_admission: Option<Box<HttpLegacyIngressAdmission>>,
    legacy_dispatch_mode: LiveHttpLegacyDispatchMode,
) -> HttpResponse {
    let is_legacy_message = request.method == HttpMethod::Post
        && request.path == endpoint.server.http_config.legacy_message_path;
    if is_legacy_message {
        let Some(session_id) = request.query.get("session_id") else {
            return HttpResponse::new(HttpStatus::NOT_FOUND);
        };
        let session = legacy_sessions
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .get(session_id)
            .cloned();
        let Some(session) = session else {
            return HttpResponse::new(HttpStatus::NOT_FOUND);
        };
        let admitted = match admit_legacy_2024_http_post(
            &request,
            &session.cancellation.legacy_message_path,
            &session.cancellation.http_session_id,
            session.cancellation.max_body_size,
        ) {
            Ok(admitted) => admitted,
            Err(response) => return response,
        };
        if matches!(
            &admitted,
            Legacy2024HttpPostEnvelope::ClientMessage(notification)
                if notification.id.is_none()
                    && notification.method == "notifications/cancelled"
        ) {
            return session
                .cancellation
                .handle(cx, &request)
                .unwrap_or_else(HttpResponse::bad_request);
        }
        // The connection creates this authority before queueing the blocking
        // dispatch. Direct embedding callers create it here instead. In both
        // cases it remains live through the serialized adapter/session mutex,
        // active guard, and response finalization.
        let admission = match legacy_admission {
            Some(admission) => Some(admission),
            None => match &admitted {
                Legacy2024HttpPostEnvelope::ClientMessage(message) => {
                    let transport_authorization =
                        match transport_authorization_from_http_request(&request) {
                            Ok(authorization) => authorization,
                            Err(response) => return response,
                        };
                    let receipt = match session.cancellation.server.preauthenticate_http_request(
                        cx,
                        message,
                        &transport_authorization,
                    ) {
                        Ok(receipt) => receipt,
                        Err(response) => return response,
                    };
                    let Some(admission) =
                        session.cancellation.legacy_lifecycle.commit_if_live(|| {
                            session.cancellation.admissions.admit(
                                message,
                                &session.cancellation.session_principal,
                                receipt.fingerprint,
                            )
                        })
                    else {
                        return HttpResponse::new(HttpStatus::SERVICE_UNAVAILABLE);
                    };
                    match admission {
                        Ok(admission) => Some(Box::new(HttpLegacyIngressAdmission {
                            _request_guard: admission,
                            auth_receipt: receipt,
                        })),
                        Err(()) => return HttpResponse::bad_request(),
                    }
                }
                Legacy2024HttpPostEnvelope::Response(_) => None,
            },
        };
        let request_cancellation = match &admitted {
            Legacy2024HttpPostEnvelope::ClientMessage(message) => {
                message.id.as_ref().and_then(|request_id| {
                    session
                        .cancellation
                        .admissions
                        .admitted_request_cancellation(request_id)
                })
            }
            Legacy2024HttpPostEnvelope::Response(_) => None,
        };
        let session_take = if matches!(
            legacy_dispatch_mode,
            LiveHttpLegacyDispatchMode::CallerOwnedAsync
        ) {
            take_live_http_session_async(cx, &session, request_cancellation.as_ref()).await
        } else {
            take_live_http_session(cx, &session, request_cancellation.as_ref())
        };
        let mut owned = match session_take {
            LiveHttpSessionTake::Acquired(owned) => *owned,
            LiveHttpSessionTake::Cancelled => {
                return HttpResponse::new(HttpStatus::ACCEPTED);
            }
            LiveHttpSessionTake::Unavailable => {
                return HttpResponse::new(HttpStatus::SERVICE_UNAVAILABLE);
            }
        };
        let response = if let LiveHttpLegacyDispatchMode::BlockingPreclassifiedResponse(verified) =
            legacy_dispatch_mode
        {
            owned
                .handle_preclassified_unmatched_legacy_response(cx, request, verified)
                .await
        } else {
            owned
                .handle_with_modern_request_cancellation_async(
                    cx,
                    request,
                    None,
                    false,
                    admission
                        .as_ref()
                        .map(|admission| admission.auth_receipt.clone()),
                )
                .await
                .map_err(ServerHttpEndpointError::from_internal)
        }
        .map_err(|_| HttpResponse::bad_request());
        let closing_dispatches = restore_live_http_session(&session, owned);
        for mut dispatch in closing_dispatches {
            let _ = dispatch.join(cx).await;
        }
        return response.map_or_else(
            |response| response,
            |response| http_endpoint_response_to_static(cx, response),
        );
    }

    if request.method == HttpMethod::Post
        && request.path == endpoint.server.http_config.handler_config.base_path
    {
        return dispatch_modern_http_request(cx, endpoint, modern_sessions, request).await;
    }

    let mut session = match endpoint.open_session(cx) {
        Ok(session) => session,
        Err(_) => return HttpResponse::internal_error(),
    };
    let error_request = request.clone();
    session
        .handle_async(cx, request)
        .await
        .map(|response| http_endpoint_response_to_static(cx, response))
        .unwrap_or_else(|error| {
            http_endpoint_error_response(
                &error_request,
                error,
                endpoint.server.http_config.handler_config.max_body_size,
            )
        })
}

#[cfg(feature = "legacy-2024-11-05")]
async fn serve_http_connection(
    cx: &Cx,
    stream: AsyncTcpStream,
    endpoint: Arc<ServerHttpEndpoint>,
    legacy_sessions: LiveHttpSessionRegistry,
    modern_sessions: LiveModernHttpSessionRegistry,
    listener_shutdown: HttpListenerShutdown,
) {
    let http_config = &endpoint.server.http_config.handler_config;
    let mut framed = Framed::new(stream, native_http1_codec(&endpoint));
    #[cfg(test)]
    lib_unit_tests::record_live_http_connection_read_wait();
    let read_timeout = endpoint.server.http_config.request_read_timeout;
    let Some(request) =
        next_native_http1_request(cx, &listener_shutdown, &mut framed, read_timeout).await
    else {
        return;
    };
    let request = match request {
        Ok(request) => request,
        Err(_) => {
            let _ = send_h1_response(
                cx,
                &listener_shutdown,
                &mut framed,
                HttpResponse::bad_request(),
            )
            .await;
            return;
        }
    };
    if !framed.read_buffer().is_empty() {
        let _ = send_h1_response(
            cx,
            &listener_shutdown,
            &mut framed,
            HttpResponse::bad_request(),
        )
        .await;
        return;
    }
    if serve_oauth_h1_request(cx, &listener_shutdown, &mut framed, &endpoint, &request).await {
        return;
    }
    let transport_authorization = match h1_transport_authorization(&request) {
        Ok(authorization) => authorization,
        Err(response) => {
            let _ = send_h1_response(cx, &listener_shutdown, &mut framed, response).await;
            return;
        }
    };
    let raw_path = request
        .uri
        .split_once('?')
        .map_or(request.uri.as_str(), |(path, _)| path);
    if matches!(&request.method, Http1Method::Post) && raw_path == http_config.base_path.as_str() {
        // Preserve wire-field cardinality for strict admission: conversion to
        // `HttpRequest` intentionally merges list-valued Accept fields.
        let headers = request
            .headers
            .iter()
            .map(|(name, value)| (name.clone(), value.clone()))
            .collect::<Vec<_>>();
        if let Err(response) =
            admit_modern_http_post(http_config, "POST", raw_path, &headers, &request.body)
        {
            let _ = send_h1_response(cx, &listener_shutdown, &mut framed, response).await;
            return;
        }
    }
    let request = match h1_request_to_transport(&request) {
        Ok(request) => request,
        Err(response) => {
            let _ = send_h1_response(cx, &listener_shutdown, &mut framed, response).await;
            return;
        }
    };

    let is_legacy_sse = request.method == HttpMethod::Get
        && request.path == endpoint.server.http_config.legacy_sse_path;
    let is_modern_sse = request.method == HttpMethod::Post
        && request.path == endpoint.server.http_config.handler_config.base_path
        && http_request_accepts_sse(&request);
    if is_modern_sse {
        if request.header("mcp-session-id").is_some() {
            let _ = send_h1_response(
                cx,
                &listener_shutdown,
                &mut framed,
                HttpResponse::bad_request(),
            )
            .await;
            return;
        }
        let mut session = match endpoint.open_session(cx) {
            Ok(session) => session,
            Err(_) => {
                let _ = send_h1_response(
                    cx,
                    &listener_shutdown,
                    &mut framed,
                    HttpResponse::internal_error(),
                )
                .await;
                return;
            }
        };
        let http_parameter_headers = http_admission::http_parameter_headers(&request.headers);
        let response = {
            match session
                .begin_modern_sse(cx, request.clone(), transport_authorization.clone(), None)
                .await
            {
                Ok(Ok((request, response, raw_params, auth_receipt))) => Ok(Ok((
                    InboundRequestContext::with_modern_connection_and_transport_authorization(
                        cx.clone(),
                        request_id_to_u64(request.id.as_ref()),
                        InboundRequestTransport::Http,
                        &session.modern_connection,
                        transport_authorization.clone(),
                    )
                    .with_http_parameter_headers(http_parameter_headers),
                    request,
                    raw_params,
                    auth_receipt,
                    response,
                ))),
                Ok(Err(response)) => Ok(Err(response)),
                Err(error) => Err(ServerHttpEndpointError::from_internal(error)),
            }
        };
        let live_session = Arc::new(LiveModernHttpSession::new(session));
        match response {
            Ok(Ok((inbound, request, raw_params, auth_receipt, response))) => {
                let response_body_generation = next_live_modern_http_response_body_generation();
                let live_session = match modern_sessions
                    .register_response_body(response_body_generation, Arc::clone(&live_session))
                {
                    Ok(()) => live_session,
                    Err(live_session) => {
                        close_detached_modern_http_session(&modern_sessions, live_session);
                        let _ = send_h1_response(
                            cx,
                            &listener_shutdown,
                            &mut framed,
                            HttpResponse::new(HttpStatus::SERVICE_UNAVAILABLE),
                        )
                        .await;
                        return;
                    }
                };
                let stream = framed.into_inner();
                let _ = send_modern_sse_stream(
                    cx,
                    &listener_shutdown,
                    stream,
                    Arc::clone(&endpoint.server),
                    &live_session,
                    &modern_sessions,
                    next_modern_http_stream_generation(),
                    inbound,
                    request,
                    raw_params,
                    Some(auth_receipt),
                    response,
                )
                .await;
                if let Some(live_session) =
                    modern_sessions.take_response_body(response_body_generation)
                {
                    close_detached_modern_http_session(&modern_sessions, live_session);
                }
                return;
            }
            Ok(Err(response)) => {
                let _ = send_h1_response(
                    cx,
                    &listener_shutdown,
                    &mut framed,
                    http_endpoint_response_to_static(cx, *response),
                )
                .await;
                return;
            }
            Err(error) => {
                let _ = send_h1_response(
                    cx,
                    &listener_shutdown,
                    &mut framed,
                    http_endpoint_error_response(&request, error, http_config.max_body_size),
                )
                .await;
                return;
            }
        }
    }
    if request.method == HttpMethod::Post
        && request.path == endpoint.server.http_config.handler_config.base_path
    {
        let stream = framed.into_inner();
        serve_modern_json_http_connection(
            cx,
            stream,
            endpoint,
            modern_sessions,
            listener_shutdown.clone(),
            request,
            transport_authorization,
        )
        .await;
        return;
    }
    if !is_legacy_sse {
        // Admit correlated legacy work before dispatch. The captured guard
        // keeps this authority live while ordinary requests use synchronous
        // isolation. Matching reverse responses are consumed during ingress;
        // cancellation is handled there too. Handlers frozen as async remain
        // on the caller runtime, with a yielding session-acquisition path.
        let ingress = match admit_live_http_legacy_request(
            cx,
            &endpoint,
            &legacy_sessions,
            &request,
            &transport_authorization,
        ) {
            Ok(admission) => admission,
            Err(response) => {
                let _ = send_h1_response(cx, &listener_shutdown, &mut framed, response).await;
                return;
            }
        };
        let (legacy_admission, legacy_dispatch_mode) = match ingress {
            LiveHttpLegacyIngress::Dispatch { admission, mode } => (admission, mode),
            LiveHttpLegacyIngress::Immediate(response) => {
                let _ = send_h1_response(cx, &listener_shutdown, &mut framed, response).await;
                return;
            }
        };
        if request.method == HttpMethod::Post
            && request.path == endpoint.server.http_config.legacy_message_path
        {
            if matches!(
                legacy_dispatch_mode,
                LiveHttpLegacyDispatchMode::CallerOwnedAsync
            ) {
                let response = dispatch_http_request_async(
                    cx,
                    &endpoint,
                    &legacy_sessions,
                    &modern_sessions,
                    request,
                    legacy_admission,
                    legacy_dispatch_mode,
                )
                .await;
                let _ = send_h1_response(cx, &listener_shutdown, &mut framed, response).await;
                return;
            }
            let dispatch_endpoint = Arc::clone(&endpoint);
            let dispatch_legacy_sessions = Arc::clone(&legacy_sessions);
            let dispatch_modern_sessions = Arc::clone(&modern_sessions);
            let Some(blocking_dispatch_permit) = try_reserve_blocking_dispatch() else {
                let _ = send_h1_response(
                    cx,
                    &listener_shutdown,
                    &mut framed,
                    HttpResponse::new(HttpStatus::SERVICE_UNAVAILABLE),
                )
                .await;
                return;
            };
            // Keep the direct pool handle inside a real request-region child.
            // This avoids `Cx::spawn_blocking`'s documented inline fallback,
            // while the outer TaskHandle still binds listener quiescence to
            // the pool task's actual terminal state.
            let panic_session_id = request.query.get("session_id").cloned();
            let response = match run_live_http_legacy_blocking_dispatch(
                cx,
                &legacy_sessions,
                panic_session_id,
                blocking_dispatch_permit,
                move |blocking_cx| {
                    dispatch_http_request(
                        &blocking_cx,
                        &dispatch_endpoint,
                        &dispatch_legacy_sessions,
                        &dispatch_modern_sessions,
                        request,
                        legacy_admission,
                        legacy_dispatch_mode,
                    )
                },
            )
            .await
            {
                Ok(response) => response,
                Err(()) => HttpResponse::new(HttpStatus::SERVICE_UNAVAILABLE),
            };
            let _ = send_h1_response(cx, &listener_shutdown, &mut framed, response).await;
            return;
        }
        let response = dispatch_http_request_async(
            cx,
            &endpoint,
            &legacy_sessions,
            &modern_sessions,
            request,
            legacy_admission,
            LiveHttpLegacyDispatchMode::Blocking,
        )
        .await;
        let _ = send_h1_response(cx, &listener_shutdown, &mut framed, response).await;
        return;
    }

    let mut session = match endpoint.open_session_for_legacy_sse(cx, &request) {
        Ok(session) => session,
        Err(_) => {
            let _ = send_h1_response(
                cx,
                &listener_shutdown,
                &mut framed,
                HttpResponse::internal_error(),
            )
            .await;
            return;
        }
    };
    let session_id = session.legacy_session_id().to_owned();
    let response = match session.handle_async(cx, request).await {
        Ok(ServerHttpEndpointResponse::LegacySse(response)) => response,
        Ok(response) => {
            let _ = send_h1_response(
                cx,
                &listener_shutdown,
                &mut framed,
                http_endpoint_response_to_static(cx, response),
            )
            .await;
            return;
        }
        Err(_) => {
            let _ = send_h1_response(
                cx,
                &listener_shutdown,
                &mut framed,
                HttpResponse::bad_request(),
            )
            .await;
            return;
        }
    };
    let session = Arc::new(LiveHttpSession {
        cancellation: session.cancellation_control(),
        legacy_pending_requests: Arc::clone(&session.legacy_pending_requests),
        session: Mutex::new(Some(session)),
        session_available: Condvar::new(),
        closing: AtomicBool::new(false),
    });
    legacy_sessions
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .insert(session_id.clone(), Arc::clone(&session));
    let stream = framed.into_inner();
    let _ = send_legacy_sse_stream(cx, stream, response).await;
    // Peer close must revoke active exact-2024 requests before acquiring the
    // serialized session slot below. Mark the detached shell first so an
    // in-flight handler closes its owned session instead of restoring it
    // after this listener has removed the public admission route.
    session.closing.store(true, Ordering::Release);
    session.session_available.notify_all();
    session.cancellation.cancel_all_admitted_requests();
    let removed = legacy_sessions
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .remove(&session_id);
    if let Some(session) = removed {
        let dispatches = session
            .session
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .as_mut()
            .map(ServerHttpSession::begin_close)
            .unwrap_or_default();
        for mut task in dispatches {
            let _ = task.join(cx).await;
        }
    }
}

/// Production HTTP/1 connection path for a feature-off server.
///
/// This is intentionally separate from the dual-era listener: the only
/// request route admitted here is final Streamable HTTP. Historical `/sse`
/// and `/messages` traffic reaches `ServerHttpSession::handle_async` as a 404 and
/// can neither allocate a legacy session nor pin a legacy era.
#[cfg(not(feature = "legacy-2024-11-05"))]
async fn serve_modern_http_connection(
    cx: &Cx,
    stream: AsyncTcpStream,
    endpoint: Arc<ServerHttpEndpoint>,
    modern_sessions: LiveModernHttpSessionRegistry,
    listener_shutdown: HttpListenerShutdown,
) {
    let http_config = &endpoint.server.http_config.handler_config;
    let mut framed = Framed::new(stream, native_http1_codec(&endpoint));
    #[cfg(test)]
    lib_unit_tests::record_live_http_connection_read_wait();
    let read_timeout = endpoint.server.http_config.request_read_timeout;
    let Some(request) =
        next_native_http1_request(cx, &listener_shutdown, &mut framed, read_timeout).await
    else {
        return;
    };
    let request = match request {
        Ok(request) => request,
        Err(_) => {
            let _ = send_h1_response(
                cx,
                &listener_shutdown,
                &mut framed,
                HttpResponse::bad_request(),
            )
            .await;
            return;
        }
    };
    if !framed.read_buffer().is_empty() {
        let _ = send_h1_response(
            cx,
            &listener_shutdown,
            &mut framed,
            HttpResponse::bad_request(),
        )
        .await;
        return;
    }
    if serve_oauth_h1_request(cx, &listener_shutdown, &mut framed, &endpoint, &request).await {
        return;
    }
    let transport_authorization = match h1_transport_authorization(&request) {
        Ok(authorization) => authorization,
        Err(response) => {
            let _ = send_h1_response(cx, &listener_shutdown, &mut framed, response).await;
            return;
        }
    };
    let raw_path = request
        .uri
        .split_once('?')
        .map_or(request.uri.as_str(), |(path, _)| path);
    if matches!(&request.method, Http1Method::Post) && raw_path == http_config.base_path.as_str() {
        let headers = request
            .headers
            .iter()
            .map(|(name, value)| (name.clone(), value.clone()))
            .collect::<Vec<_>>();
        if let Err(response) =
            admit_modern_http_post(http_config, "POST", raw_path, &headers, &request.body)
        {
            let _ = send_h1_response(cx, &listener_shutdown, &mut framed, response).await;
            return;
        }
    }
    let request = match h1_request_to_transport(&request) {
        Ok(request) => request,
        Err(response) => {
            let _ = send_h1_response(cx, &listener_shutdown, &mut framed, response).await;
            return;
        }
    };
    let is_modern_sse = request.method == HttpMethod::Post
        && request.path == endpoint.server.http_config.handler_config.base_path
        && http_request_accepts_sse(&request);
    if is_modern_sse {
        if request.header("mcp-session-id").is_some() {
            let _ = send_h1_response(
                cx,
                &listener_shutdown,
                &mut framed,
                HttpResponse::bad_request(),
            )
            .await;
            return;
        }
        let mut session = match endpoint.open_session(cx) {
            Ok(session) => session,
            Err(_) => {
                let _ = send_h1_response(
                    cx,
                    &listener_shutdown,
                    &mut framed,
                    HttpResponse::internal_error(),
                )
                .await;
                return;
            }
        };
        let http_parameter_headers = http_admission::http_parameter_headers(&request.headers);
        let response = {
            match session
                .begin_modern_sse(cx, request.clone(), transport_authorization.clone(), None)
                .await
            {
                Ok(Ok((request, response, raw_params, auth_receipt))) => Ok(Ok((
                    InboundRequestContext::with_modern_connection_and_transport_authorization(
                        cx.clone(),
                        request_id_to_u64(request.id.as_ref()),
                        InboundRequestTransport::Http,
                        &session.modern_connection,
                        transport_authorization.clone(),
                    )
                    .with_http_parameter_headers(http_parameter_headers),
                    request,
                    raw_params,
                    auth_receipt,
                    response,
                ))),
                Ok(Err(response)) => Ok(Err(response)),
                Err(error) => Err(ServerHttpEndpointError::from_internal(error)),
            }
        };
        let live_session = Arc::new(LiveModernHttpSession::new(session));
        match response {
            Ok(Ok((inbound, request, raw_params, auth_receipt, response))) => {
                let response_body_generation = next_live_modern_http_response_body_generation();
                let live_session = match modern_sessions
                    .register_response_body(response_body_generation, Arc::clone(&live_session))
                {
                    Ok(()) => live_session,
                    Err(live_session) => {
                        close_detached_modern_http_session(&modern_sessions, live_session);
                        let _ = send_h1_response(
                            cx,
                            &listener_shutdown,
                            &mut framed,
                            HttpResponse::new(HttpStatus::SERVICE_UNAVAILABLE),
                        )
                        .await;
                        return;
                    }
                };
                let stream = framed.into_inner();
                let _ = send_modern_sse_stream(
                    cx,
                    &listener_shutdown,
                    stream,
                    Arc::clone(&endpoint.server),
                    &live_session,
                    &modern_sessions,
                    next_modern_http_stream_generation(),
                    inbound,
                    request,
                    raw_params,
                    Some(auth_receipt),
                    response,
                )
                .await;
                if let Some(live_session) =
                    modern_sessions.take_response_body(response_body_generation)
                {
                    close_detached_modern_http_session(&modern_sessions, live_session);
                }
                return;
            }
            Ok(Err(response)) => {
                let _ = send_h1_response(
                    cx,
                    &listener_shutdown,
                    &mut framed,
                    http_endpoint_response_to_static(cx, *response),
                )
                .await;
                return;
            }
            Err(error) => {
                let _ = send_h1_response(
                    cx,
                    &listener_shutdown,
                    &mut framed,
                    http_endpoint_error_response(&request, error, http_config.max_body_size),
                )
                .await;
                return;
            }
        }
    }

    if request.method == HttpMethod::Post
        && request.path == endpoint.server.http_config.handler_config.base_path
    {
        let stream = framed.into_inner();
        serve_modern_json_http_connection(
            cx,
            stream,
            endpoint,
            modern_sessions,
            listener_shutdown.clone(),
            request,
            transport_authorization,
        )
        .await;
        return;
    }

    let response = if request.method == HttpMethod::Post
        && request.path == endpoint.server.http_config.handler_config.base_path
    {
        dispatch_modern_http_request(cx, &endpoint, &modern_sessions, request).await
    } else {
        let mut session = match endpoint.open_session(cx) {
            Ok(session) => session,
            Err(_) => {
                let _ = send_h1_response(
                    cx,
                    &listener_shutdown,
                    &mut framed,
                    HttpResponse::internal_error(),
                )
                .await;
                return;
            }
        };
        let error_request = request.clone();
        session
            .handle_async(cx, request)
            .await
            .map(|response| http_endpoint_response_to_static(cx, response))
            .unwrap_or_else(|error| {
                http_endpoint_error_response(&error_request, error, http_config.max_body_size)
            })
    };
    let _ = send_h1_response(cx, &listener_shutdown, &mut framed, response).await;
}

/// An MCP server instance.
///
/// Servers are built using [`ServerBuilder`] and can run on various
/// transports (stdio, SSE, WebSocket).
pub struct Server {
    info: ServerInfo,
    title: Option<String>,
    description: Option<String>,
    website_url: Option<String>,
    icons: Vec<fastmcp_protocol::common_types::RawIcon>,
    capabilities: ServerCapabilities,
    router: Arc<Router>,
    instructions: Option<String>,
    /// Server-owned request ceiling in seconds (0 = no additional ceiling).
    request_timeout_secs: u64,
    /// Runtime statistics collector (None = disabled).
    stats: Option<ServerStats>,
    /// Whether to mask internal error details in responses.
    mask_error_details: bool,
    /// Logging configuration.
    logging: LoggingConfig,
    /// Console configuration for rich output.
    console_config: ConsoleConfig,
    /// Server-owned console resolved from `console_config`.
    console: FastMcpConsole,
    /// Lifecycle hooks (wrapped in Option so they can be taken once).
    lifespan: Mutex<Option<LifespanHooks>>,
    /// Optional authentication provider.
    auth_provider: Option<Arc<dyn AuthProvider>>,
    /// Registered middleware.
    middleware: Arc<Vec<Box<dyn crate::Middleware>>>,
    /// Active requests by connection/session identity and JSON-RPC request ID.
    active_requests: Arc<Mutex<HashMap<ActiveRequestKey, ActiveRequest>>>,
    /// Test-only legacy task manager retained while the task subsystem is
    /// rebuilt. It is absent from production library builds.
    #[cfg(all(test, feature = "tasks"))]
    task_manager: Option<SharedTaskManager>,
    /// Per-connection ceiling for pending server-to-client requests.
    #[cfg(feature = "legacy-2024-11-05")]
    max_bidirectional_requests_per_connection: usize,
    /// Immutable protocol-era admission policy selected by [`ServerBuilder`].
    protocol_policy: ProtocolPolicy,
    #[cfg(feature = "legacy-2024-11-05")]
    legacy_application_tool_content: bool,
    /// Immutable configuration for the live dual-era HTTP endpoint.
    http_config: HttpServerConfig,
    /// Optional OAuth-only public routes admitted before MCP transport conversion.
    oauth_http_routes: Option<OAuthHttpRoutes>,
    /// Frozen modern-only extension descriptors, handlers, and resolver.
    extension_runtime: Option<Arc<ServerExtensionRuntime>>,
    /// Application-owned final Tasks state retained for the caller's supervisor.
    #[cfg(feature = "tasks")]
    final_task_runtime: Option<FinalTaskRuntime>,
    /// Application service entered and settled by the owning serve lifetime.
    #[cfg(feature = "tasks")]
    task_service_host: Option<tasks::TaskServiceHost>,
    /// One route-bound upstream final Tasks relay, distinct from local durable
    /// task state because its identifiers and lifecycle remain upstream-owned.
    #[cfg(all(feature = "proxy", feature = "tasks"))]
    final_task_relay: Option<Arc<ProxyFinalTaskRelay>>,
    /// Request-owned final subscription streams shared by stdio and HTTP.
    final_subscriptions: Arc<FinalSubscriptionRegistry>,
}

impl Server {
    /// Returns the local subscription/notification delivery state for unit
    /// tests that prove a rejected request produced no local side effect.
    #[cfg(all(test, feature = "proxy", feature = "tasks"))]
    pub(crate) fn final_subscription_snapshot_for_test(&self) -> serde_json::Value {
        self.final_subscriptions.snapshot_for_test()
    }

    /// Creates a new server builder.
    #[must_use]
    #[allow(clippy::new_ret_no_self)]
    pub fn new(name: impl Into<String>, version: impl Into<String>) -> ServerBuilder {
        ServerBuilder::new(name, version)
    }

    /// Returns the server info.
    #[must_use]
    pub fn info(&self) -> &ServerInfo {
        &self.info
    }

    #[cfg(feature = "legacy-2024-11-05")]
    fn new_pending_requests_for_connection(&self) -> Arc<bidirectional::PendingRequests> {
        Arc::new(
            bidirectional::PendingRequests::with_max_in_flight(
                self.max_bidirectional_requests_per_connection,
            )
            .expect("ServerBuilder validates the bidirectional request limit"),
        )
    }

    /// Returns the server capabilities.
    #[must_use]
    pub fn capabilities(&self) -> &ServerCapabilities {
        &self.capabilities
    }

    /// Returns the immutable protocol-era policy selected by the builder.
    #[must_use]
    pub const fn protocol_policy(&self) -> ProtocolPolicy {
        self.protocol_policy
    }

    /// Returns the installed frozen extension handler registry, if configured.
    #[must_use]
    pub fn extension_handler_registry(&self) -> Option<&ExtensionHandlerRegistry> {
        self.extension_runtime
            .as_deref()
            .map(|runtime| &runtime.handlers)
    }

    /// Returns the canonical descriptor receipt for the installed registry.
    #[must_use]
    pub fn extension_registry_receipt(&self) -> Option<&ExtensionRegistryReceipt> {
        self.extension_handler_registry()
            .and_then(|registry| registry.descriptor_registry().receipt())
    }

    /// Returns final Tasks state when the application configured the official extension.
    ///
    /// The returned state machine creates no runtime and no detached task. A
    /// caller-owned structured supervisor drives worker transitions through
    /// this handle while the server routes only the negotiated wire methods.
    #[must_use]
    #[cfg(feature = "tasks")]
    pub fn final_task_runtime(&self) -> Option<&FinalTaskRuntime> {
        self.final_task_runtime.as_ref()
    }

    #[cfg(feature = "tasks")]
    async fn start_hosted_task_service(
        &self,
        cx: &Cx,
    ) -> McpResult<Option<tasks::HostedTaskService>> {
        match self.task_service_host.as_ref() {
            Some(host) => host.start_ready(cx).await.map(Some),
            None => Ok(None),
        }
    }

    #[cfg(feature = "tasks")]
    fn start_hosted_task_service_blocking(
        &self,
        cx: &Cx,
        owns_server_lifecycle: bool,
    ) -> McpResult<Option<tasks::HostedTaskService>> {
        match self
            .task_service_host
            .as_ref()
            .filter(|_| owns_server_lifecycle)
        {
            Some(host) => host.start_ready_blocking(cx).map(Some),
            None => Ok(None),
        }
    }

    #[cfg(feature = "tasks")]
    async fn settle_hosted_task_service(
        hosted: Option<tasks::HostedTaskService>,
        cx: &Cx,
    ) -> McpResult<()> {
        match hosted {
            Some(hosted) => hosted.settle(cx).await,
            None => Ok(()),
        }
    }

    #[cfg(feature = "tasks")]
    fn settle_hosted_task_service_blocking(
        hosted: Option<tasks::HostedTaskService>,
    ) -> McpResult<()> {
        match hosted {
            Some(hosted) => hosted.settle_blocking(),
            None => Ok(()),
        }
    }

    /// Publishes one final catalog or resource change notification to every
    /// live `subscriptions/listen` request whose accepted filter matches it.
    ///
    /// The server tags each delivered notification with that request's exact
    /// subscription ID. Request-scoped notifications such as progress and
    /// messages are rejected rather than being broadcast.
    ///
    /// Each listener retains at most 64 events and 256 KiB of encoded event
    /// data, including its active callback. Concurrent and reentrant publishes
    /// queue in admission order behind that callback; their return count means
    /// queue admission. Overflow cancels and unregisters only that listener.
    /// The caller that starts a drain invokes callbacks synchronously, so an
    /// application callback must still bound its own work.
    ///
    /// # Errors
    ///
    /// Returns `InvalidParams` when `notification` is not a final
    /// subscription event, a capacity error for oversized application event
    /// data, or an internal error when it cannot be encoded.
    pub fn publish_subscription_notification(
        &self,
        notification: ServerNotification,
    ) -> McpResult<usize> {
        self.final_subscriptions.publish(notification)
    }

    /// Opens one in-process `subscriptions/listen` stream.
    ///
    /// The returned handle keeps the stream registered. Dropping it
    /// unregisters the listener. Events are delivered through
    /// `notification_sender`; this method does not block on stream lifetime.
    /// Wire transports should keep using their owned listen dispatch.
    /// This is a trusted embedding control without caller authentication;
    /// never expose it as a request adapter for protected Tasks.
    ///
    /// # Errors
    ///
    /// Returns `InvalidRequest` when `subscription_id` is not a valid JSON-RPC
    /// id, `InvalidParams` when the filter cannot be admitted, or a capacity
    /// error when the server already holds the maximum number of streams.
    pub fn open_subscription_listen(
        &self,
        subscription_id: RequestId,
        notifications: SubscriptionFilter,
        notification_sender: NotificationSender,
    ) -> McpResult<SubscriptionListenHandle> {
        #[cfg(feature = "tasks")]
        let accept_tasks = task_subscription_ids(&notifications)
            .ok()
            .flatten()
            .is_some();
        #[cfg(not(feature = "tasks"))]
        let accept_tasks = false;
        let lease = self.final_subscriptions.open(
            subscription_id,
            notifications,
            accept_tasks,
            None,
            McpRequestCancellation::new(),
            None,
            notification_sender,
        )?;
        Ok(SubscriptionListenHandle { _lease: lease })
    }

    /// Publishes one typed final Tasks status notification to matching streams.
    ///
    /// Only subscriptions whose acknowledged `taskIds` set contains the
    /// notification's exact opaque task identifier receive it. The server adds
    /// the request's subscription ID without changing Task state.
    /// This embedding publisher has no authenticated event custody and reaches
    /// only unprotected subscriptions. Authenticated task transitions publish
    /// internally with their committed principal.
    #[cfg(feature = "tasks")]
    pub fn publish_task_status_notification(
        &self,
        notification: FinalTaskStatusNotification,
    ) -> McpResult<usize> {
        self.final_subscriptions.publish_task(notification)
    }

    /// Begins graceful termination for all live final subscription streams.
    ///
    /// Stdio `subscriptions/listen` streams receive one correlated final
    /// `notifications/cancelled` control. Modern HTTP streams instead end
    /// gracefully with their correlated terminal response; client
    /// cancellation is response-body closure, never an MCP cancellation
    /// notification.
    #[must_use]
    pub fn terminate_subscription_streams(&self) -> usize {
        self.final_subscriptions.terminate()
    }

    /// Shutdown's subscription teardown. A listen still inside its
    /// acknowledgement (or an event) callback when the server wins its election
    /// is completed by that callback's owner, and only if its request is not
    /// cancelled yet. So this waits, bounded, for those owners before the
    /// caller's generic `cancel_active_requests`, which a peer cancel and a
    /// shutdown cancel look identical to (bd-81cct).
    fn terminate_subscription_streams_for_shutdown(&self) -> usize {
        let receipt = self.final_subscriptions.terminate_with_receipt();
        if !receipt.wait_for_pending_elections(SHUTDOWN_CLEANUP_TIMEOUT) {
            error!(
                target: targets::SESSION,
                "Final subscription callbacks did not finish their graceful completion before shutdown cancellation"
            );
        }
        receipt.terminated
    }

    /// Negotiates currently advertised client extension settings against this server.
    ///
    /// The resulting set is bound to this server's frozen descriptor receipt and
    /// can only admit modern extension calls through
    /// [`Self::dispatch_negotiated_extension`]. Exact MCP 2024-11-05 uses no
    /// extension registry path.
    pub fn negotiate_extensions(
        &self,
        client: &ClientExtensionDiscovery,
    ) -> Result<fastmcp_protocol::extensions::NegotiatedExtensionSet, ServerExtensionNegotiationError>
    {
        let runtime = self
            .extension_runtime
            .as_deref()
            .ok_or(ServerExtensionNegotiationError::NotConfigured)?;
        runtime.negotiate(client)
    }

    #[cfg(feature = "legacy-2024-11-05")]
    fn legacy_2024_server_config(&self) -> Legacy2024ServerConfig {
        Legacy2024ServerConfig {
            capabilities: Legacy2024ServerCapabilities {
                logging: self.capabilities.logging.as_ref().map(|_| BTreeMap::new()),
                prompts: self.capabilities.prompts.as_ref().map(|capability| {
                    Legacy2024ListChangedCapability {
                        list_changed: capability.list_changed,
                        ..Legacy2024ListChangedCapability::default()
                    }
                }),
                resources: self.capabilities.resources.as_ref().map(|capability| {
                    Legacy2024ResourcesCapability {
                        subscribe: capability.subscribe,
                        list_changed: capability.list_changed,
                        ..Legacy2024ResourcesCapability::default()
                    }
                }),
                tools: self.capabilities.tools.as_ref().map(|capability| {
                    Legacy2024ListChangedCapability {
                        list_changed: capability.list_changed,
                        ..Legacy2024ListChangedCapability::default()
                    }
                }),
                extensions: self
                    .capabilities
                    .completions
                    .as_ref()
                    .map(|_| {
                        BTreeMap::from([(
                            "completions".to_owned(),
                            serde_json::Value::Object(serde_json::Map::new()),
                        )])
                    })
                    .unwrap_or_default(),
                ..Legacy2024ServerCapabilities::default()
            },
            server_info: Legacy2024ServerInfo {
                name: self.info.name.clone(),
                version: self.info.version.clone(),
            },
            instructions: self.instructions.clone(),
        }
    }

    #[cfg(feature = "legacy-2024-11-05")]
    fn install_legacy_2024_adapter<H: Legacy2024Handler>(
        &self,
        binding: LegacyPeerBinding,
        handler: H,
    ) -> Result<Legacy2024ServerAdapter<H>, Legacy2024AdapterError> {
        Legacy2024ServerAdapter::install(binding, self.legacy_2024_server_config(), handler).map(
            |adapter| adapter.with_application_tool_content(self.legacy_application_tool_content),
        )
    }

    /// Returns the final discovery result for this constructed server.
    ///
    /// Discovery is explicitly unauthenticated at this server boundary, just
    /// like the rest of the modern stateless surface: transports authenticate
    /// raw credentials before constructing [`InboundRequestContext`], while
    /// this method receives only already-sanitized request facts. The result
    /// derives from the immutable router catalog and cannot grant access to a
    /// method or notification path that is not installed.
    pub fn server_discovery(&self) -> McpResult<ServerDiscoverResult> {
        let instructions = match self.instructions.as_deref() {
            Some(value) if value.len() > MAX_SERVER_INSTRUCTIONS_BYTES => {
                return Err(McpError::internal_error(
                    "Server discovery instructions exceed the configured limit",
                ));
            }
            Some(value) => Some(ServerInstructions::new(value.to_owned()).map_err(|_| {
                McpError::internal_error("Server discovery instructions are invalid")
            })?),
            None => None,
        };
        let registry = self.router.server_discovery_behavior_registry();
        let extension_capabilities = self.extension_runtime.as_deref().map_or_else(
            BTreeMap::new,
            ServerExtensionRuntime::discovery_capabilities,
        );
        let capabilities =
            ServerDiscoverCapabilities::from_registry(&registry, extension_capabilities).map_err(
                |_| McpError::internal_error("Server discovery capabilities are invalid"),
            )?;

        let discovery = ServerDiscoverResult::new(
            capabilities,
            self.info.clone(),
            instructions,
            DiscoveryCacheHints::private_ttl_ms(u64::from(DISCOVERY_CACHE_MAX_AGE_SECONDS) * 1_000),
        );
        let Some(mut implementation) = fastmcp_protocol::common_types::Implementation::try_new(
            self.info.name.clone(),
            self.info.version.clone(),
        )
        .ok() else {
            return Ok(discovery);
        };
        implementation.title = self.title.clone();
        implementation.description = self.description.clone();
        if let Some(website_url) = self.website_url.as_deref()
            && let Ok(uri) = fastmcp_protocol::common_types::AbsoluteUri::parse(website_url)
        {
            implementation.website_url = Some(uri);
        }
        implementation.icons = self.icons.clone();
        if implementation.title.is_some()
            || implementation.description.is_some()
            || implementation.website_url.is_some()
            || !implementation.icons.is_empty()
        {
            return Ok(discovery.with_implementation(implementation));
        }
        Ok(discovery)
    }

    /// Lists all registered tools.
    #[must_use]
    pub fn tools(&self) -> Vec<Tool> {
        self.router.tools()
    }

    /// Lists all registered resources.
    #[must_use]
    pub fn resources(&self) -> Vec<Resource> {
        self.router.resources()
    }

    /// Lists all registered resource templates.
    #[must_use]
    pub fn resource_templates(&self) -> Vec<ResourceTemplate> {
        self.router.resource_templates()
    }

    /// Lists all registered prompts.
    #[must_use]
    pub fn prompts(&self) -> Vec<Prompt> {
        self.router.prompts()
    }

    fn registered_extension_handler_id(&self, method: &str) -> McpResult<Option<&ExtensionId>> {
        let Some(runtime) = self.extension_runtime.as_deref() else {
            return Ok(None);
        };

        for id in runtime.server_discovery.extensions.keys() {
            match runtime.handlers.lookup(id, method) {
                Ok(_) => return Ok(Some(id)),
                Err(ExtensionHandlerLookupError::HandlerNotFound(_)) => {}
                Err(ExtensionHandlerLookupError::RegistryNotFrozen) => {
                    return Err(McpError::internal_error(
                        "server extension handlers were not frozen",
                    ));
                }
            }
        }
        Ok(None)
    }

    fn invoke_negotiated_extension(
        &self,
        request_ctx: &McpContext,
        negotiated: &fastmcp_protocol::extensions::NegotiatedExtensionSet,
        extension_id: &ExtensionId,
        request: &JsonRpcRequest,
    ) -> McpResult<serde_json::Value> {
        // Keep the exact metadata available for modern admission and
        // negotiation, but never expose the transport-owned version marker to
        // extension handlers.
        let mut request = request.clone();
        remove_modern_protocol_metadata(&mut request);
        let runtime = self
            .extension_runtime
            .as_deref()
            .ok_or_else(|| McpError::method_not_found(&request.method))?;
        runtime
            .handlers
            .invoke(
                request_ctx,
                negotiated,
                ProtocolEra::Modern2026,
                extension_id,
                &request,
            )
            .map_err(|error| match error {
                ExtensionHandlerInvocationError::Handler(error) => error,
                ExtensionHandlerInvocationError::RegistryNotFrozen => {
                    McpError::internal_error("server extension handlers were not frozen")
                }
                ExtensionHandlerInvocationError::Protocol(_)
                | ExtensionHandlerInvocationError::HandlerNotFound(_)
                | ExtensionHandlerInvocationError::RequestEnvelopeRequired(_) => {
                    McpError::invalid_params("Extension request is not admitted")
                }
            })
    }

    /// Dispatches an already-negotiated modern extension request.
    ///
    /// This public seam preserves the caller's request-owned context and only
    /// invokes a handler when its descriptor is active in the supplied frozen
    /// current-exchange capability set.
    pub fn dispatch_negotiated_extension(
        &self,
        request_ctx: &McpContext,
        negotiated: &fastmcp_protocol::extensions::NegotiatedExtensionSet,
        request: &JsonRpcRequest,
    ) -> McpResult<serde_json::Value> {
        require_exact_modern_extension_metadata(request)?;
        let Some(extension_id) = self.registered_extension_handler_id(&request.method)? else {
            return Err(McpError::method_not_found(&request.method));
        };
        if negotiated.active(extension_id).is_none() {
            return Err(McpError::invalid_params(
                "Extension request is not admitted",
            ));
        }
        self.invoke_negotiated_extension(request_ctx, negotiated, extension_id, request)
    }

    /// Dispatches a negotiated extension on the caller's runtime, including
    /// handlers that suspend for upstream I/O. The synchronous dispatch API
    /// remains suitable only for synchronous extension handlers.
    pub async fn dispatch_negotiated_extension_async(
        &self,
        request_ctx: &McpContext,
        negotiated: &fastmcp_protocol::extensions::NegotiatedExtensionSet,
        request: &JsonRpcRequest,
    ) -> McpResult<serde_json::Value> {
        require_exact_modern_extension_metadata(request)?;
        let Some(extension_id) = self.registered_extension_handler_id(&request.method)? else {
            return Err(McpError::method_not_found(&request.method));
        };
        if negotiated.active(extension_id).is_none() {
            return Err(McpError::invalid_params(
                "Extension request is not admitted",
            ));
        }
        let mut request = request.clone();
        remove_modern_protocol_metadata(&mut request);
        let runtime = self
            .extension_runtime
            .as_deref()
            .ok_or_else(|| McpError::method_not_found(&request.method))?;
        runtime
            .handlers
            .invoke_async(
                request_ctx,
                negotiated,
                ProtocolEra::Modern2026,
                extension_id,
                &request,
            )
            .await
            .map_err(|error| match error {
                ExtensionHandlerInvocationError::Handler(error) => error,
                ExtensionHandlerInvocationError::RegistryNotFrozen => {
                    McpError::internal_error("server extension handlers were not frozen")
                }
                ExtensionHandlerInvocationError::Protocol(_)
                | ExtensionHandlerInvocationError::HandlerNotFound(_)
                | ExtensionHandlerInvocationError::RequestEnvelopeRequired(_) => {
                    McpError::invalid_params("Extension request is not admitted")
                }
            })
    }

    async fn dispatch_extension_fallback_async(
        &self,
        request_ctx: &McpContext,
        request: &JsonRpcRequest,
    ) -> McpResult<serde_json::Value> {
        require_exact_modern_extension_metadata(request)?;
        if self
            .registered_extension_handler_id(&request.method)?
            .is_none()
        {
            return Err(McpError::method_not_found(&request.method));
        }
        let client = final_client_extension_discovery(request)?;
        let negotiated = self
            .negotiate_extensions(&client)
            .map_err(|_| McpError::invalid_params("Extension request negotiation was rejected"))?;
        self.dispatch_negotiated_extension_async(request_ctx, &negotiated, request)
            .await
    }

    fn dispatch_extension_fallback(
        &self,
        request_ctx: &McpContext,
        request: &JsonRpcRequest,
    ) -> McpResult<serde_json::Value> {
        // Extension fallback is a modern-only escape hatch after the frozen
        // core router rejects an unknown method.  Do not let a request merely
        // shaped like an extension call reach either negotiation or an
        // extension handler: admission requires the exact final-era marker
        // carried by the current request.
        require_exact_modern_extension_metadata(request)?;
        let Some(extension_id) = self.registered_extension_handler_id(&request.method)? else {
            return Err(McpError::method_not_found(&request.method));
        };
        let client = final_client_extension_discovery(request)?;
        let negotiated = self
            .negotiate_extensions(&client)
            .map_err(|_| McpError::invalid_params("Extension request negotiation was rejected"))?;
        self.invoke_negotiated_extension(request_ctx, &negotiated, extension_id, request)
    }

    fn maybe_dispatch_extension_fallback(
        &self,
        request_ctx: &McpContext,
        request: &JsonRpcRequest,
        result: McpResult<serde_json::Value>,
    ) -> McpResult<serde_json::Value> {
        match result {
            Err(error)
                if error.code == McpErrorCode::MethodNotFound
                    && modern_protocol_version(request) == Some(MODERN_PROTOCOL_VERSION) =>
            {
                match self.registered_extension_handler_id(&request.method) {
                    Ok(Some(_)) => self.dispatch_extension_fallback(request_ctx, request),
                    Ok(None) => Err(error),
                    Err(lookup) => Err(lookup),
                }
            }
            other => other,
        }
    }

    /// Returns the test-only legacy task manager, if configured.
    #[cfg(all(test, feature = "tasks"))]
    #[must_use]
    pub(crate) fn task_manager(&self) -> Option<&SharedTaskManager> {
        self.task_manager.as_ref()
    }

    /// Consumes the server and returns its router.
    ///
    /// This is used for mounting one server's components into another.
    ///
    #[must_use]
    pub fn into_router(self) -> Router {
        Arc::into_inner(self.router)
            .expect("the server is the sole strong owner of its router outside dispatch")
    }

    /// Returns the capabilities this server provides.
    ///
    /// This is useful when determining what components a server has
    /// before mounting.
    #[must_use]
    pub fn has_tools(&self) -> bool {
        self.capabilities.tools.is_some()
    }

    /// Returns whether this server has resources.
    #[must_use]
    pub fn has_resources(&self) -> bool {
        self.capabilities.resources.is_some()
    }

    /// Returns whether this server has prompts.
    #[must_use]
    pub fn has_prompts(&self) -> bool {
        self.capabilities.prompts.is_some()
    }

    /// Returns a point-in-time snapshot of server statistics.
    ///
    /// Returns `None` if statistics collection is disabled.
    #[must_use]
    pub fn stats(&self) -> Option<StatsSnapshot> {
        self.stats.as_ref().map(ServerStats::snapshot)
    }

    /// Returns the raw statistics collector.
    ///
    /// Useful for advanced scenarios where you need direct access.
    /// Returns `None` if statistics collection is disabled.
    #[must_use]
    pub fn stats_collector(&self) -> Option<&ServerStats> {
        self.stats.as_ref()
    }

    /// Renders a stats panel to stderr, if stats are enabled.
    pub fn display_stats(&self) {
        let Some(stats) = self.stats.as_ref() else {
            return;
        };

        let snapshot = stats.snapshot();
        let renderer =
            fastmcp_console::stats::StatsRenderer::new(self.console_config.resolve_context());
        renderer.render_panel(&snapshot, &self.console);
    }

    fn configured_traffic_renderer(&self) -> Option<RequestResponseRenderer> {
        let show_bodies = match self.console_config.traffic_verbosity {
            TrafficVerbosity::None => return None,
            TrafficVerbosity::Summary => false,
            TrafficVerbosity::Full => true,
        };
        let mut renderer = RequestResponseRenderer::new(self.console_config.resolve_context());
        renderer.truncate_at = self.console_config.truncate_at;
        renderer.max_json_depth = self.console_config.max_json_depth;
        renderer.show_params = show_bodies;
        renderer.show_result = show_bodies;
        Some(renderer)
    }

    /// Returns the console configuration.
    #[must_use]
    pub fn console_config(&self) -> &ConsoleConfig {
        &self.console_config
    }

    /// Renders the startup banner based on console configuration.
    fn render_startup_banner(&self, transport: &str) {
        let render = || {
            let mut banner = StartupBanner::new(&self.info.name, &self.info.version)
                .tools(self.router.tools_count())
                .resources(self.router.resources_count())
                .prompts(self.router.prompts_count())
                .transport(transport)
                .show_capabilities(self.console_config.show_capabilities);

            if let Some(desc) = self.instructions.as_deref().filter(|d| !d.is_empty()) {
                banner = banner.description(desc);
            }

            // Apply banner style from config
            match self.console_config.banner_style {
                BannerStyle::Full => banner.render(&self.console),
                BannerStyle::Compact => {
                    banner.no_logo().render(&self.console);
                }
                BannerStyle::Minimal => banner.minimal().render(&self.console),
                BannerStyle::None => {} // Already checked show_banner, but be safe
            }
        };

        if std::panic::catch_unwind(std::panic::AssertUnwindSafe(render)).is_err() {
            self.console
                .print_plain("Warning: startup banner rendering failed");
        }
    }

    /// Initializes rich logging based on server configuration.
    ///
    /// This should be called early in the startup sequence, before any
    /// log output is generated. If initialization fails (e.g., logger
    /// already set), a warning is printed to stderr.
    fn init_rich_logging(&self) {
        let result = RichLoggerBuilder::new()
            .level_filter(self.logging.level)
            .with_timestamps(self.logging.timestamps)
            .with_targets(self.logging.targets)
            .with_file_line(self.logging.file_line)
            .with_max_width(Some(self.console_config.truncate_at))
            .with_context(self.console_config.resolve_context())
            .init();

        if result.is_err() {
            // Logger already initialized (likely by user code), not an error
            self.console
                .print_plain("Note: Rich logging not initialized (logger already set)");
        }
    }

    /// Processes one modern request through the final dispatch surface.
    ///
    /// The transport owns raw headers and retains a native authorization field
    /// only in crate-private inbound custody. Each call creates a fresh request
    /// authority, authenticates before extension middleware, and delegates only
    /// to the router's final dispatch surface. It neither reads nor mutates a
    /// legacy [`Session`]. A transport that supplies a connection-bound
    /// [`InboundRequestContext`] also carries retained-continuation authority.
    /// Durable connections contribute their exact MRTR partition; ephemeral
    /// HTTP contributes an eligibility partition that the router replaces with
    /// its stateless domain.
    ///
    /// Requests that require connection-local lifecycle state remain available
    /// exclusively through the legacy adapter. Modern list results still come
    /// from the immutable router catalog and never depend on previous request
    /// data.
    #[must_use]
    pub async fn dispatch_stateless(
        &self,
        inbound: &InboundRequestContext,
        request: &JsonRpcRequest,
    ) -> Option<JsonRpcResponse> {
        self.dispatch_stateless_with_cancellation(inbound, request, None, None, None, None)
            .await
    }

    async fn dispatch_stateless_with_cancellation(
        &self,
        inbound: &InboundRequestContext,
        request: &JsonRpcRequest,
        request_cancellation: Option<McpRequestCancellation>,
        raw_params: Option<&str>,
        auth_receipt: Option<&AuthDispatchCustody>,
        websocket_connection_generation: Option<u64>,
    ) -> Option<JsonRpcResponse> {
        let method = request.method.clone();
        let response_id = request.id.clone();
        let is_notification = response_id.is_none();
        let started_at = Instant::now();

        let response_for_error = |error: McpError| {
            response_id.clone().map(|id| {
                let masked = mask_peer_error(error, self.mask_error_details);
                JsonRpcResponse::error(
                    Some(id),
                    JsonRpcError {
                        code: masked.code.into(),
                        message: masked.message,
                        data: masked.data,
                    },
                )
            })
        };

        if request.validate().is_err() {
            if let Some(stats) = &self.stats {
                stats.record_request(&method, started_at.elapsed(), false);
            }
            return response_for_error(McpError::invalid_request("Invalid JSON-RPC request"));
        }
        if !is_notification && is_notification_only_method(&method) {
            if let Some(stats) = &self.stats {
                stats.record_request(&method, started_at.elapsed(), false);
            }
            return response_for_error(McpError::invalid_request(
                "MCP notification method must not carry a request id",
            ));
        }
        if admit_final_client_notification_ingress(request).is_err() {
            return None;
        }
        if is_notification && is_request_only_method(&method) {
            if let Some(stats) = &self.stats {
                stats.record_request(&method, started_at.elapsed(), false);
            }
            return None;
        }
        if inbound.request_id() != request_id_to_u64(response_id.as_ref()) {
            if let Some(stats) = &self.stats {
                stats.record_request(&method, started_at.elapsed(), false);
            }
            return response_for_error(McpError::invalid_request(
                "Inbound request identity does not match the JSON-RPC request id",
            ));
        }

        let request_ctx = match request_cancellation.as_ref() {
            Some(cancellation) => inbound
                .request_context()
                .with_request_cancellation(cancellation.clone()),
            None => inbound.request_context(),
        };
        let request_ctx = self
            .attach_request_scoped_component_access(self.with_final_catalog_publisher(request_ctx));
        let budget = self.create_request_budget(request_ctx.cx());
        if let Some(error) = Self::request_budget_error(request_ctx.cx(), budget) {
            if let Some(stats) = &self.stats {
                stats.record_request(&method, started_at.elapsed(), false);
            }
            return response_for_error(error);
        }
        let Some((request_ctx, _request_lease_guard)) = request_ctx
            .with_budget_ceiling(budget)
            .begin_request_scope()
        else {
            if let Some(stats) = &self.stats {
                stats.record_request(&method, started_at.elapsed(), false);
            }
            return response_for_error(McpError::internal_error(
                "request scope could not be established",
            ));
        };

        // The value the raw sidecar was admitted with; `request` is shadowed
        // below by a metadata-stripped copy.
        let admitted_params = request.params.as_ref();
        let mut admission_request = request.clone();
        if let Err(error) = self.authenticate_modern_request(
            &request_ctx,
            inbound,
            &mut admission_request,
            auth_receipt,
            websocket_connection_generation,
        ) {
            if let Some(stats) = &self.stats {
                stats.record_request(&method, started_at.elapsed(), false);
            }
            return response_for_error(error);
        }

        let final_core_request = match decode_final_core_request_for_middleware(&admission_request)
        {
            Ok(request) => request,
            Err(error) => {
                if let Some(stats) = &self.stats {
                    stats.record_request(&method, started_at.elapsed(), false);
                }
                return response_for_error(error);
            }
        };
        let request_ctx = match admitted_final_client_capability_info(final_core_request.as_ref()) {
            Ok(Some(capabilities)) => request_ctx.with_client_capabilities(capabilities),
            Ok(None) => request_ctx,
            Err(error) => {
                if let Some(stats) = &self.stats {
                    stats.record_request(&method, started_at.elapsed(), false);
                }
                return response_for_error(error);
            }
        };
        let request_ctx = match admitted_final_client_implementation(final_core_request.as_ref()) {
            Ok(Some(identity)) => request_ctx.with_client_implementation(identity),
            Ok(None) => request_ctx,
            Err(error) => {
                if let Some(stats) = &self.stats {
                    stats.record_request(&method, started_at.elapsed(), false);
                }
                return response_for_error(error);
            }
        };

        // The protocol-version marker is part of typed modern admission. Once
        // that admission has completed, keep the marker out of application
        // middleware and handler parameter decoding just as stdio does.
        let mut request = admission_request.clone();
        remove_modern_protocol_metadata(&mut request);

        let mut entered_middleware: Vec<&dyn crate::Middleware> = Vec::new();
        let result: McpResult<serde_json::Value> = async {
            for middleware in self.middleware.iter() {
                Self::enforce_request_context(&request_ctx)?;
                entered_middleware.push(middleware.as_ref());
                match catch_extension_unwind(|| middleware.on_request(&request_ctx, &request)) {
                    Ok(Ok(MiddlewareDecision::Continue)) => {}
                    Ok(Ok(MiddlewareDecision::Respond(value))) => {
                        if final_core_request.is_some()
                            && !middleware_may_complete_final_core_from_cache(
                                &request_ctx,
                                middleware.as_ref(),
                                &value,
                            )
                        {
                            return Err(McpError::internal_error(
                                "middleware cannot short-circuit a final core response",
                            ));
                        }
                        return Ok(value);
                    }
                    Ok(Err(error)) => return Err(error),
                    Err(_payload) => return Err(extension_panic_error("middleware_on_request")),
                }
            }
            if request.method == SERVER_DISCOVER_METHOD {
                let params = admission_request
                    .params
                    .clone()
                    .unwrap_or_else(|| serde_json::json!({}));
                serde_json::from_value::<ServerDiscoverRequest>(params)
                    .map_err(|error| McpError::invalid_params(error.to_string()))?;
                serde_json::to_value(self.server_discovery()?).map_err(McpError::from)
            } else if request.method == SUBSCRIPTIONS_LISTEN {
                Err(McpError::invalid_request(
                    "subscriptions/listen is a long-lived stream; use Server::open_subscription_listen or an owned transport dispatch",
                ))
            } else {
                let continuation_cancellation =
                    inbound.mrtr_continuation_cancellation().unwrap_or_default();
                match self
                    .router
                    .dispatch_stateless_with_continuation_cancellation_and_raw_params(
                        &request_ctx,
                        &admission_request,
                        retained_raw_params(
                            raw_params,
                            admitted_params,
                            admission_request.params.as_ref(),
                        ),
                        &continuation_cancellation,
                    )
                    .await
                {
                    Err(error) if error.code == McpErrorCode::MethodNotFound => {
                        self.dispatch_extension_fallback(&request_ctx, &admission_request)
                    }
                    result => result,
                }
            }
        }
        .await;
        let result = match result {
            Ok(value) => {
                let metadata_seal = final_core_middleware_metadata_seal(
                    final_core_request.as_ref(),
                    &request,
                    &value,
                );
                metadata_seal
                    .and_then(|metadata_seal| {
                        self.apply_middleware_response(
                            &entered_middleware,
                            &request_ctx,
                            &request,
                            value,
                        )
                        .and_then(|value| {
                            validate_final_core_middleware_response(
                                final_core_request.as_ref(),
                                &request,
                                value,
                            )
                        })
                        .and_then(|value| {
                            validate_final_core_middleware_metadata_seal(
                                metadata_seal.as_ref(),
                                final_core_request.as_ref(),
                                &request,
                                &value,
                            )?;
                            Ok(value)
                        })
                    })
                    .map_err(|error| {
                        self.apply_middleware_error(
                            &entered_middleware,
                            &request_ctx,
                            &request,
                            error,
                        )
                    })
            }
            Err(error) => {
                Err(self.apply_middleware_error(&entered_middleware, &request_ctx, &request, error))
            }
        };
        let result = Self::request_context_error(&request_ctx).map_or(result, Err);

        let succeeded = result.is_ok();
        if let Some(stats) = &self.stats {
            stats.record_request(&method, started_at.elapsed(), succeeded);
        }
        if is_notification {
            if let Err(error) = result {
                error!(
                    target: targets::HANDLER,
                    "Stateless notification failed; method_key={:016x}; code={:?}",
                    stable_hash_request_id(&method),
                    error.code
                );
            }
            return None;
        }

        // A listen stream terminates through its request-owned cancellation
        // authority.  For both a peer-close and server-initiated teardown,
        // the stream has no usable response channel after that terminal
        // signal; emitting an error response would create a second terminal
        // outcome.  Other request methods retain ordinary cancellation
        // responses.
        if request.method == SUBSCRIPTIONS_LISTEN
            && request_cancellation
                .as_ref()
                .is_some_and(McpRequestCancellation::is_cancel_requested)
        {
            return None;
        }

        let response_id = response_id.expect("non-notification requests have an id");
        Some(match result {
            Ok(value) => JsonRpcResponse::success(response_id, value),
            Err(error) => {
                let masked = mask_peer_error(error, self.mask_error_details);
                JsonRpcResponse::error(
                    Some(response_id),
                    JsonRpcError {
                        code: masked.code.into(),
                        message: masked.message,
                        data: masked.data,
                    },
                )
            }
        })
    }

    async fn dispatch_stateless_owned_with_cancellation(
        self: Arc<Self>,
        inbound: &InboundRequestContext,
        mut request: JsonRpcRequest,
        raw_params: Option<Arc<str>>,
        auth_receipt: Option<AuthDispatchCustody>,
        websocket_connection_generation: Option<u64>,
        modern_http_owner: Option<u64>,
        request_cancellation: McpRequestCancellation,
        terminal_delivery: Option<Arc<FinalSubscriptionTerminalDelivery>>,
        notification_sender: NotificationSender,
        handler_admission: Option<FinalHandlerAdmission>,
    ) -> Option<JsonRpcResponse> {
        // The value the raw sidecar was admitted with, before authentication
        // may strip credentials from this request.
        let admitted_params = raw_params.as_ref().and_then(|_| request.params.clone());
        let method = request.method.clone();
        let response_id = request.id.clone();
        let is_notification = response_id.is_none();
        let started_at = Instant::now();
        let response_for_error = |error: McpError| {
            response_id.clone().map(|id| {
                let masked = mask_peer_error(error, self.mask_error_details);
                JsonRpcResponse::error(
                    Some(id),
                    JsonRpcError {
                        code: masked.code.into(),
                        message: masked.message,
                        data: masked.data,
                    },
                )
            })
        };
        if request.validate().is_err() {
            return response_for_error(McpError::invalid_request("Invalid JSON-RPC request"));
        }
        if !is_notification && is_notification_only_method(&method) {
            return response_for_error(McpError::invalid_request(
                "MCP notification method must not carry a request id",
            ));
        }
        if admit_final_client_notification_ingress(&request).is_err() {
            return None;
        }
        if is_notification && is_request_only_method(&method) {
            return None;
        }
        if inbound.request_id() != request_id_to_u64(response_id.as_ref()) {
            return response_for_error(McpError::invalid_request(
                "Inbound request identity does not match the JSON-RPC request id",
            ));
        }
        let request_ctx = self.attach_request_scoped_component_access(
            self.with_final_catalog_publisher(
                inbound
                    .request_context()
                    .with_request_cancellation(request_cancellation.clone()),
            ),
        );
        let budget = self.create_owned_modern_request_budget(request_ctx.cx(), &method);
        if let Some(error) = Self::request_budget_error(request_ctx.cx(), budget) {
            return response_for_error(error);
        }
        let Some((mut request_ctx, _request_lease_guard)) = request_ctx
            .with_budget_ceiling(budget)
            .begin_request_scope()
        else {
            return response_for_error(McpError::internal_error(
                "request scope could not be established",
            ));
        };
        if let Err(error) = self.authenticate_modern_request(
            &request_ctx,
            inbound,
            &mut request,
            auth_receipt.as_ref(),
            websocket_connection_generation,
        ) {
            return response_for_error(error);
        }

        let final_core_request = match decode_final_core_request_for_middleware(&request) {
            Ok(request) => request,
            Err(error) => return response_for_error(error),
        };
        match admitted_final_client_capability_info(final_core_request.as_ref()) {
            Ok(Some(capabilities)) => {
                request_ctx = request_ctx.with_client_capabilities(capabilities);
            }
            Ok(None) => {}
            Err(error) => return response_for_error(error),
        }
        match admitted_final_client_implementation(final_core_request.as_ref()) {
            Ok(Some(identity)) => {
                request_ctx = request_ctx.with_client_implementation(identity);
            }
            Ok(None) => {}
            Err(error) => return response_for_error(error),
        }
        if let Some(level) = self.final_request_log_level(&request) {
            request_ctx =
                request_ctx.with_min_log_level(Some(Self::mcp_log_level_from_final(level)));
        }
        {
            let sender = notification_sender.clone();
            request_ctx =
                request_ctx.with_log_sender(Arc::new(crate::handler::LogNotificationSender::new(
                    move |notification| {
                        sender(notification);
                    },
                    ProtocolEra::Modern2026,
                )));
        }
        // The outer request owner retains the sole final-progress runtime.
        // Router/handler derivation sees this reporter and reuses it instead
        // of constructing a second sender, so the coalescing slot and
        // terminal race remain request-scoped across the whole call chain.
        let final_progress_runtime = final_core_request
            .as_ref()
            .and_then(|_| Self::request_progress_marker(&request))
            .map(|marker| {
                let sender = notification_sender.clone();
                let frame_context = request_ctx.clone();
                let frame_cancellation = request_cancellation.clone();
                Arc::new(handler::FinalProgressRuntime::new(
                    marker,
                    move |notification| {
                        // A final response finalization prevents a later
                        // cancellation from winning, but an ordinary peer or
                        // body-drop cancellation must suppress every queued
                        // progress frame at the callback boundary.
                        if !frame_cancellation.is_cancel_requested()
                            && frame_context.ensure_live().is_ok()
                        {
                            sender(notification);
                        }
                    },
                ))
            });
        if let Some(runtime) = &final_progress_runtime {
            request_ctx = request_ctx.with_progress_reporter(Arc::clone(runtime).into_reporter());
        }

        let mut entered_middleware: Vec<&dyn crate::Middleware> = Vec::new();
        let mut middleware_result = None;
        for middleware in self.middleware.iter() {
            if let Err(error) = Self::enforce_request_context(&request_ctx) {
                middleware_result = Some(Err(error));
                break;
            }
            entered_middleware.push(middleware.as_ref());
            let decision = catch_extension_unwind(|| middleware.on_request(&request_ctx, &request))
                .map_err(|_payload| extension_panic_error("middleware_on_request"))
                .and_then(|result| result);
            match decision {
                Ok(MiddlewareDecision::Continue) => {}
                Ok(MiddlewareDecision::Respond(value)) => {
                    middleware_result = Some(
                        if final_core_request.is_some()
                            && !middleware_may_complete_final_core_from_cache(
                                &request_ctx,
                                middleware.as_ref(),
                                &value,
                            )
                        {
                            Err(McpError::internal_error(
                                "middleware cannot short-circuit a final core response",
                            ))
                        } else {
                            Ok(value)
                        },
                    );
                    break;
                }
                Err(error) => {
                    middleware_result = Some(Err(error));
                    break;
                }
            }
        }
        // Bound the dispatch state and its Send proof before the progress
        // timer and transport futures wrap it. The same owner still polls
        // and drops the request; no extra task or cancellation scope is added.
        let dispatch: std::pin::Pin<
            Box<dyn Future<Output = McpResult<serde_json::Value>> + Send + '_>,
        > = Box::pin(async {
            match middleware_result {
                Some(result) => result,
                None if request.method == SERVER_DISCOVER_METHOD => {
                    let params = request
                        .params
                        .clone()
                        .unwrap_or_else(|| serde_json::json!({}));
                    match serde_json::from_value::<ServerDiscoverRequest>(params)
                        .map_err(|error| McpError::invalid_params(error.to_string()))
                    {
                        Ok(_) => self.server_discovery().and_then(|result| {
                            serde_json::to_value(result).map_err(McpError::from)
                        }),
                        Err(error) => Err(error),
                    }
                }
                None if request.method == SUBSCRIPTIONS_LISTEN => {
                    self.dispatch_final_subscriptions_listen(
                        &request_ctx,
                        &request,
                        modern_http_owner,
                        request_cancellation.clone(),
                        terminal_delivery,
                        Arc::clone(&notification_sender),
                    )
                    .await
                }
                None => match Arc::clone(&self.router)
                    .dispatch_stateless_owned_with_handler_admission(
                        request_ctx.clone(),
                        request.clone(),
                        retained_raw_params(
                            raw_params.as_deref(),
                            admitted_params.as_ref(),
                            request.params.as_ref(),
                        )
                        .map(Arc::<str>::from),
                        inbound.mrtr_continuation_cancellation().unwrap_or_default(),
                        handler_admission,
                    )
                    .await
                {
                    Err(error) if error.code == McpErrorCode::MethodNotFound => {
                        self.dispatch_extension_fallback_async(&request_ctx, &request)
                            .await
                    }
                    result => result,
                },
            }
        });
        let result = match final_progress_runtime.as_ref() {
            Some(runtime) => {
                await_final_progress_rate_tick(
                    request_ctx.cx(),
                    &request_cancellation,
                    runtime,
                    dispatch,
                )
                .await
            }
            None => dispatch.await,
        };
        // The server-side graceful election cancels the listen as its
        // dispatch wake; liveness gating would convert the sanctioned
        // terminal completion into a cancellation error, so that exact
        // response is exempt while middleware hooks still run.
        let raw_graceful_completion = request.method == SUBSCRIPTIONS_LISTEN
            && result.as_ref().is_ok_and(|value| {
                final_subscription_completion_result(value, request.id.as_ref())
            });
        let result = match result {
            Ok(value) => {
                let metadata_seal = final_core_middleware_metadata_seal(
                    final_core_request.as_ref(),
                    &request,
                    &value,
                );
                metadata_seal
                    .and_then(|metadata_seal| {
                        self.apply_middleware_response_with_liveness(
                            &entered_middleware,
                            &request_ctx,
                            &request,
                            value,
                            !raw_graceful_completion,
                        )
                        .and_then(|value| {
                            validate_final_core_middleware_response(
                                final_core_request.as_ref(),
                                &request,
                                value,
                            )
                        })
                        .and_then(|value| {
                            validate_final_core_middleware_metadata_seal(
                                metadata_seal.as_ref(),
                                final_core_request.as_ref(),
                                &request,
                                &value,
                            )?;
                            Ok(value)
                        })
                    })
                    .map_err(|error| {
                        self.apply_middleware_error(
                            &entered_middleware,
                            &request_ctx,
                            &request,
                            error,
                        )
                    })
            }
            Err(error) => {
                Err(self.apply_middleware_error(&entered_middleware, &request_ctx, &request, error))
            }
        };
        let graceful_subscription_completion = request.method == SUBSCRIPTIONS_LISTEN
            && result.as_ref().is_ok_and(|value| {
                final_subscription_completion_result(value, request.id.as_ref())
            });
        // Response middleware may replace the server-elected complete result
        // with the one canonical missing-capability error. Once a live SSE
        // listen has admitted, that replacement is its terminal SSE response
        // rather than a request-cancellation loser; preserve it through the
        // liveness fence below.
        let graceful_subscription_canonical_substitution = raw_graceful_completion
            && result
                .as_ref()
                .is_err_and(is_canonical_missing_required_client_capability_error);
        let result =
            if graceful_subscription_completion || graceful_subscription_canonical_substitution {
                result
            } else {
                Self::request_context_error(&request_ctx).map_or(result, Err)
            };
        // Elect terminal ownership before final progress, logging, or a
        // response writer can run. A cancellation result, or cancellation
        // already elected by response-body drop, suppresses every trailing
        // request-scoped notification instead of letting a final log escape
        // after the cancelled tool call.
        let finalization_won = !result
            .as_ref()
            .is_err_and(|error| error.code == McpErrorCode::RequestCancelled)
            && request_cancellation.begin_finalization();
        if let Some(runtime) = &final_progress_runtime {
            if finalization_won {
                runtime.finalize();
            } else {
                runtime.cancel();
            }
        }
        if let Some(stats) = &self.stats {
            stats.record_request(&method, started_at.elapsed(), result.is_ok());
        }
        if finalization_won {
            self.maybe_emit_final_log_notification(&request, &notification_sender, result.is_ok());
        }
        if is_notification {
            if let Err(error) = result {
                error!(
                    target: targets::HANDLER,
                    "Stateless notification failed; method_key={:016x}; code={:?}",
                    stable_hash_request_id(&method),
                    error.code
                );
            }
            return None;
        }
        if request.method == SUBSCRIPTIONS_LISTEN
            && request_cancellation.is_cancel_requested()
            && !graceful_subscription_completion
            && !graceful_subscription_canonical_substitution
        {
            return None;
        }
        let response_id = response_id.expect("non-notification requests have an id");
        Some(match result {
            Ok(value) => JsonRpcResponse::success(response_id, value),
            Err(error) => {
                let masked = mask_peer_error(error, self.mask_error_details);
                JsonRpcResponse::error(
                    Some(response_id),
                    JsonRpcError {
                        code: masked.code.into(),
                        message: masked.message,
                        data: masked.data,
                    },
                )
            }
        })
    }

    #[cfg(feature = "tasks")]
    fn admit_final_task_subscription(
        &self,
        notifications: &SubscriptionFilter,
        client_capabilities: &serde_json::Map<String, serde_json::Value>,
    ) -> McpResult<bool> {
        let tasks_requested = task_subscription_ids(notifications)
            .map_err(|_| McpError::invalid_params("invalid Tasks subscription filter"))?
            .is_some();
        if !tasks_requested {
            return Ok(false);
        }

        let has_task_service = self.final_task_runtime.is_some() || {
            #[cfg(feature = "proxy")]
            {
                self.final_task_relay.is_some()
            }
            #[cfg(not(feature = "proxy"))]
            {
                false
            }
        };
        if !has_task_service {
            return Err(McpError::invalid_params(
                "Tasks subscription filter is unavailable on this server",
            ));
        }

        let tasks_declared = client_capabilities
            .get("extensions")
            .and_then(serde_json::Value::as_object)
            .and_then(|extensions| extensions.get(fastmcp_protocol::TASKS_EXTENSION))
            .and_then(serde_json::Value::as_object)
            .is_some_and(serde_json::Map::is_empty);
        if !tasks_declared {
            return Err(missing_final_tasks_capability_error()?);
        }
        Ok(true)
    }

    /// Executes one final `subscriptions/listen` request until the server
    /// begins graceful stream termination or the request transport is
    /// cancelled. The registry lease is intentionally scoped to this future:
    /// cancellation, disconnect, and every error path remove the entry before
    /// the request response path can run.
    async fn dispatch_final_subscriptions_listen(
        self: &Arc<Self>,
        request_ctx: &McpContext,
        request: &JsonRpcRequest,
        modern_http_owner: Option<u64>,
        request_cancellation: McpRequestCancellation,
        terminal_delivery: Option<Arc<FinalSubscriptionTerminalDelivery>>,
        notification_sender: NotificationSender,
    ) -> McpResult<serde_json::Value> {
        let subscription_id = request.id.clone().ok_or_else(|| {
            McpError::invalid_request("subscriptions/listen must carry a JSON-RPC request id")
        })?;
        let params = request
            .params
            .clone()
            .ok_or_else(|| McpError::invalid_params("subscriptions/listen requires parameters"))
            .and_then(|params| {
                serde_json::from_value::<FinalSubscriptionsListenParams>(params)
                    .map_err(|error| McpError::invalid_params(error.to_string()))
            })?;
        let protocol_version = params.meta.protocol_version().map_err(|_| {
            McpError::invalid_params("subscriptions/listen has invalid protocol metadata")
        })?;
        let client_capabilities = params.meta.client_capabilities().map_err(|_| {
            McpError::invalid_params("subscriptions/listen has invalid client capabilities")
        })?;
        if client_capabilities.is_none() {
            return Err(McpError::invalid_params(
                "subscriptions/listen requires exact final request metadata",
            ));
        }
        #[cfg(feature = "tasks")]
        let client_capabilities = client_capabilities.expect("presence checked above");
        if protocol_version != Some(MODERN_PROTOCOL_VERSION) {
            return Err(McpError::invalid_params(
                "subscriptions/listen requires exact final request metadata",
            ));
        }
        #[cfg(feature = "tasks")]
        let tasks_requested =
            self.admit_final_task_subscription(&params.notifications, client_capabilities)?;
        #[cfg(feature = "tasks")]
        let notification_sender =
            if tasks_requested && let Some(runtime) = self.final_task_runtime.as_ref() {
                let mut admitted_tasks = BTreeMap::new();
                for task_id in task_subscription_ids(&params.notifications)
                    .map_err(|_| McpError::invalid_params("invalid Tasks subscription filter"))?
                    .unwrap_or_default()
                {
                    let snapshot = runtime.task_for_request(request_ctx, &task_id)?;
                    admitted_tasks.insert(task_id, snapshot);
                }
                let runtime = runtime.clone();
                let guarded: NotificationSender = Arc::new(move |notification| {
                    if notification.method == fastmcp_protocol::TASK_STATUS_NOTIFICATION {
                        let event = serde_json::to_value(&notification).ok().and_then(|wire| {
                            serde_json::from_value::<FinalTaskStatusNotification>(wire).ok()
                        });
                        let Some(event) = event else {
                            return;
                        };
                        let Some(admitted) = admitted_tasks.get(&event.params.task.base().task_id)
                        else {
                            return;
                        };
                        if !runtime.notification_matches_task_owner(admitted, &event) {
                            return;
                        }
                    }
                    notification_sender(notification);
                });
                guarded
            } else {
                notification_sender
            };
        #[cfg(not(feature = "tasks"))]
        let tasks_requested = false;

        if request_cancellation.is_cancel_requested() || request_ctx.ensure_live().is_err() {
            return Err(McpError::request_cancelled());
        }

        // A route-bound relay owns a distinct upstream listen request. Require
        // its acknowledgement before acknowledging downstream, and refuse a
        // narrowed upstream filter rather than advertising task IDs we cannot
        // later deliver. The listener itself remains owned by this downstream
        // request future; dropping it closes its upstream response body.
        #[cfg(all(feature = "proxy", feature = "tasks"))]
        let mut relay_listener: Option<Box<dyn ProxyFinalTaskListener>> = None;
        #[cfg(all(feature = "proxy", feature = "tasks"))]
        if tasks_requested && let Some(relay) = self.final_task_relay.as_ref() {
            let mut listener = relay
                .open_listener_async(request_ctx, params.notifications.clone())
                .await?;
            match listener
                .next_async(request_ctx.cx(), &request_cancellation)
                .await?
            {
                ProxyFinalTaskListenerEvent::Acknowledged(accepted) => {
                    if !subscription_filter_admission_matches(&params.notifications, &accepted)? {
                        return Err(McpError::invalid_params(
                            "Proxy upstream narrowed the final Tasks subscription filter",
                        ));
                    }
                }
                ProxyFinalTaskListenerEvent::Notification(_)
                | ProxyFinalTaskListenerEvent::Terminal => {
                    return Err(McpError::invalid_request(
                        "Proxy upstream Tasks listener did not acknowledge before events",
                    ));
                }
            }
            relay_listener = Some(listener);
        }

        #[cfg(all(feature = "proxy", feature = "tasks"))]
        let mut catalog_relay_listener: Option<Box<dyn ProxyCatalogListener>> = None;
        #[cfg(all(feature = "proxy", feature = "tasks"))]
        if !tasks_requested
            && catalog_filter_requests_resource_updates(&params.notifications)
            && let Some(relay) = self.final_task_relay.as_ref()
        {
            let mut listener = relay
                .open_catalog_listener_async(request_ctx, params.notifications.clone())
                .await?;
            match listener
                .next_async(request_ctx.cx(), &request_cancellation)
                .await?
            {
                ProxyCatalogListenerEvent::Acknowledged(accepted) => {
                    if !subscription_filter_admission_matches(&params.notifications, &accepted)? {
                        return Err(McpError::invalid_params(
                            "Proxy upstream narrowed the catalog subscription filter",
                        ));
                    }
                }
                ProxyCatalogListenerEvent::Notification(_)
                | ProxyCatalogListenerEvent::Terminal => {
                    return Err(McpError::invalid_request(
                        "Proxy upstream catalog listener did not acknowledge before events",
                    ));
                }
            }
            catalog_relay_listener = Some(listener);
        }

        #[cfg(feature = "tasks")]
        let task_principal = if tasks_requested && self.final_task_runtime.is_some() {
            request_ctx
                .auth()
                .as_ref()
                .map(|auth| auth::principal_fingerprint(Some(auth)))
                .transpose()?
        } else {
            None
        };
        #[cfg(not(feature = "tasks"))]
        let task_principal = None;
        let lease = self.final_subscriptions.open_with_task_principal(
            subscription_id.clone(),
            params.notifications,
            tasks_requested,
            modern_http_owner,
            request_cancellation.clone(),
            terminal_delivery.clone(),
            notification_sender,
            task_principal,
        )?;

        while !self.final_subscriptions.is_terminating() {
            if request_cancellation.is_cancel_requested() || request_ctx.ensure_live().is_err() {
                if lease.has_graceful_completion() {
                    return self.final_subscription_complete_result(&subscription_id);
                }
                if let Some(delivery) = &terminal_delivery {
                    delivery.mark_failed();
                }
                return Err(McpError::request_cancelled());
            }
            #[cfg(all(feature = "proxy", feature = "tasks"))]
            if let Some(listener) = relay_listener.as_mut() {
                match listener
                    .next_async(request_ctx.cx(), &request_cancellation)
                    .await
                {
                    Ok(ProxyFinalTaskListenerEvent::Notification(notification)) => {
                        self.final_subscriptions.publish_task(notification)?;
                    }
                    Ok(ProxyFinalTaskListenerEvent::Terminal) => {
                        return self.final_subscription_complete_result(&subscription_id);
                    }
                    Ok(ProxyFinalTaskListenerEvent::Acknowledged(_)) => {
                        return Err(McpError::invalid_request(
                            "Proxy upstream Tasks listener acknowledged more than once",
                        ));
                    }
                    Err(error) if error.code == McpErrorCode::RequestCancelled => {
                        // Shutdown elects graceful completion by cancelling
                        // this wait. The `?` path would drop that elected
                        // terminal response because cancellation already won
                        // the request token, and HTTP teardown would wait out
                        // both drain budgets.
                        if lease.has_graceful_completion() {
                            return self.final_subscription_complete_result(&subscription_id);
                        }
                        if let Some(delivery) = &terminal_delivery {
                            delivery.mark_failed();
                        }
                        return Err(error);
                    }
                    Err(error) => return Err(error),
                }
            }
            #[cfg(all(feature = "proxy", feature = "tasks"))]
            if let Some(listener) = catalog_relay_listener.as_mut() {
                match listener
                    .next_async(request_ctx.cx(), &request_cancellation)
                    .await
                {
                    Ok(ProxyCatalogListenerEvent::Notification(
                        notification @ ServerNotification::ResourceUpdated(_),
                    )) => {
                        self.final_subscriptions.publish(notification)?;
                    }
                    Ok(ProxyCatalogListenerEvent::Notification(_)) => {}
                    Ok(ProxyCatalogListenerEvent::Terminal) => {
                        return self.final_subscription_complete_result(&subscription_id);
                    }
                    Ok(ProxyCatalogListenerEvent::Acknowledged(_)) => {
                        return Err(McpError::invalid_request(
                            "Proxy upstream catalog listener acknowledged more than once",
                        ));
                    }
                    Err(error) if error.code == McpErrorCode::RequestCancelled => {
                        if lease.has_graceful_completion() {
                            return self.final_subscription_complete_result(&subscription_id);
                        }
                        if let Some(delivery) = &terminal_delivery {
                            delivery.mark_failed();
                        }
                        return Err(error);
                    }
                    Err(error) => return Err(error),
                }
            }
            if request_cancellation.is_cancel_requested() {
                // A server-side graceful election cancels this request as its
                // wake; the elected terminal completion outranks the plain
                // cancellation error a peer-initiated cancel produces.
                if lease.has_graceful_completion() {
                    return self.final_subscription_complete_result(&subscription_id);
                }
                if let Some(delivery) = &terminal_delivery {
                    delivery.mark_failed();
                }
                return Err(McpError::request_cancelled());
            }
            if request_ctx.ensure_live().is_err() {
                // Keep the lease registered until the owning server lifecycle
                // performs its global terminal election. Exiting here would
                // let `Drop` remove the entry before `BoundHttpServer::serve`
                // can obtain the delivery receipt it must await. An embedding
                // session without that lifecycle still releases this wait by
                // cancelling the exact response-body request in `close`.
                while !self.final_subscriptions.is_terminating()
                    && !request_cancellation.is_cancel_requested()
                {
                    asupersync::runtime::yield_now().await;
                }
                if request_cancellation.is_cancel_requested()
                    && !self.final_subscriptions.is_terminating()
                    && !lease.has_graceful_completion()
                {
                    return Err(McpError::request_cancelled());
                }
                break;
            }
            // The registry is intentionally transport-neutral. Polling uses
            // the caller-owned clock and never creates a detached wake task;
            // a request cancellation wakes its transport-owned dispatch task.
            // Race the poll against `cancelled()` so two live HTTP listens
            // wake as soon as `terminate_with_receipt` elects completion,
            // instead of remaining parked on a cancelled-Cx timer.
            if request_ctx.ensure_live().is_err() {
                asupersync::runtime::yield_now().await;
            } else {
                let mut sleep = std::pin::pin!(asupersync::time::sleep(
                    request_ctx.cx().now(),
                    Duration::from_millis(1),
                ));
                let cancellation = request_cancellation.clone();
                let mut cancelled = std::pin::pin!(async move {
                    cancellation.cancelled().await;
                });
                std::future::poll_fn(|task_cx| {
                    if self.final_subscriptions.is_terminating()
                        || request_cancellation.is_cancel_requested()
                    {
                        return std::task::Poll::Ready(());
                    }
                    if cancelled.as_mut().poll(task_cx).is_ready() {
                        return std::task::Poll::Ready(());
                    }
                    if sleep.as_mut().poll(task_cx).is_ready() {
                        return std::task::Poll::Ready(());
                    }
                    std::task::Poll::Pending
                })
                .await;
            }
        }

        // `terminate_with_receipt` publishes its global terminating bit before
        // it acquires each lease election. Do not let that brief ordering
        // window turn a server-owned graceful close into peer cancellation:
        // wait until this exact lease records which terminal owner won.
        while self.final_subscriptions.is_terminating()
            && !lease.has_graceful_completion()
            && !lease.is_peer_terminated()
            && !request_cancellation.is_cancel_requested()
        {
            asupersync::runtime::yield_now().await;
        }

        if lease.has_graceful_completion() {
            return self.final_subscription_complete_result(&subscription_id);
        }

        Err(McpError::request_cancelled())
    }

    fn final_subscription_complete_result(
        &self,
        subscription_id: &RequestId,
    ) -> McpResult<serde_json::Value> {
        let server_info =
            Implementation::try_new(self.info.name.clone(), self.info.version.clone())
                .map_err(|_| McpError::internal_error("server identity is invalid"))?;
        let mut metadata = BTreeMap::new();
        metadata.insert(
            FINAL_SERVER_INFO_META_KEY.to_owned(),
            serde_json::to_value(&server_info).map_err(McpError::from)?,
        );
        metadata.insert(
            FINAL_SUBSCRIPTION_ID_META_KEY.to_owned(),
            serde_json::to_value(subscription_id).map_err(McpError::from)?,
        );
        let metadata = OpenMetadata::try_from_entries(metadata)
            .map_err(|_| McpError::internal_error("final subscription metadata is invalid"))?;
        let result = CompleteResult::new(
            FinalSubscriptionsListenResult {},
            ResultMeta::server_generated(server_info).with_metadata(metadata),
        );
        let wire = CoreResult::Final(FinalCoreResult::SubscriptionsListen {
            result,
            subscription_id: subscription_id.clone(),
            diagnostic: None,
        })
        .encode()
        .map_err(|error| {
            McpError::internal_error(format!(
                "failed to encode final subscriptions/listen completion: {error}"
            ))
        })?;
        serde_json::from_str(&wire).map_err(McpError::from)
    }

    /// Runs one modern stdio request. `subscriptions/listen` runs in a
    /// caller-owned blocking task so the receive pump can keep accepting
    /// requests while shutdown retains the subscription's active ownership.
    /// On an unsplit transport, output queued while `recv` owns the I/O
    /// handle flushes when that receive returns. Waiting for a blocked
    /// middleware callback here would also block the input that releases it;
    /// callers needing independent output must use the split transport API.
    ///
    /// `cx` is the RECEIVE PUMP's context and owns transport I/O. `dispatch_cx`
    /// is the caller runtime's context and owns the request future: when the
    /// pump runs as a blocking child (the stdio arrangement), a handler that
    /// admits an async child cannot make progress under the pump's blocking
    /// context, and the request future stays `Pending` forever — the process
    /// answers `server/discover` and then silently stops responding
    /// (GitHub #65). Callers whose pump and runtime are the same context pass
    /// the same `Cx` twice.
    fn dispatch_or_schedule_stdio_modern_request<S>(
        server: Arc<Self>,
        cx: &Cx,
        dispatch_cx: &Cx,
        session_id: u64,
        inbound: InboundRequestContext,
        request: JsonRpcRequest,
        auth_receipt: Option<AuthDispatchCustody>,
        auth_custody_generation: Option<u64>,
        notification_sender: NotificationSender,
        send: Arc<Mutex<S>>,
        background_send_failure: Arc<Mutex<Option<McpError>>>,
        queue: Arc<DispatchQueueState>,
    ) -> Option<JsonRpcResponse>
    where
        S: FnMut(&Cx, &JsonRpcMessage) -> Result<(), TransportError> + Send + 'static,
    {
        let policy = server.protocol_policy;
        if request.id.is_none() && request.method == "notifications/cancelled" {
            let mut request = request;
            if admit_final_client_notification_ingress(&request).is_ok()
                && let Ok(cancellation) = server.authenticate_modern_cancelled_control(
                    &inbound,
                    &mut request,
                    auth_receipt.as_ref(),
                    auth_custody_generation,
                )
            {
                let _writer = send
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                server.handle_cancellation_wire_notification(session_id, cancellation);
            }
            return None;
        }
        // Reserve count and retained bytes before authentication or task
        // submission. The owner moves into the task, including while it is
        // queued or still blocked in application middleware.
        let reservation =
            match queue.admit_modern_request(&request, Arc::new(AtomicBool::new(false))) {
                Ok(reservation) => reservation,
                Err(error) => return request.id.map(|id| JsonRpcResponse::error(Some(id), error)),
            };
        let request_cancellation = reservation.cancellation();
        // Establish the connection principal before receiving another frame.
        // A cancellation of this opening request must work even if its child
        // has not started. The private receipt prevents a second provider call.
        let auth_receipt = match server.admit_modern_pump_authentication(
            &inbound,
            &request,
            auth_receipt.as_ref(),
            auth_custody_generation,
        ) {
            Ok(receipt) => Some(receipt),
            Err(error) => {
                let error = mask_peer_error(error, server.mask_error_details);
                return request.id.map(|id| {
                    JsonRpcResponse::error(
                        Some(id),
                        JsonRpcError {
                            code: error.code.into(),
                            message: error.message,
                            data: error.data,
                        },
                    )
                });
            }
        };
        if request.method == SUBSCRIPTIONS_LISTEN {
            // `inbound`/`request` move into the worker closure below;
            // `InboundRequestContext` is deliberately non-Clone, so a failed
            // spawn cannot fall back to inline dispatch — it answers with an
            // internal error instead of freezing the receive pump.
            let send_cx = cx.clone();
            let request_id = request.id.clone();
            // Never let spawn_blocking fall back to polling a blocking
            // middleware inline on the caller's async worker.
            if dispatch_cx.blocking_pool_handle().is_none() {
                return Some(JsonRpcResponse::error(
                    request_id,
                    JsonRpcError {
                        code: McpErrorCode::InternalError.into(),
                        message: "Subscriptions require a caller-owned blocking pool".to_owned(),
                        data: None,
                    },
                ));
            }
            // Reserve ownership before admission: shutdown can race a queued
            // task before its caller-owned child Cx has been created.
            let active_request = request
                .id
                .clone()
                .map(|id| {
                    ActiveRequestGuard::try_reserve(
                        Arc::clone(&server.active_requests),
                        session_id,
                        id,
                        dispatch_cx.region_id(),
                        request_cancellation.clone(),
                    )
                })
                .transpose();
            let active_request = match active_request {
                Ok(guard) => guard,
                Err(_) => {
                    return Some(JsonRpcResponse::error(
                        request_id,
                        JsonRpcError {
                            code: McpErrorCode::InvalidRequest.into(),
                            message: "Request id is already active".to_owned(),
                            data: None,
                        },
                    ));
                }
            };
            let submitted = dispatch_cx.spawn_blocking({
                let server = Arc::clone(&server);
                let notification_sender = Arc::clone(&notification_sender);
                let request_cancellation = request_cancellation.clone();
                move |request_cx| {
                    let _reservation = reservation;
                    let active_guard = active_request;
                    if active_guard
                        .as_ref()
                        .is_some_and(|guard| !guard.activate(request_cx.clone()))
                    {
                        return;
                    }
                    let inbound = inbound.with_cx(request_cx.clone());
                    let response = poll_on_cx(
                        &request_cx,
                        server.dispatch_with_protocol_policy_owned(
                            policy,
                            &inbound,
                            request,
                            None,
                            auth_receipt,
                            auth_custody_generation,
                            None,
                            request_cancellation,
                            None,
                            notification_sender,
                        ),
                    );
                    if let Some(response) = response {
                        let mut send_guard = send
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner);
                        if let Err(error) =
                            send_guard(&send_cx, &JsonRpcMessage::Response(response))
                            && let Err(error) = returning_send_result(&error)
                        {
                            background_send_failure
                                .lock()
                                .unwrap_or_else(std::sync::PoisonError::into_inner)
                                .get_or_insert(error);
                        }
                    }
                    drop(active_guard);
                }
            });
            return match submitted {
                Ok(_) => None,
                Err(_) => Some(JsonRpcResponse::error(
                    request_id,
                    JsonRpcError {
                        code: (-32603).into(),
                        message: "Caller runtime could not admit the subscription task".to_owned(),
                        data: None,
                    },
                )),
            };
        }
        poll_on_cx(
            dispatch_cx,
            server.dispatch_with_protocol_policy_owned(
                policy,
                &inbound,
                request,
                None,
                auth_receipt,
                auth_custody_generation,
                None,
                request_cancellation,
                None,
                notification_sender,
            ),
        )
    }

    async fn dispatch_with_protocol_policy_owned(
        self: Arc<Self>,
        policy: ProtocolPolicy,
        inbound: &InboundRequestContext,
        request: JsonRpcRequest,
        raw_params: Option<Arc<str>>,
        auth_receipt: Option<AuthDispatchCustody>,
        websocket_connection_generation: Option<u64>,
        modern_http_owner: Option<u64>,
        request_cancellation: McpRequestCancellation,
        terminal_delivery: Option<Arc<FinalSubscriptionTerminalDelivery>>,
        notification_sender: NotificationSender,
    ) -> Option<JsonRpcResponse> {
        self.dispatch_with_protocol_policy_owned_and_handler_admission(
            policy,
            inbound,
            request,
            raw_params,
            auth_receipt,
            websocket_connection_generation,
            modern_http_owner,
            request_cancellation,
            terminal_delivery,
            notification_sender,
            None,
        )
        .await
    }

    async fn dispatch_with_protocol_policy_owned_and_handler_admission(
        self: Arc<Self>,
        policy: ProtocolPolicy,
        inbound: &InboundRequestContext,
        request: JsonRpcRequest,
        raw_params: Option<Arc<str>>,
        auth_receipt: Option<AuthDispatchCustody>,
        websocket_connection_generation: Option<u64>,
        modern_http_owner: Option<u64>,
        request_cancellation: McpRequestCancellation,
        terminal_delivery: Option<Arc<FinalSubscriptionTerminalDelivery>>,
        notification_sender: NotificationSender,
        handler_admission: Option<FinalHandlerAdmission>,
    ) -> Option<JsonRpcResponse> {
        if matches!(policy, ProtocolPolicy::ModernOnly)
            && request.method == "initialize"
            && request.validate().is_ok()
            && inbound.request_id() == request_id_to_u64(request.id.as_ref())
        {
            return request.id.clone().map(|id| {
                JsonRpcResponse::error(
                    Some(id),
                    JsonRpcError {
                        code: (-32601).into(),
                        message: MODERN_ONLY_INITIALIZE_MESSAGE.to_owned(),
                        data: Some(serde_json::json!({ "supported": ["2026-07-28"] })),
                    },
                )
            });
        }
        self.dispatch_stateless_owned_with_cancellation(
            inbound,
            request,
            raw_params,
            auth_receipt,
            websocket_connection_generation,
            modern_http_owner,
            request_cancellation,
            terminal_delivery,
            notification_sender,
            handler_admission,
        )
        .await
    }

    /// Dispatches one adapter-admitted exact-2024 request without applying the
    /// modern complete-result package.
    ///
    /// The exact adapter owns lifecycle admission and final JSON-RPC response
    /// construction. This seam owns the request authority for a real wire ID,
    /// including cooperative cancellation, middleware ordering, and raw
    /// method-specific result serialization. In particular, it must never
    /// reuse [`Self::dispatch_stateless`]: that modern surface adds
    /// `resultType: "complete"`, which has no exact-2024 representation.
    #[cfg(feature = "legacy-2024-11-05")]
    async fn dispatch_legacy_2024(
        &self,
        cx: &Cx,
        session_id: u64,
        session_principal: &SessionPrincipalBinding,
        runtime: Option<&LiveLegacy2024ConnectionRuntime>,
        admitted_cancellation: Option<McpRequestCancellation>,
        request: &JsonRpcRequest,
        auth_receipt: Option<&AuthAdmissionReceipt>,
        connection_auth: Option<&AuthDispatchCustody>,
    ) -> McpResult<LiveLegacy2024Dispatch> {
        let request_id = request
            .id
            .clone()
            .ok_or_else(|| McpError::invalid_request("exact legacy requests require an id"))?;
        let budget = self.create_request_budget(cx);
        Self::enforce_request_budget(cx, budget)?;

        // Hold this guard through handler and middleware completion so a
        // concurrently received notifications/cancelled frame targets the
        // exact legacy wire ID rather than an internal synthetic ID.
        let active_guard = ActiveRequestGuard::try_new_with_cancellation(
            Arc::clone(&self.active_requests),
            session_id,
            request_id,
            cx.clone(),
            admitted_cancellation.unwrap_or_default(),
        )
        .map_err(|_| {
            McpError::invalid_request(
                "Request id is already active; wait for the earlier request to finish before reusing it",
            )
        })?;
        let request_cancellation = active_guard.cancellation();
        let result = async {
            let session_state =
                runtime.map_or_else(SessionState::new, |runtime| runtime.session_state.clone());
            let (mut request_ctx, _request_lease_guard) = self.request_context(
                cx,
                request_id_to_u64(request.id.as_ref()),
                session_state.clone(),
                request_cancellation.clone(),
                budget,
            )?;
            request_ctx = Self::attach_session_log_floor(
                request_ctx,
                runtime.and_then(|runtime| runtime.log_level()),
            );
            if let Some(runtime) = runtime {
                let subscriptions = runtime
                    .resource_subscriptions
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .clone();
                request_ctx = Self::attach_session_resource_subscriptions(
                    request_ctx,
                    subscriptions.iter().map(String::as_str),
                );
            }
            if let Some(runtime) = runtime {
                let mut info = ClientCapabilityInfo::new();
                if runtime.supports_sampling.load(Ordering::Acquire) {
                    info = info.with_sampling();
                }
                if runtime.supports_roots.load(Ordering::Acquire) {
                    info = info.with_roots(false);
                }
                request_ctx = request_ctx.with_client_capabilities(info);
                let identity = runtime
                    .client_info
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .clone();
                request_ctx =
                    Self::attach_session_client_implementation(request_ctx, identity.as_ref());
            }
            if let Some(runtime) = runtime {
                let sender = Arc::clone(&runtime.notification_sender);
                request_ctx = request_ctx.with_log_sender(Arc::new(
                    crate::handler::LogNotificationSender::new(
                        move |notification| {
                            sender(notification);
                        },
                        ProtocolEra::Legacy2024,
                    ),
                ));
            }
            if let (Some(marker), Some(runtime)) = (Self::request_progress_marker(request), runtime)
            {
                let sender = Arc::clone(&runtime.notification_sender);
                request_ctx = request_ctx.with_progress_reporter(
                    ProgressNotificationSender::new(marker, move |notification| {
                        sender(notification);
                    })
                    .into_reporter(),
                );
            }
            let bidirectional_senders = runtime.and_then(|runtime| {
                runtime.bidirectional_senders(self, &request_cancellation, &request_ctx)
            });
            Self::enforce_request_context(&request_ctx)?;
            // Clone so in-band credentials can be stripped after admission.
            // Exact-2024 stdio has no transport custody; it must still evaluate
            // AuthProvider the same way modern stdio does, or negotiating
            // 2024-11-05 would skip every installed verifier.
            let mut request = request.clone();
            let fingerprint = if let Some(receipt) = auth_receipt {
                let fingerprint = receipt.commit_legacy(&request_ctx, &request)?;
                request.params = receipt.sanitized_params.clone();
                fingerprint
            } else if let Some(connection_auth) = connection_auth {
                let fingerprint = connection_auth.commit_legacy_connection(&request_ctx)?;
                auth::strip_recognized_access_credentials(&mut request.params);
                fingerprint
            } else {
                let auth_request = AuthRequest {
                    method: request.method.as_str(),
                    params: request.params.as_ref(),
                    transport_authorization: None,
                    request_id: request_id_to_u64(request.id.as_ref()),
                };
                let fingerprint = self.authenticate_request(&request_ctx, auth_request)?;
                auth::strip_recognized_access_credentials(&mut request.params);
                fingerprint
            };
            if !session_principal.bind_or_verify(fingerprint) {
                return Err(McpError::new(
                    McpErrorCode::ResourceForbidden,
                    "Authenticated principal does not own an admitted session",
                ));
            }

            let mut entered_middleware: Vec<&dyn crate::Middleware> = Vec::new();
            let result: McpResult<serde_json::Value> = async {
                for middleware in self.middleware.iter() {
                    Self::enforce_request_context(&request_ctx)?;
                    entered_middleware.push(middleware.as_ref());
                    match catch_extension_unwind(|| middleware.on_request(&request_ctx, &request)) {
                        Ok(Ok(MiddlewareDecision::Continue)) => {}
                        Ok(Ok(MiddlewareDecision::Respond(value))) => return Ok(value),
                        Ok(Err(error)) => return Err(error),
                        Err(_payload) => {
                            return Err(extension_panic_error("middleware_on_request"));
                        }
                    }
                }

                let params = request.params.clone();
                match request.method.as_str() {
                    "completion/complete" => {
                        self.router
                            .dispatch_legacy_completion_in_request(&request_ctx, cx, &request)
                            .await
                    }
                    "tools/list" => {
                        let params: ListToolsParams = parse_params_or_default(params)?;
                        serde_json::to_value(self.router.handle_tools_list(
                            &request_ctx,
                            params,
                            Some(&session_state),
                        )?)
                        .map_err(McpError::from)
                    }
                    "tools/call" => {
                        let params: CallToolParams = parse_params(params)?;
                        if self.legacy_application_tool_content {
                            return serde_json::to_value(
                                self.router
                                    .handle_application_tools_call_in_request(
                                        &request_ctx,
                                        cx,
                                        params,
                                        session_state.clone(),
                                        runtime.map(|runtime| &runtime.notification_sender),
                                        bidirectional_senders.as_ref(),
                                    )
                                    .await?,
                            )
                            .map_err(McpError::from);
                        }
                        serde_json::to_value(
                            self.router
                                .handle_tools_call_in_request(
                                    &request_ctx,
                                    cx,
                                    params,
                                    session_state.clone(),
                                    runtime.map(|runtime| &runtime.notification_sender),
                                    bidirectional_senders.as_ref(),
                                )
                                .await?,
                        )
                        .map_err(McpError::from)
                    }
                    "resources/list" => {
                        let params: ListResourcesParams = parse_params_or_default(params)?;
                        serde_json::to_value(self.router.handle_resources_list(
                            &request_ctx,
                            params,
                            Some(&session_state),
                        )?)
                        .map_err(McpError::from)
                    }
                    "resources/templates/list" => {
                        let params: ListResourceTemplatesParams = parse_params_or_default(params)?;
                        serde_json::to_value(self.router.handle_resource_templates_list(
                            &request_ctx,
                            params,
                            Some(&session_state),
                        )?)
                        .map_err(McpError::from)
                    }
                    "resources/read" => {
                        let params: ReadResourceParams = parse_params(params)?;
                        serde_json::to_value(
                            self.router
                                .handle_resources_read_in_request(
                                    &request_ctx,
                                    cx,
                                    &params,
                                    session_state.clone(),
                                    runtime.map(|runtime| &runtime.notification_sender),
                                    bidirectional_senders.as_ref(),
                                )
                                .await?,
                        )
                        .map_err(McpError::from)
                    }
                    "prompts/list" => {
                        let params: ListPromptsParams = parse_params_or_default(params)?;
                        serde_json::to_value(self.router.handle_prompts_list(
                            &request_ctx,
                            params,
                            Some(&session_state),
                        )?)
                        .map_err(McpError::from)
                    }
                    "prompts/get" => {
                        let params: GetPromptParams = parse_params(params)?;
                        serde_json::to_value(
                            self.router
                                .handle_prompts_get_in_request(
                                    &request_ctx,
                                    cx,
                                    params,
                                    session_state,
                                    runtime.map(|runtime| &runtime.notification_sender),
                                    bidirectional_senders.as_ref(),
                                )
                                .await?,
                        )
                        .map_err(McpError::from)
                    }
                    "resources/subscribe" => {
                        let params: SubscribeResourceParams = parse_params(params)?;
                        let uri = params.uri;
                        if uri.len() > MAX_RESOURCE_SUBSCRIPTION_BYTES_PER_SESSION {
                            return Err(resource_subscription_capacity_error());
                        }
                        if !self.router.resource_exists(&uri) {
                            return Err(McpError::resource_not_found(&uri));
                        }
                        self.router
                            .notify_resource_subscribed_async(&request_ctx, &uri)
                            .await?;
                        Ok(serde_json::json!({}))
                    }
                    "resources/unsubscribe" => {
                        let params: UnsubscribeResourceParams = parse_params(params)?;
                        self.router
                            .notify_resource_unsubscribed_async(&request_ctx, &params.uri)
                            .await?;
                        Ok(serde_json::json!({}))
                    }
                    _ => Err(McpError::method_not_found(&request.method)),
                }
            }
            .await;

            let result = self.finalize_middleware_result(
                &request_cancellation,
                &entered_middleware,
                &request_ctx,
                &request,
                result,
            );

            if let Some(runtime) = runtime {
                self.maybe_emit_log_notification_for_level(
                    runtime.log_level(),
                    &runtime.notification_sender,
                    &request.method,
                    &result,
                );
            }

            match result {
                Ok(value) if value.get("resultType").is_some() => Err(mask_peer_error(
                    McpError::internal_error(
                        "modern result discriminator cannot cross the exact legacy bridge",
                    ),
                    self.mask_error_details,
                )),
                Ok(value) => Ok(value),
                Err(error) => Err(mask_peer_error(error, self.mask_error_details)),
            }
        }
        .await;

        Ok(LiveLegacy2024Dispatch {
            result,
            active_request: LiveLegacy2024ActiveRequest {
                cancellation: request_cancellation,
                active_guard,
                budget,
            },
        })
    }

    /// Rejects a final Tasks subscription request before the admitted HTTP
    /// response representation can commit or dispatch request-scoped SSE
    /// output. Tool outcome capability admission stays in router dispatch so
    /// disabled-tool, schema, and complete-outcome precedence remains exact.
    fn preflight_modern_http_required_capability(
        &self,
        request: &JsonRpcRequest,
    ) -> Option<JsonRpcResponse> {
        #[cfg(feature = "tasks")]
        {
            let admission = self.preflight_final_http_subscription_required_capability(request);
            if let Err(error) = admission
                && is_canonical_missing_required_client_capability_error(&error)
            {
                return request.id.clone().map(|id| {
                    JsonRpcResponse::error(
                        Some(id),
                        JsonRpcError {
                            code: error.code.into(),
                            message: error.message,
                            data: error.data,
                        },
                    )
                });
            }
        }
        #[cfg(not(feature = "tasks"))]
        let _ = request;
        None
    }

    #[cfg(feature = "tasks")]
    fn preflight_final_http_subscription_required_capability(
        &self,
        request: &JsonRpcRequest,
    ) -> McpResult<()> {
        if request.method != SUBSCRIPTIONS_LISTEN
            || modern_protocol_version(request) != Some(MODERN_PROTOCOL_VERSION)
        {
            return Ok(());
        }
        let Some(params) = request.params.clone() else {
            return Ok(());
        };
        let Ok(params) = serde_json::from_value::<FinalSubscriptionsListenParams>(params) else {
            return Ok(());
        };
        let Ok(Some(client_capabilities)) = params.meta.client_capabilities() else {
            return Ok(());
        };
        self.admit_final_task_subscription(&params.notifications, client_capabilities)
            .map(|_| ())
    }

    /// Processes a modern request under an explicit protocol policy.
    ///
    /// `ModernOnly` declines every request that lacks the exact final-era
    /// marker before parameter decoding or any legacy session lookup. Final
    /// `server/discover` remains a valid first request when it carries that
    /// marker.
    #[must_use]
    pub async fn dispatch_with_protocol_policy(
        &self,
        policy: ProtocolPolicy,
        inbound: &InboundRequestContext,
        request: &JsonRpcRequest,
    ) -> Option<JsonRpcResponse> {
        self.dispatch_with_protocol_policy_and_cancellation(
            policy, inbound, request, None, None, None, None,
        )
        .await
    }

    async fn dispatch_with_protocol_policy_and_cancellation(
        &self,
        policy: ProtocolPolicy,
        inbound: &InboundRequestContext,
        request: &JsonRpcRequest,
        request_cancellation: Option<McpRequestCancellation>,
        raw_params: Option<&str>,
        auth_receipt: Option<&AuthDispatchCustody>,
        websocket_connection_generation: Option<u64>,
    ) -> Option<JsonRpcResponse> {
        if matches!(policy, ProtocolPolicy::LegacyOnly)
            && modern_protocol_version(request).is_some()
        {
            return legacy_only_modern_refusal(request);
        }
        if matches!(policy, ProtocolPolicy::ModernOnly)
            && modern_protocol_version(request) != Some(MODERN_PROTOCOL_VERSION)
        {
            if request.method != "initialize"
                || request.validate().is_err()
                || inbound.request_id() != request_id_to_u64(request.id.as_ref())
            {
                return protocol_era_refusal(request);
            }
            return request.id.clone().map(|id| {
                JsonRpcResponse::error(
                    Some(id),
                    JsonRpcError {
                        code: (-32601).into(),
                        message: MODERN_ONLY_INITIALIZE_MESSAGE.to_owned(),
                        data: Some(serde_json::json!({ "supported": ["2026-07-28"] })),
                    },
                )
            });
        }
        self.dispatch_stateless_with_cancellation(
            inbound,
            request,
            request_cancellation,
            raw_params,
            auth_receipt,
            websocket_connection_generation,
        )
        .await
    }

    /// Maps an explicit-policy modern dispatch result onto the HTTP response
    /// status required for an explicit-policy cross-era refusal.
    ///
    /// The transport still owns raw HTTP parsing, origin checks, and
    /// authentication before it constructs [`InboundRequestContext`]. This
    /// helper owns only the transport-neutral JSON-RPC result and its final
    /// HTTP status mapping.
    #[must_use]
    pub async fn dispatch_http_with_protocol_policy(
        &self,
        policy: ProtocolPolicy,
        inbound: &InboundRequestContext,
        request: &JsonRpcRequest,
    ) -> HttpResponse {
        let is_modern_http_request =
            modern_protocol_version(request) == Some(MODERN_PROTOCOL_VERSION);
        let is_cross_era_request = (matches!(policy, ProtocolPolicy::LegacyOnly)
            && modern_protocol_version(request).is_some())
            || (matches!(policy, ProtocolPolicy::ModernOnly)
                && modern_protocol_version(request) != Some(MODERN_PROTOCOL_VERSION));
        match self
            .dispatch_with_protocol_policy(policy, inbound, request)
            .await
        {
            Some(response)
                if is_cross_era_request
                    || is_modern_http_request
                        && (is_canonical_missing_required_client_capability_response(
                            &response,
                        ) || is_parameter_header_mismatch_response(&response)) =>
            {
                HttpResponse::new(HttpStatus::BAD_REQUEST).with_json(&response)
            }
            Some(response) if is_modern_http_request && is_method_not_found_response(&response) => {
                HttpResponse::new(HttpStatus::NOT_FOUND).with_json(&response)
            }
            Some(response) => HttpResponse::ok().with_json(&response),
            None => HttpResponse::new(HttpStatus::ACCEPTED),
        }
    }

    /// Processes a single JSON-RPC request through the full server dispatch
    /// pipeline (initialization checks, middleware, routing, tool/resource/prompt
    /// execution, error masking, and statistics recording).
    ///
    /// This is the public equivalent of the internal `handle_request` method that
    /// the stdio and custom transport paths use. It allows
    /// external code to drive the server from a custom transport or embedding
    /// without going through a `Transport` abstraction.
    ///
    /// # Parameters
    ///
    /// - `cx` — The cancellation / budget context for this request.
    /// - `session` — Mutable reference to the session for this connection.
    ///   The caller is responsible for session lifecycle (creation, sharing,
    ///   locking if shared across threads).
    /// - `request` — The incoming JSON-RPC request (or notification).
    /// - `notification_sender` — Callback used to push server-initiated
    ///   notifications (e.g. progress) back to the client.
    /// - `request_sender` — Sender for server-to-client requests
    ///   (sampling, elicitation, roots).
    ///
    /// # Returns
    ///
    /// `Some(JsonRpcResponse)` for normal requests, or `None` for
    /// notifications (JSON-RPC messages without an `id`).
    ///
    /// # Example
    ///
    /// ```ignore
    /// use std::sync::Arc;
    /// use fastmcp_rust::{
    ///     Server, Session, JsonRpcRequest, NotificationSender,
    ///     bidirectional::RequestSender,
    /// };
    /// use fastmcp_core::Cx;
    ///
    /// let server = Arc::new(
    ///     Server::new("my-server", "1.0.0").build(),
    /// );
    /// let mut session = Session::new();
    /// let cx = Cx::for_request();
    /// let notify: NotificationSender = Arc::new(|_| {});
    /// let req_sender = RequestSender::noop();
    ///
    /// let request: JsonRpcRequest = /* ... */;
    /// let response = server
    ///     .dispatch_request(&cx, &mut session, request, &notify, &req_sender)
    ///     .await;
    /// ```
    pub async fn dispatch_request(
        &self,
        cx: &Cx,
        session: &mut Session,
        request: JsonRpcRequest,
        notification_sender: &NotificationSender,
        request_sender: &bidirectional::RequestSender,
    ) -> Option<JsonRpcResponse> {
        self.handle_request(cx, session, request, notification_sender, request_sender)
            .await
    }

    /// Runs the server on stdio with a provided Cx.
    ///
    /// The application owns the runtime and must configure a blocking pool
    /// for the receive pump. This method does not create or re-enter a runtime.
    ///
    /// On Unix, the receive pump uses readiness polling so cancellation from a
    /// failed dispatch worker remains observable while stdin is silent or a
    /// pipe frame is incomplete. Unix responses use nonblocking writes with a
    /// bounded commit deadline for ordinary pipes and sockets; regular files
    /// and some devices may ignore `O_NONBLOCK`. Other targets use the
    /// sequential server loop: that avoids a worker failing while the receive
    /// side is blocked, but generic blocking stdin reads and stdout writes
    /// remain observable only at frame boundaries or I/O completion.
    ///
    /// If an arbitrary handler does not quiesce within the bounded worker
    /// shutdown deadline, the process exits unsuccessfully without running the
    /// shutdown hook; running a hook concurrently with a live handler would
    /// violate the hook's quiescence contract.
    pub async fn run_stdio_with_cx(self, cx: &Cx) -> ! {
        let dispatch_cx = cx.clone();
        let mut pump =
            match cx.spawn_blocking(move |pump_cx| self.run_stdio_pump(&pump_cx, &dispatch_cx)) {
                Ok(pump) => pump,
                Err(error) => {
                    error!(
                        target: targets::SERVER,
                        "Could not admit the stdio pump into the caller runtime: {error}"
                    );
                    std::process::exit(1);
                }
            };
        let exit_code = match pump.join(cx).await {
            Ok(exit_code) => exit_code,
            Err(error) => {
                error!(
                    target: targets::SERVER,
                    "Caller-owned stdio pump ended without a final status: {error:?}"
                );
                1
            }
        };
        std::process::exit(exit_code)
    }

    fn run_stdio_pump(self, cx: &Cx, dispatch_cx: &Cx) -> i32 {
        // Initialize rich logging first, before any log output
        self.init_rich_logging();

        let mut transport = StdioTransport::stdio();
        let mut stdout = AsyncStdout::new();
        let codec = Codec::new();

        // Create a notification sender that writes to a separate stdout handle.
        // This allows progress notifications to be sent during handler execution
        // while the main transport is blocked on recv().
        let fatal_notification_output = Arc::new(AtomicBool::new(false));
        let notification_sender =
            create_notification_sender(Arc::clone(&fatal_notification_output));

        #[cfg(unix)]
        {
            let receive_fatal_output = Arc::clone(&fatal_notification_output);
            let send_fatal_output = Arc::clone(&fatal_notification_output);
            self.run_loop_with_dispatch_cx(
                cx,
                dispatch_cx,
                move |cx, worker_failed| {
                    transport.recv_until_or_stopped(cx, None, || {
                        if receive_fatal_output.load(Ordering::Acquire) {
                            worker_failed.store(true, Ordering::Release);
                            true
                        } else {
                            worker_failed.load(Ordering::Acquire)
                        }
                    })
                },
                move |cx, message| {
                    if send_fatal_output.load(Ordering::Acquire) || cx.checkpoint().is_err() {
                        return Err(TransportError::Cancelled);
                    }
                    let bytes = match message {
                        JsonRpcMessage::Request(request) => codec.encode_request(request)?,
                        JsonRpcMessage::Response(response) => codec.encode_response(response)?,
                    };
                    stdout.write_all_bounded(&bytes, STDIO_OUTPUT_COMMIT_TIMEOUT)?;
                    Ok(())
                },
                notification_sender,
                Arc::clone(&fatal_notification_output),
                "stdio",
            )
        }

        #[cfg(not(unix))]
        {
            let receive_fatal_output = Arc::clone(&fatal_notification_output);
            let send_fatal_output = Arc::clone(&fatal_notification_output);
            self.run_loop_with_dispatch_cx(
                cx,
                dispatch_cx,
                move |cx, worker_failed| {
                    if receive_fatal_output.load(Ordering::Acquire) {
                        worker_failed.store(true, Ordering::Release);
                        return Err(TransportError::Io(std::io::Error::other(
                            "notification output failed",
                        )));
                    }
                    let result = transport.recv(cx);
                    if receive_fatal_output.load(Ordering::Acquire) {
                        // Generic non-Unix reads cannot be interrupted once
                        // blocked, but the fatal latch must still dominate a
                        // concurrently completed frame or clean EOF.
                        worker_failed.store(true, Ordering::Release);
                        Err(TransportError::Io(std::io::Error::other(
                            "notification output failed",
                        )))
                    } else {
                        result
                    }
                },
                move |cx, message| {
                    if send_fatal_output.load(Ordering::Acquire) || cx.checkpoint().is_err() {
                        return Err(TransportError::Cancelled);
                    }
                    let bytes = match message {
                        JsonRpcMessage::Request(request) => codec.encode_request(request)?,
                        JsonRpcMessage::Response(response) => codec.encode_response(response)?,
                    };
                    stdout.write_all_unchecked(&bytes)?;
                    stdout.flush_unchecked()?;
                    Ok(())
                },
                notification_sender,
                Arc::clone(&fatal_notification_output),
                "stdio",
            )
        }
    }

    /// Runs the server on a custom transport with a provided Cx.
    ///
    /// This allows integration with a real asupersync runtime.
    ///
    /// ```compile_fail
    /// use fastmcp_server::Server;
    /// use fastmcp_transport::Transport;
    ///
    /// fn omitted_context<T>(server: Server, transport: T)
    /// where
    ///     T: Transport + Send + 'static,
    /// {
    ///     server.run_transport(transport);
    /// }
    /// ```
    pub fn run_transport_with_cx<T>(self, cx: &Cx, transport: T) -> !
    where
        T: Transport + Send + 'static,
    {
        self.run_transport_with_label(cx, transport, "custom")
    }

    fn run_transport_with_label<T>(self, cx: &Cx, transport: T, label: &'static str) -> !
    where
        T: Transport + Send + 'static,
    {
        self.init_rich_logging();

        let notification_failure = Arc::new(AtomicBool::new(false));
        let shared =
            SharedTransport::with_output_failure(transport, Arc::clone(&notification_failure));
        let notification_sender = create_transport_notification_sender(
            shared.clone(),
            cx.clone(),
            Arc::clone(&notification_failure),
        );

        let shared_recv = shared.clone();
        let shared_send = shared.clone();
        #[cfg(feature = "legacy-2024-11-05")]
        let run_result = self.run_loop_returning(
            cx,
            move |cx| shared_recv.recv(cx),
            move |cx, message| shared_send.send(cx, message),
            notification_sender,
            Some(notification_failure),
            label,
        );
        #[cfg(not(feature = "legacy-2024-11-05"))]
        let run_result = match Arc::new(self).run_loop_pump_with_policy(
            cx,
            cx,
            move |cx, _worker_failed| shared_recv.recv(cx),
            move |cx, message| shared_send.send(cx, message),
            notification_sender,
            label,
            true,
            Some(notification_failure),
            true,
            true,
            None,
            None,
            None,
            PumpIoMode::Unsplit,
        ) {
            0 => Ok(()),
            _ => Err(server_run_error(
                "transport",
                "pump_failure",
                "Server transport loop failed",
            )),
        };
        let close_result = shared
            .close(cx)
            .map_err(|error| transport_run_error("close", &error));
        let result = match (run_result, close_result) {
            (Ok(()), Ok(())) => Ok(()),
            (Err(error), Ok(())) | (Ok(()), Err(error)) => Err(error),
            (Err(run_error), Err(close_error)) => {
                Err(combined_run_and_close_error(run_error, close_error))
            }
        };
        let exit_code = match result {
            Ok(()) => 0,
            Err(error) => {
                error!(
                    target: targets::TRANSPORT,
                    "Server transport terminated with error: {error:?}"
                );
                1
            }
        };
        std::process::exit(exit_code)
    }

    /// Runs the server on a custom transport until clean closure, cancellation,
    /// or failure.
    ///
    /// Unlike [`run_transport_with_cx`](Self::run_transport_with_cx), this does not call
    /// `std::process::exit` on shutdown. This is useful for tests and embedding where you need
    /// the server loop to be joinable. Clean EOF and cancellation return
    /// `Ok(())` when request cleanup quiesces; bounded non-quiescent cleanup,
    /// startup, protocol, fatal receive, and fatal send failures return an
    /// error.
    /// Transport failures carry fixed `stage` and `kind` fields in the error
    /// data without copying peer-controlled I/O or codec text.
    ///
    /// This entry point and [`Transport::recv`] are synchronous. When the
    /// caller uses an async runtime, run this loop through [`Cx::spawn_blocking`],
    /// pass the closure's child context here, and await its task handle from
    /// the caller. Calling the loop directly on a cooperative runtime worker
    /// can prevent that same runtime from polling the request children.
    ///
    /// An unsplit transport cannot write while its `recv` blocks. Output that
    /// request workers produce in that window (subscription acknowledgements,
    /// notifications, responses) is queued in order and written as soon as
    /// `recv` returns. Use [`Server::run_split_transport_returning_with_cx`]
    /// when that output must not wait for the next inbound frame.
    ///
    /// # Errors
    ///
    /// Returns an error when startup fails, a fatal receive/protocol failure is
    /// observed, request cleanup remains non-quiescent at its finite bound,
    /// the server cannot send a required response, or transport close fails.
    /// Simultaneous operation, cleanup, and close failures retain structured
    /// nested evidence under `data.run` and `data.close`.
    ///
    /// ```compile_fail
    /// use fastmcp_server::Server;
    /// use fastmcp_transport::Transport;
    ///
    /// fn omitted_context<T>(server: Server, transport: T)
    /// where
    ///     T: Transport + Send + 'static,
    /// {
    ///     server.run_transport_returning(transport);
    /// }
    /// ```
    pub fn run_transport_returning_with_cx<T>(self, cx: &Cx, transport: T) -> McpResult<()>
    where
        T: Transport + Send + 'static,
    {
        self.init_rich_logging();

        let notification_failure = Arc::new(AtomicBool::new(false));
        let shared =
            SharedTransport::with_output_failure(transport, Arc::clone(&notification_failure));
        let notification_sender = create_transport_notification_sender(
            shared.clone(),
            cx.clone(),
            Arc::clone(&notification_failure),
        );

        let shared_recv = shared.clone();
        let shared_send = shared.clone();
        let run_result = self.run_loop_returning(
            cx,
            move |cx| shared_recv.recv(cx),
            move |cx, message| shared_send.send(cx, message),
            notification_sender,
            Some(notification_failure),
            "custom",
        );
        let close_result = shared
            .close(cx)
            .map_err(|error| transport_run_error("close", &error));
        match (run_result, close_result) {
            (Ok(()), Ok(())) => Ok(()),
            (Err(error), Ok(())) | (Ok(()), Err(error)) => Err(error),
            (Err(run_error), Err(close_error)) => {
                Err(combined_run_and_close_error(run_error, close_error))
            }
        }
    }

    /// Runs independently owned receive and send halves under the dual-era dispatcher.
    ///
    /// Modern requests receive bounded request-owned child contexts and may
    /// progress while the receive half blocks for another frame. Exact
    /// MCP 2024-11-05 traffic remains serialized through its lifecycle adapter.
    /// Use this entry point for genuinely full-duplex transports; an unsplit
    /// [`Transport`] cannot safely promise concurrent receive and response I/O.
    ///
    /// Shutdown retains ownership of the dispatch worker. If an arbitrary
    /// handler ignores cancellation past the bounded shutdown deadline, this
    /// returning API continues waiting for that worker to quiesce instead of
    /// orphaning it merely to return. Once it does quiesce, the call reports
    /// the timeout failure and then performs the normal owned cleanup.
    pub fn run_split_transport_returning_with_cx<R, S>(
        self,
        cx: &Cx,
        recv_half: R,
        send_half: S,
    ) -> McpResult<()>
    where
        R: TransportRecvHalf + Send + 'static,
        S: TransportSendHalf + 'static,
    {
        self.run_split_transport_returning_with_dispatch_cx(cx, cx, recv_half, send_half)
    }

    /// Runs independently owned receive and send halves with an explicit
    /// caller-owned context for modern request dispatch.
    ///
    /// A split receive pump may itself be placed on the caller's blocking
    /// pool. In that arrangement `pump_cx` owns ingress cancellation, while
    /// `dispatch_cx` must remain the runtime context that owns the blocking
    /// pool used by concurrent modern request children.
    pub fn run_split_transport_returning_with_dispatch_cx<R, S>(
        self,
        pump_cx: &Cx,
        dispatch_cx: &Cx,
        recv_half: R,
        send_half: S,
    ) -> McpResult<()>
    where
        R: TransportRecvHalf + Send + 'static,
        S: TransportSendHalf + 'static,
    {
        self.init_rich_logging();
        let recv_half = SharedRecvHalf::new(recv_half);
        let send_half = SharedSendHalf::new(send_half);
        let notification_failure = Arc::new(AtomicBool::new(false));
        let notification_sender = create_split_transport_notification_sender(
            send_half.clone(),
            pump_cx.clone(),
            Arc::clone(&notification_failure),
        );

        let recv_for_run = recv_half.clone();
        let send_for_run = send_half.clone();
        let run_result = self.run_loop_returning_with_dispatch_cx(
            pump_cx,
            dispatch_cx,
            move |cx, _worker_failed| recv_for_run.recv(cx),
            move |cx, message| send_for_run.send(cx, message),
            notification_sender,
            Some(notification_failure),
            "split-custom",
        );
        let recv_close = recv_half
            .close(pump_cx)
            .map_err(|error| transport_run_error("receive_close", &error));
        let send_close = send_half
            .close(pump_cx)
            .map_err(|error| transport_run_error("send_close", &error));
        combine_split_transport_results(run_result, recv_close, send_close)
    }

    #[cfg(feature = "websocket")]
    fn run_split_transport_returning_shared_with_dispatch_cx<R, S>(
        self: Arc<Self>,
        pump_cx: &Cx,
        dispatch_cx: &Cx,
        recv_half: R,
        send_half: S,
        transport_authorization: TransportAuthorization,
        auth_receipt: AuthDispatchCustody,
        websocket_connection_generation: u64,
    ) -> McpResult<()>
    where
        R: TransportRecvHalf + Send + 'static,
        S: TransportSendHalf + 'static,
    {
        let recv_half = SharedRecvHalf::new(recv_half);
        let send_half = SharedSendHalf::new(send_half);
        let notification_failure = Arc::new(AtomicBool::new(false));
        let notification_sender = create_split_transport_notification_sender(
            send_half.clone(),
            pump_cx.clone(),
            Arc::clone(&notification_failure),
        );
        let recv_for_run = recv_half.clone();
        let send_for_run = send_half.clone();
        let run_result = self.run_loop_returning_shared_with_dispatch_cx(
            pump_cx,
            dispatch_cx,
            move |cx, _worker_failed| recv_for_run.recv(cx),
            move |cx, message| send_for_run.send(cx, message),
            notification_sender,
            Some(notification_failure),
            "websocket",
            transport_authorization,
            auth_receipt,
            websocket_connection_generation,
        );
        let recv_close = recv_half
            .close(pump_cx)
            .map_err(|error| transport_run_error("receive_close", &error));
        let send_close = send_half
            .close(pump_cx)
            .map_err(|error| transport_run_error("send_close", &error));
        combine_split_transport_results(run_result, recv_close, send_close)
    }

    #[cfg(feature = "legacy-2024-11-05")]
    async fn run_split_transport_with_label<R, S>(
        self,
        cx: &Cx,
        recv_half: R,
        send_half: S,
        transport_label: &'static str,
    ) -> !
    where
        R: TransportRecvHalf + Send + 'static,
        S: TransportSendHalf + 'static,
    {
        let dispatch_cx = cx.clone();
        let mut pump = match cx.spawn_blocking(move |pump_cx| {
            self.run_split_transport_returning_with_dispatch_cx(
                &pump_cx,
                &dispatch_cx,
                recv_half,
                send_half,
            )
        }) {
            Ok(pump) => pump,
            Err(error) => {
                error!(
                    target: targets::SERVER,
                    "Could not admit the {transport_label} split transport pump into the caller runtime: {error}"
                );
                std::process::exit(1);
            }
        };
        let exit_code = match pump.join(cx).await {
            Ok(Ok(())) => 0,
            Ok(Err(error)) => {
                error!(
                    target: targets::SERVER,
                    "{transport_label} split transport pump failed: {error}"
                );
                1
            }
            Err(error) => {
                error!(
                    target: targets::SERVER,
                    "Caller-owned {transport_label} split transport pump ended without a final status: {error:?}"
                );
                1
            }
        };
        std::process::exit(exit_code)
    }

    /// Runs the server using SSE transport with a provided Cx.
    ///
    /// ```compile_fail
    /// use fastmcp_server::Server;
    /// use std::io::Write;
    ///
    /// fn omitted_context<W, R>(server: Server, writer: W, requests: R)
    /// where
    ///     W: Write + Send + 'static,
    ///     R: Iterator<Item = fastmcp_protocol::JsonRpcRequest> + Send + 'static,
    /// {
    ///     server.run_sse(writer, requests, "http://localhost/events");
    /// }
    /// ```
    #[cfg(feature = "legacy-2024-11-05")]
    pub async fn run_sse_with_cx<W, R>(
        self,
        cx: &Cx,
        writer: W,
        request_source: R,
        endpoint_url: impl Into<String>,
    ) -> !
    where
        W: Write + Send + 'static,
        R: Iterator<Item = JsonRpcRequest> + Send + 'static,
    {
        let (recv_half, send_half) =
            SseServerTransport::new(writer, request_source, endpoint_url).into_split();
        self.run_split_transport_with_label(cx, recv_half, send_half, "sse")
            .await
    }

    // =========================================================================
    // HTTP Server — caller-owned asupersync HTTP/1.1 lifecycle
    // =========================================================================

    /// Runs the turnkey dual-era HTTP server on a caller-owned [`Cx`].
    ///
    /// This is an async lifecycle rather than a runtime constructor: callers
    /// drive it from their existing asupersync region and retain cancellation,
    /// deadlines, and task ownership throughout socket acceptance.
    pub async fn run_http(self, cx: &Cx, addr: impl Into<String>) -> McpResult<HttpServerShutdown> {
        self.serve_http(cx, addr).await
    }

    /// Named compatibility entry point for callers that already pass a
    /// context. It is exactly [`Self::run_http`] and never creates a runtime.
    pub async fn run_http_with_cx(
        self,
        cx: &Cx,
        addr: impl Into<String>,
    ) -> McpResult<HttpServerShutdown> {
        self.serve_http(cx, addr).await
    }

    /// Returning form of [`Self::run_http`] for embedders that select the
    /// shutdown boundary themselves.
    pub async fn run_http_returning(
        self,
        cx: &Cx,
        addr: impl Into<String>,
    ) -> McpResult<HttpServerShutdown> {
        self.serve_http(cx, addr).await
    }

    /// Returning form with an explicit caller-owned context.
    pub async fn run_http_returning_with_cx(
        self,
        cx: &Cx,
        addr: impl Into<String>,
    ) -> McpResult<HttpServerShutdown> {
        self.serve_http(cx, addr).await
    }

    fn configured_http_request_handler(&self) -> HttpRequestHandler {
        HttpRequestHandler::with_config(self.http_config.handler_config.clone())
    }

    /// Runs the startup lifecycle hook, if configured.
    ///
    /// Returns `true` if startup succeeded (or no hook was configured),
    /// `false` if the hook returned an error.
    pub(crate) fn run_startup_hook(&self) -> bool {
        let hook = {
            let mut guard = self.lifespan.lock().unwrap_or_else(|poisoned| {
                error!(target: targets::SERVER, "lifespan lock poisoned in run_startup_hook, recovering");
                poisoned.into_inner()
            });
            guard.as_mut().and_then(|h| h.on_startup.take())
        };

        if let Some(hook) = hook {
            debug!(target: targets::SERVER, "Running startup hook");
            match catch_extension_unwind(hook) {
                Ok(Ok(())) => {
                    debug!(target: targets::SERVER, "Startup hook completed successfully");
                    true
                }
                Ok(Err(e)) => {
                    error!(target: targets::SERVER, "Startup hook failed: {}", e);
                    false
                }
                Err(_payload) => {
                    let _ = extension_panic_error("startup_hook");
                    false
                }
            }
        } else {
            true
        }
    }

    /// Runs the shutdown lifecycle hook, if configured.
    pub(crate) fn run_shutdown_hook(&self) {
        let hook = {
            let mut guard = self.lifespan.lock().unwrap_or_else(|poisoned| {
                error!(target: targets::SERVER, "lifespan lock poisoned in run_shutdown_hook, recovering");
                poisoned.into_inner()
            });
            guard.as_mut().and_then(|h| h.on_shutdown.take())
        };

        if let Some(hook) = hook {
            debug!(target: targets::SERVER, "Running shutdown hook");
            if catch_extension_unwind(hook).is_err() {
                let _ = extension_panic_error("shutdown_hook");
            } else {
                debug!(target: targets::SERVER, "Shutdown hook completed");
            }
        }
    }

    /// Performs graceful shutdown without exiting the process.
    ///
    /// This is intended for embedding/testing scenarios where the server loop is
    /// running on a thread and the caller wants to `join()` it.
    fn graceful_shutdown_returning(&self) -> ShutdownCleanupOutcome {
        // Preserve the same graceful subscription completion semantics for
        // embedded servers as for the process-exiting lifecycle.
        let _ = self.terminate_subscription_streams_for_shutdown();
        let cleanup = self.cancel_active_requests(CancelKind::Shutdown, true);
        if matches!(cleanup, ShutdownCleanupOutcome::Quiescent) {
            self.run_shutdown_hook();
        } else {
            error!(
                target: targets::SESSION,
                "Skipping shutdown hook because active request cleanup did not quiesce"
            );
        }
        if let Some(ref stats) = self.stats {
            stats.connection_closed();
        }
        cleanup
    }

    /// Runs a continuous receive pump. Exact-2024 frames retain the one
    /// lifecycle-preserving worker; modern frames use bounded children of the
    /// caller context and may progress independently.
    fn run_loop_with_dispatch_cx<R, S>(
        self,
        pump_cx: &Cx,
        dispatch_cx: &Cx,
        recv: R,
        send: S,
        notification_sender: NotificationSender,
        connection_failure: Arc<AtomicBool>,
        transport_label: &'static str,
    ) -> i32
    where
        R: FnMut(&Cx, &AtomicBool) -> Result<JsonRpcMessage, TransportError>,
        S: FnMut(&Cx, &JsonRpcMessage) -> Result<(), TransportError> + Send + Sync + 'static,
    {
        Arc::new(self).run_loop_pump_with_policy(
            pump_cx,
            dispatch_cx,
            recv,
            send,
            notification_sender,
            transport_label,
            true,
            Some(connection_failure),
            true,
            true,
            None,
            None,
            None,
            PumpIoMode::Split,
        )
    }

    /// Returning counterpart of [`Self::run_loop_with_dispatch_cx`].
    ///
    /// Clean closure or cancellation returns `Ok(())`; any failing pump status
    /// is preserved as a local server-loop error. A receive implementation
    /// that can block must include the supplied worker-failure flag in its
    /// readiness/stop predicate. Modern requests establish a fresh stateless
    /// request scope; exact legacy traffic retains its isolated session path.
    /// Unlike the process-exiting stdio entry point, this returning helper
    /// never detaches a non-quiescent handler: after logging the bounded
    /// shutdown deadline it waits without a second deadline for the owned
    /// worker before running lifecycle hooks or returning to the caller.
    fn run_loop_returning_with_dispatch_cx<R, S>(
        self,
        pump_cx: &Cx,
        dispatch_cx: &Cx,
        mut recv: R,
        send: S,
        notification_sender: NotificationSender,
        connection_failure: Option<Arc<AtomicBool>>,
        transport_label: &'static str,
    ) -> McpResult<()>
    where
        R: FnMut(&Cx, &AtomicBool) -> Result<JsonRpcMessage, TransportError>,
        S: FnMut(&Cx, &JsonRpcMessage) -> Result<(), TransportError> + Send + Sync + 'static,
    {
        match Arc::new(self).run_loop_pump_with_policy(
            pump_cx,
            dispatch_cx,
            move |cx, worker_failed| recv(cx, worker_failed),
            send,
            notification_sender,
            transport_label,
            false,
            connection_failure,
            true,
            true,
            None,
            None,
            None,
            PumpIoMode::Split,
        ) {
            0 => Ok(()),
            _ => Err(server_run_error(
                "transport",
                "pump_failure",
                "Server transport loop failed",
            )),
        }
    }

    #[cfg(feature = "websocket")]
    fn run_loop_returning_shared_with_dispatch_cx<R, S>(
        self: Arc<Self>,
        pump_cx: &Cx,
        dispatch_cx: &Cx,
        mut recv: R,
        send: S,
        notification_sender: NotificationSender,
        connection_failure: Option<Arc<AtomicBool>>,
        transport_label: &'static str,
        transport_authorization: TransportAuthorization,
        auth_receipt: AuthDispatchCustody,
        websocket_connection_generation: u64,
    ) -> McpResult<()>
    where
        R: FnMut(&Cx, &AtomicBool) -> Result<JsonRpcMessage, TransportError>,
        S: FnMut(&Cx, &JsonRpcMessage) -> Result<(), TransportError> + Send + Sync + 'static,
    {
        match self.run_loop_pump_with_policy(
            pump_cx,
            dispatch_cx,
            move |cx, worker_failed| recv(cx, worker_failed),
            send,
            notification_sender,
            transport_label,
            false,
            connection_failure,
            true,
            false,
            Some(transport_authorization),
            Some(auth_receipt),
            Some(websocket_connection_generation),
            PumpIoMode::Split,
        ) {
            0 => Ok(()),
            _ => Err(server_run_error(
                "transport",
                "pump_failure",
                "Server transport loop failed",
            )),
        }
    }

    /// Feature-off stdio runner: only final-era envelopes can reach dispatch.
    ///
    /// Uses the shared bounded request admission and retains each child until
    /// it settles, without compiling a legacy adapter or reverse registry.
    /// The dual-era implementation below remains compiled only with the dated
    /// feature.
    #[cfg(not(feature = "legacy-2024-11-05"))]
    #[allow(clippy::too_many_arguments)]
    fn run_loop_pump_with_policy<R, S>(
        self: Arc<Self>,
        cx: &Cx,
        dispatch_cx: &Cx,
        mut recv: R,
        send: S,
        _notification_sender: NotificationSender,
        transport_label: &'static str,
        detach_on_worker_timeout: bool,
        connection_failure: Option<Arc<AtomicBool>>,
        enforce_runtime_era: bool,
        owns_server_lifecycle: bool,
        transport_authorization: Option<TransportAuthorization>,
        auth_receipt: Option<AuthDispatchCustody>,
        websocket_connection_generation: Option<u64>,
        io_mode: PumpIoMode,
    ) -> i32
    where
        R: FnMut(&Cx, &AtomicBool) -> Result<JsonRpcMessage, TransportError>,
        S: FnMut(&Cx, &JsonRpcMessage) -> Result<(), TransportError> + Send + Sync + 'static,
    {
        let server = self;
        let auth_custody_generation = websocket_connection_generation;
        if let Some(stats) = &server.stats {
            stats.connection_opened();
        }
        if server.console_config.show_banner && !banner_suppressed() {
            server.render_startup_banner(transport_label);
        }
        if owns_server_lifecycle && !server.run_startup_hook() {
            server.graceful_shutdown_returning();
            return 1;
        }
        #[cfg(feature = "tasks")]
        let hosted_task_service =
            match server.start_hosted_task_service_blocking(dispatch_cx, owns_server_lifecycle) {
                Ok(hosted) => hosted,
                Err(error) => {
                    error!(target: targets::SERVER, "Hosted Task service startup failed: {error}");
                    server.graceful_shutdown_returning();
                    return 1;
                }
            };

        let modern_connection = ModernConnection::new();
        let send = Arc::new(Mutex::new(send));
        let mut classifier = StdioEraClassifier::new(runtime_stdio_policy(server.protocol_policy));
        #[cfg(feature = "tasks")]
        let worker_failed = hosted_task_service.as_ref().map_or_else(
            || Arc::new(AtomicBool::new(false)),
            tasks::HostedTaskService::failure_signal,
        );
        #[cfg(not(feature = "tasks"))]
        let worker_failed = Arc::new(AtomicBool::new(false));
        let queue = Arc::new(DispatchQueueState::default());
        let mut children: Vec<asupersync::runtime::TaskHandle<()>> = Vec::new();
        let mut blocking_children: Vec<BlockingTaskGuard> = Vec::new();
        // A synchronous embedding can call this loop on the runtime's only
        // async worker. It cannot join a task scheduled on that same worker.
        // Use the existing bounded blocking bridge in that arrangement; the
        // split/stdio pump supplies a distinct dispatch Cx and uses async
        // children instead. Both paths retain the same admission ownership.
        let synchronous_dispatch =
            io_mode == PumpIoMode::Split && cx.task_id() == dispatch_cx.task_id();
        let mut negotiated_era = None;
        let mut exit_code = 0;
        let mut drain_responses = false;
        loop {
            blocking_children.retain(|child| !child.0.is_done());
            // Retain ownership until completion, but do not accumulate handles
            // over the lifetime of a long-running connection.
            for index in (0..children.len()).rev() {
                if children[index].is_finished() {
                    let mut child = children.swap_remove(index);
                    match poll_on_cx(cx, child.join(cx)) {
                        Ok(()) | Err(asupersync::runtime::JoinError::Cancelled(_)) => {}
                        Err(_) => worker_failed.store(true, Ordering::Release),
                    }
                }
            }
            if cx.checkpoint().is_err()
                || worker_failed.load(Ordering::Acquire)
                || connection_failure
                    .as_ref()
                    .is_some_and(|failed| failed.load(Ordering::Acquire))
            {
                break;
            }
            let message = match recv(cx, &worker_failed) {
                Ok(message) => message,
                Err(TransportError::Closed) => {
                    drain_responses = true;
                    break;
                }
                Err(TransportError::Cancelled) => break,
                Err(_) => {
                    exit_code = 1;
                    break;
                }
            };
            // A request child can fail its write while ingress is blocked.
            // Recheck before authenticating or admitting the returned frame.
            if worker_failed.load(Ordering::Acquire)
                || connection_failure
                    .as_ref()
                    .is_some_and(|failed| failed.load(Ordering::Acquire))
            {
                exit_code = 1;
                break;
            }
            let JsonRpcMessage::Request(request) = message else {
                continue;
            };
            if request.validate().is_err() {
                exit_code = 1;
                break;
            }
            if enforce_runtime_era && negotiated_era.is_none() {
                match classify_initial_stdio_envelope(
                    &mut classifier,
                    &JsonRpcMessage::Request(request.clone()),
                ) {
                    Ok(ProtocolEra::Modern2026) => negotiated_era = Some(ProtocolEra::Modern2026),
                    Err(decision) if opening_rejection_selected_modern(&decision) => {
                        negotiated_era = Some(ProtocolEra::Modern2026);
                    }
                    Ok(ProtocolEra::Legacy2024) | Err(_) => {
                        if let Some(response) = protocol_era_refusal(&request) {
                            let _ = send
                                .lock()
                                .unwrap_or_else(std::sync::PoisonError::into_inner)(
                                cx,
                                &JsonRpcMessage::Response(response),
                            );
                        }
                        exit_code = i32::from(owns_server_lifecycle);
                        drain_responses = true;
                        break;
                    }
                }
            }
            if negotiated_era == Some(ProtocolEra::Modern2026)
                && modern_protocol_version(&request) != Some(MODERN_PROTOCOL_VERSION)
            {
                // Stateless per-request admission: answer this request and
                // keep serving the stream.
                if let Some(response) = modern_request_version_refusal(&request)
                    && send
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)(
                        cx,
                        &JsonRpcMessage::Response(response),
                    )
                    .is_err()
                {
                    exit_code = 1;
                    break;
                }
                continue;
            }
            if negotiated_era != Some(ProtocolEra::Modern2026) {
                if let Some(response) = protocol_era_refusal(&request) {
                    let _ = send
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)(
                        cx,
                        &JsonRpcMessage::Response(response),
                    );
                }
                exit_code = i32::from(owns_server_lifecycle);
                drain_responses = true;
                break;
            }
            if admit_final_client_notification_ingress(&request).is_err() {
                continue;
            }
            // The request context is the DISPATCH runtime's, not the receive
            // pump's: under the stdio arrangement the pump is a blocking child
            // and cannot drive an async request child (GitHub #65).
            let inbound = InboundRequestContext::with_modern_connection_and_transport_authorization(
                dispatch_cx.clone(),
                request_id_to_u64(request.id.as_ref()),
                InboundRequestTransport::Stdio,
                &modern_connection,
                transport_authorization.clone().unwrap_or_default(),
            );
            if request.id.is_none() && request.method == "notifications/cancelled" {
                let mut request = request;
                if let Ok(cancellation) = server.authenticate_modern_cancelled_control(
                    &inbound,
                    &mut request,
                    auth_receipt.as_ref(),
                    auth_custody_generation,
                ) {
                    // Cancellation and final output elect their winner under
                    // the same writer fence. An unrelated ID changes nothing.
                    let _writer = send
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    queue.cancel_reserved(Self::cancellation_wire_request_id(&cancellation));
                }
                continue;
            }
            let admission = queue.admit_modern_request(&request, Arc::clone(&worker_failed));
            let mut reservation = match admission {
                Ok(reservation) => reservation,
                Err(error) => {
                    if let Some(id) = request.id {
                        let response = JsonRpcResponse::error(Some(id), error);
                        if send
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner)(
                            cx,
                            &JsonRpcMessage::Response(response),
                        )
                        .is_err()
                        {
                            exit_code = 1;
                            break;
                        }
                    }
                    continue;
                }
            };
            // A listen does not finish until it is terminated, so on an
            // unsplit transport it cannot run inline: the pump would stop
            // reading and never see the cancellation that ends it (bd-4crkf).
            let unsplit_listen =
                io_mode == PumpIoMode::Unsplit && request.method == SUBSCRIPTIONS_LISTEN;
            let blocking_permit =
                (synchronous_dispatch || unsplit_listen).then(try_reserve_blocking_dispatch);
            if matches!(blocking_permit, Some(None)) {
                if let Some(id) = request.id {
                    let response = JsonRpcResponse::error(
                        Some(id),
                        JsonRpcError {
                            code: RESOURCE_EXHAUSTED_ERROR_CODE.into(),
                            message: DISPATCH_QUEUE_CAPACITY_MESSAGE.to_owned(),
                            data: None,
                        },
                    );
                    if send
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)(
                        cx,
                        &JsonRpcMessage::Response(response),
                    )
                    .is_err()
                    {
                        exit_code = 1;
                        break;
                    }
                }
                continue;
            }
            // Establish ordinary-request ownership before reading the next
            // frame. A following cancellation must not depend on whether the
            // runtime has polled this child yet. Dispatch consumes the exact
            // private receipt, so the provider is evaluated only once.
            let task_auth_receipt = match server.admit_modern_pump_authentication(
                &inbound,
                &request,
                auth_receipt.as_ref(),
                auth_custody_generation,
            ) {
                Ok(receipt) => receipt,
                Err(error) => {
                    if let Some(id) = request.id {
                        let response = JsonRpcResponse::error(
                            Some(id),
                            JsonRpcError {
                                code: error.code.into(),
                                message: error.message,
                                data: error.data,
                            },
                        );
                        if send
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner)(
                            cx,
                            &JsonRpcMessage::Response(response),
                        )
                        .is_err()
                        {
                            exit_code = 1;
                            break;
                        }
                    }
                    continue;
                }
            };
            reservation.begin();
            let request_server = Arc::clone(&server);
            let request_send = Arc::clone(&send);
            let listen_opened = unsplit_listen.then(|| Arc::new(UnsplitListenOpened::default()));
            let listen_opened_by_dispatch = listen_opened.clone();
            let dispatch = move |request_cx: Cx| async move {
                let mut reservation = reservation;
                let cancellation = reservation.cancellation();
                let subscription_request = request.method == SUBSCRIPTIONS_LISTEN;
                let inbound = inbound.with_cx(request_cx.clone());
                let notification_send = Arc::clone(&request_send);
                let notification_cx = request_cx.clone();
                let notification_cancellation = cancellation.clone();
                let notification_failed = Arc::clone(&reservation.failed);
                let notification_opened = listen_opened_by_dispatch;
                #[cfg(test)]
                let notification_request_id = request_id_to_u64(request.id.as_ref());
                let committed_notifications: NotificationSender = Arc::new(move |notification| {
                    #[cfg(test)]
                    wait_for_stdio_progress_commit_fence(notification_request_id, &notification);
                    let acknowledgement = notification.method
                        == fastmcp_protocol::methods::NOTIFICATIONS_SUBSCRIPTIONS_ACKNOWLEDGED;
                    let mut writer = notification_send
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    if !notification_cancellation.is_cancel_requested()
                        && writer(&notification_cx, &JsonRpcMessage::Request(notification)).is_err()
                    {
                        notification_failed.store(true, Ordering::Release);
                        notification_cancellation.cancel();
                    }
                    drop(writer);
                    if acknowledgement && let Some(opened) = &notification_opened {
                        opened.fire();
                    }
                });
                let response = match reservation.queue.begin_modern_dispatch(request.id.as_ref()) {
                    ModernDispatchStart::Stopping => None,
                    ModernDispatchStart::Cancelled => request.id.clone().map(|id| {
                        JsonRpcResponse::error(
                            Some(id),
                            JsonRpcError {
                                code: McpErrorCode::RequestCancelled.into(),
                                message: "Request cancelled before dispatch".to_owned(),
                                data: None,
                            },
                        )
                    }),
                    ModernDispatchStart::Ready => {
                        Arc::clone(&request_server)
                            .dispatch_with_protocol_policy_owned(
                                request_server.protocol_policy,
                                &inbound,
                                request,
                                None,
                                Some(task_auth_receipt),
                                auth_custody_generation,
                                None,
                                cancellation.clone(),
                                None,
                                committed_notifications,
                            )
                            .await
                    }
                };
                if let Some(mut response) = response {
                    let mut writer = request_send
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    if !(subscription_request && final_subscription_completion_response(&response)
                        || cancellation.begin_finalization())
                    {
                        response = JsonRpcResponse::error(
                            response.id,
                            JsonRpcError {
                                code: McpErrorCode::RequestCancelled.into(),
                                message: "Request cancelled before response finalization"
                                    .to_owned(),
                                data: None,
                            },
                        );
                    }
                    if writer(&request_cx, &JsonRpcMessage::Response(response)).is_err() {
                        return;
                    }
                }
                reservation.disarm_failure();
            };
            if io_mode == PumpIoMode::Unsplit && !unsplit_listen {
                // An unsplit Transport holds one mutex during recv. Finish
                // its response before receiving again, otherwise that read
                // can lock out the response the peer is waiting for.
                poll_on_cx(dispatch_cx, dispatch(dispatch_cx.clone()));
                continue;
            }
            if let Some(Some(permit)) = blocking_permit {
                let request_cx = dispatch_cx.clone();
                // Fires when the task finishes or is dropped unrun, so the
                // pump never waits on a listen that ended before it
                // acknowledged.
                let listen_finished = listen_opened.clone().map(UnsplitListenOpenedOnDrop);
                blocking_children.push(BlockingTaskGuard(blocking_dispatch_pool().spawn(
                    move || {
                        let _permit = permit;
                        let _listen_finished = listen_finished;
                        // A pool thread is never the async driver (bd-6rfrg).
                        let _lane = fastmcp_core::runtime::enter_blocking_lane();
                        poll_on_cx(&request_cx, dispatch(request_cx.clone()));
                    },
                )));
                if let Some(opened) = &listen_opened {
                    // Output written while `recv` blocks waits for that recv
                    // to return, so let the listen's acknowledgement (or its
                    // early answer) go out before reading again.
                    opened.wait(cx, UNSPLIT_LISTEN_OPEN_TIMEOUT);
                }
                continue;
            }
            let submitted = dispatch_cx.spawn(dispatch);
            match submitted {
                Ok(child) => children.push(child),
                Err(_) => {
                    exit_code = 1;
                    break;
                }
            }
        }
        if owns_server_lifecycle {
            let _ = server.terminate_subscription_streams_for_shutdown();
        }
        queue.cancel_uncorrelated_modern_children();
        if drain_responses
            && !queue.wait_for_correlated_response_drain(DISPATCH_WORKER_SHUTDOWN_TIMEOUT)
        {
            exit_code = 1;
        }
        queue.stop();
        modern_connection.disconnect();
        if owns_server_lifecycle {
            server.cancel_active_requests(CancelKind::Shutdown, false);
        }
        let mut quiescent = queue.wait_for_modern_drain(DISPATCH_WORKER_SHUTDOWN_TIMEOUT);
        if !quiescent {
            exit_code = 1;
            if !detach_on_worker_timeout {
                queue.wait_for_modern_drain_unbounded();
                quiescent = true;
            }
        }
        #[cfg(feature = "tasks")]
        let task_service_succeeded =
            Self::settle_hosted_task_service_blocking(hosted_task_service).is_ok();
        #[cfg(not(feature = "tasks"))]
        let task_service_succeeded = true;
        if !task_service_succeeded {
            error!(target: targets::SERVER, "Hosted Task service did not settle successfully");
            exit_code = 1;
        }
        if quiescent {
            for child in blocking_children {
                child.0.wait();
            }
            for mut child in children {
                match poll_on_cx(cx, child.join(cx)) {
                    Ok(()) | Err(asupersync::runtime::JoinError::Cancelled(_)) => {}
                    Err(_) => exit_code = 1,
                }
            }
            if owns_server_lifecycle {
                server.run_shutdown_hook();
            }
        }
        if worker_failed.load(Ordering::Acquire)
            || connection_failure
                .as_ref()
                .is_some_and(|failed| failed.load(Ordering::Acquire))
        {
            exit_code = 1;
        }
        if let Some(stats) = &server.stats {
            stats.connection_closed();
        }
        exit_code
    }

    #[cfg(feature = "legacy-2024-11-05")]
    #[allow(clippy::too_many_lines)]
    fn run_loop_pump_with_policy<R, S>(
        self: Arc<Self>,
        cx: &Cx,
        dispatch_cx: &Cx,
        mut recv: R,
        send: S,
        notification_sender: NotificationSender,
        transport_label: &'static str,
        detach_on_worker_timeout: bool,
        connection_failure: Option<Arc<AtomicBool>>,
        enforce_runtime_era: bool,
        owns_server_lifecycle: bool,
        transport_authorization: Option<TransportAuthorization>,
        auth_receipt: Option<AuthDispatchCustody>,
        websocket_connection_generation: Option<u64>,
        _io_mode: PumpIoMode,
    ) -> i32
    where
        R: FnMut(&Cx, &AtomicBool) -> Result<JsonRpcMessage, TransportError>,
        S: FnMut(&Cx, &JsonRpcMessage) -> Result<(), TransportError> + Send + Sync + 'static,
    {
        if let Some(ref stats) = self.stats {
            stats.connection_opened();
        }

        let auth_custody_generation = websocket_connection_generation;
        if self.console_config.show_banner && !banner_suppressed() {
            self.render_startup_banner(transport_label);
        }
        if owns_server_lifecycle && !self.run_startup_hook() {
            error!(target: targets::SERVER, "Startup hook failed, stopping");
            self.graceful_shutdown_returning();
            return 1;
        }
        #[cfg(feature = "tasks")]
        let hosted_task_service =
            match self.start_hosted_task_service_blocking(dispatch_cx, owns_server_lifecycle) {
                Ok(hosted) => hosted,
                Err(error) => {
                    error!(target: targets::SERVER, "Hosted Task service startup failed: {error}");
                    self.graceful_shutdown_returning();
                    return 1;
                }
            };

        let traffic_renderer = self.configured_traffic_renderer();

        let server = self;
        let session = Session::new(server.info.clone(), server.capabilities.clone());
        let session_id = session.id();
        let session_principal = session.principal_binding();
        let send = Arc::new(Mutex::new(send));
        let queue_state = Arc::new(DispatchQueueState::default());
        #[cfg(feature = "tasks")]
        let worker_failed = hosted_task_service.as_ref().map_or_else(
            || Arc::new(AtomicBool::new(false)),
            tasks::HostedTaskService::failure_signal,
        );
        #[cfg(not(feature = "tasks"))]
        let worker_failed = Arc::new(AtomicBool::new(false));
        let pending_requests = Arc::new(
            PendingRequests::with_max_in_flight_for_exact_legacy(
                server.max_bidirectional_requests_per_connection,
            )
            .expect("ServerBuilder validates the bidirectional request limit"),
        );
        let legacy_request_sender = RequestSender::new(Arc::clone(&pending_requests), {
            let send = Arc::clone(&send);
            let request_cx = dispatch_cx.clone();
            Arc::new(move |message| {
                let mut send_guard = send
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                send_guard(&request_cx, message).map_err(|error| error.to_string())
            })
        });
        let legacy_runtime = LiveLegacy2024ConnectionRuntime::new(
            SessionState::new(),
            notification_sender,
            Some(legacy_request_sender),
            server.logging.level,
        );
        let modern_connection = ModernConnection::new();
        let worker_modern_connection = modern_connection.request_context();
        let dispatch_modern_connection = modern_connection.request_context();
        let (dispatch_sender, mut dispatch_receiver) =
            asupersync_mpsc::channel::<QueuedDispatchMessage>(MAX_DISPATCH_QUEUE_DEPTH);

        let worker_server = Arc::clone(&server);
        let worker_send = Arc::clone(&send);
        let worker_queue_state = Arc::clone(&queue_state);
        let worker_failed_flag = Arc::clone(&worker_failed);
        let worker_cx = cx.clone();
        let worker_renderer = traffic_renderer.clone();
        let worker_session_principal = session_principal.clone();
        let worker_legacy_runtime = legacy_runtime.clone();
        let worker_transport_authorization = transport_authorization.clone().unwrap_or_default();
        let worker_auth_receipt = auth_receipt.clone();
        let worker_auth_custody_generation = auth_custody_generation;
        let (worker_completion_sender, worker_completion_receiver) = std::sync::mpsc::channel();
        let worker = std::thread::spawn(move || {
            // This dedicated thread is never the async driver: the receive
            // pump routes matched reverse responses into `pending_requests` on
            // its own thread. A handler that bridges sampling, elicitation or
            // roots here therefore cannot starve its own completion, so declare
            // the lane or bd-6rfrg's detection rejects a working call.
            let _lane = fastmcp_core::runtime::enter_blocking_lane();
            let _completion = DispatchWorkerCompletionSignal(Some(worker_completion_sender));
            let mut failure_latch = DispatchWorkerFailureLatch::new(
                Arc::clone(&worker_failed_flag),
                Arc::clone(&worker_queue_state),
            );
            let mut session = session;
            let legacy_binding = runtime_legacy_binding(session.id());
            let mut legacy_adapter: Option<
                Legacy2024ServerAdapter<LiveLegacy2024RuntimeHandler<'_>>,
            > = None;
            let legacy_active_request = Arc::new(Mutex::new(None));
            let mut clean_exit = false;
            loop {
                if worker_queue_state.is_stopping() {
                    clean_exit = true;
                    break;
                }
                let queued_message = match dispatch_receiver.try_recv() {
                    Ok(request) => request,
                    Err(asupersync_mpsc::RecvError::Empty) => {
                        if worker_queue_state.is_stopping() {
                            clean_exit = true;
                            break;
                        }
                        std::thread::sleep(Duration::from_millis(1));
                        continue;
                    }
                    Err(
                        asupersync_mpsc::RecvError::Disconnected
                        | asupersync_mpsc::RecvError::Cancelled,
                    ) => {
                        clean_exit = worker_queue_state.is_stopping();
                        break;
                    }
                };
                let queued_request = match queued_message {
                    QueuedDispatchMessage::LegacyResponse(response) => {
                        let Some(adapter) = legacy_adapter.as_mut() else {
                            break;
                        };
                        if !legacy_adapter_accept_response(adapter, legacy_binding, &response) {
                            break;
                        }
                        continue;
                    }
                    QueuedDispatchMessage::Request(request) => request,
                };
                worker_queue_state.release_queued_bytes(queued_request.serialized_bytes);
                let era = queued_request.era;
                let request = queued_request.request;
                match queued_request
                    .principal_admission
                    .wait_timeout(DISPATCH_WORKER_SHUTDOWN_TIMEOUT)
                {
                    Some(true) => {}
                    Some(false) => {
                        if let Some(id) = request.id.as_ref() {
                            worker_queue_state.discard(id);
                        }
                        continue;
                    }
                    None => {
                        if let Some(id) = request.id.as_ref() {
                            worker_queue_state.discard(id);
                        }
                        break;
                    }
                }

                // The hand-off from the receive queue to the worker is the
                // linearization point for cancellation. Mark it before any
                // further branch so a later cancellation targets an active
                // request rather than silently cancelling a dequeued one.
                let cancelled_before_dispatch = request
                    .id
                    .as_ref()
                    .is_some_and(|id| worker_queue_state.begin_dispatch(id));

                if worker_queue_state.is_stopping() {
                    if let Some(id) = request.id.as_ref() {
                        worker_queue_state.discard(id);
                    }
                    clean_exit = true;
                    break;
                }

                if cancelled_before_dispatch {
                    if let Some(id) = request.id.as_ref() {
                        if matches!(era, ProtocolEra::Legacy2024) {
                            // Exact MCP 2024-11-05 treats an accepted
                            // cancellation as the peer relinquishing its
                            // response. The queued request never executes and
                            // no synthetic RequestCancelled response is sent.
                            worker_queue_state.discard(id);
                            continue;
                        }
                        let cancelled = JsonRpcResponse::error(
                            Some(id.clone()),
                            JsonRpcError {
                                code: McpErrorCode::RequestCancelled.into(),
                                message: "Request cancelled before dispatch".to_string(),
                                data: None,
                            },
                        );
                        let mut send_guard = worker_send
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner);
                        let send_result =
                            send_guard(&worker_cx, &JsonRpcMessage::Response(cancelled));
                        drop(send_guard);
                        worker_queue_state.discard(id);
                        if let Err(send_error) = send_result {
                            if send_error.is_cancelled() {
                                worker_queue_state.stop();
                                clean_exit = true;
                            }
                            break;
                        }
                    }
                    continue;
                }

                let start_time = Instant::now();
                if let Some(renderer) = &worker_renderer {
                    renderer.render_request(&request, &worker_server.console);
                }

                let request_id = request.id.clone();
                if matches!(era, ProtocolEra::Modern2026) {
                    let inbound = InboundRequestContext::with_modern_connection_context(
                        worker_cx.clone(),
                        request_id_to_u64(request.id.as_ref()),
                        InboundRequestTransport::Stdio,
                        &worker_modern_connection,
                        worker_transport_authorization.clone(),
                    );
                    let request_cancellation = McpRequestCancellation::new();
                    let notification_send = Arc::clone(&worker_send);
                    let notification_cx = worker_cx.clone();
                    let notification_cancellation = request_cancellation.clone();
                    let notification_sender: NotificationSender = Arc::new(move |notification| {
                        let mut send_guard = notification_send
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner);
                        // The receive side claims cancellation through this
                        // same writer lock. Once it has won, never commit a
                        // trailing progress or final-log notification.
                        if !notification_cancellation.is_cancel_requested()
                            && send_guard(&notification_cx, &JsonRpcMessage::Request(notification))
                                .is_err()
                        {
                            notification_cancellation.cancel();
                        }
                    });
                    let response = poll_on_cx(
                        &worker_cx,
                        Arc::clone(&worker_server).dispatch_with_protocol_policy_owned(
                            worker_server.protocol_policy,
                            &inbound,
                            request.clone(),
                            None,
                            worker_auth_receipt.clone(),
                            worker_auth_custody_generation,
                            None,
                            request_cancellation.clone(),
                            None,
                            notification_sender,
                        ),
                    );
                    let send_result = response.map_or(Ok(()), |response| {
                        let mut send_guard = worker_send
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner);
                        send_guard(&worker_cx, &JsonRpcMessage::Response(response))
                    });
                    if let Some(id) = request_id.as_ref() {
                        worker_queue_state.discard(id);
                    }
                    if let Err(send_error) = &send_result {
                        if send_error.is_cancelled() {
                            worker_queue_state.stop();
                            clean_exit = true;
                        }
                        break;
                    }
                    continue;
                }
                let adapter = match legacy_adapter.as_mut() {
                    Some(adapter) => adapter,
                    None => {
                        let adapter = worker_server.install_legacy_2024_adapter(
                            legacy_binding,
                            LiveLegacy2024RuntimeHandler {
                                server: worker_server.as_ref(),
                                cx: worker_cx.clone(),
                                session_id: legacy_binding.generation(),
                                session_principal: worker_session_principal.clone(),
                                runtime: worker_legacy_runtime.clone(),
                                queue_state: Some(Arc::clone(&worker_queue_state)),
                                active_request: Arc::clone(&legacy_active_request),
                                connection_auth: worker_auth_receipt.clone(),
                            },
                        );
                        let Ok(adapter) = adapter else {
                            if let Some(id) = request_id.as_ref() {
                                worker_queue_state.discard(id);
                            }
                            break;
                        };
                        legacy_adapter.insert(adapter)
                    }
                };
                let legacy_response = poll_on_cx(
                    &worker_cx,
                    legacy_adapter_response_async(adapter, legacy_binding, &request),
                );
                sync_live_legacy_runtime_from_adapter(&worker_legacy_runtime, adapter);
                let active_request = take_live_legacy_active_request(&legacy_active_request);
                let handled = match legacy_response {
                    Ok(response) => response.map(|response| {
                        legacy_handled_response(response, active_request, &worker_cx)
                    }),
                    // Peer-fault rejections of id-less frames are dropped
                    // rather than terminating the dispatch worker.
                    Err(error) if matches!(error.code().as_i32(), Some(-32602..=-32600)) => {
                        debug!(
                            target: targets::SESSION,
                            "Dropped invalid exact-2024 notification; code={}",
                            error.code()
                        );
                        None
                    }
                    Err(_) => {
                        if let Some(id) = request_id.as_ref() {
                            worker_queue_state.discard(id);
                        }
                        break;
                    }
                };
                let duration = start_time.elapsed();
                let Some(handled) = handled else {
                    if let Some(id) = request_id.as_ref() {
                        worker_queue_state.discard(id);
                    }
                    continue;
                };

                // Acquire exclusive output ownership before closing the
                // cancellation race. This is the strongest reservation the
                // current synchronous writer surface can provide; the later
                // write/flush can still fail and therefore remains fallible.
                let mut send_guard = worker_send
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                let send_result = handled.send_with(&mut session, |response| {
                    send_guard(&worker_cx, &JsonRpcMessage::Response(response.clone()))
                });
                drop(send_guard);
                if let Ok(Some(response)) = &send_result {
                    if let Some(renderer) = &worker_renderer {
                        renderer.render_response(response, Some(duration), &worker_server.console);
                    }
                    if let Some(ref stats) = worker_server.stats
                        && let Ok(json) = serde_json::to_string(response)
                    {
                        stats.add_bytes_sent(json.len() as u64 + 1);
                    }
                }
                if let Some(id) = request_id.as_ref() {
                    worker_queue_state.discard(id);
                }
                if let Err(send_error) = &send_result {
                    // The send callback already maps a pre-commit context stop
                    // to `Cancelled`. Once it reports I/O or codec failure,
                    // that concrete output failure wins over any concurrent
                    // EOF, queue stop, or ambient cancellation.
                    if send_error.is_cancelled() {
                        worker_queue_state.stop();
                        clean_exit = true;
                    }
                    break;
                }
            }
            let adapter_closed = legacy_adapter
                .as_mut()
                .is_none_or(|adapter| adapter.close(legacy_binding).is_ok());
            if clean_exit && adapter_closed {
                failure_latch.disarm();
            }
        });

        let mut era_classifier =
            StdioEraClassifier::new(runtime_stdio_policy(server.protocol_policy));
        let mut negotiated_era = None;
        let mut exit_code = 0;
        let mut drain_correlated_before_stop = false;
        'receive: loop {
            if worker_failed.load(Ordering::Acquire)
                || connection_failure
                    .as_ref()
                    .is_some_and(|failed| failed.load(Ordering::Acquire))
            {
                exit_code = 1;
                break;
            }
            if cx.checkpoint().is_err() {
                break;
            }

            let message = match recv(cx, &worker_failed) {
                Ok(message) => message,
                Err(TransportError::Closed) => {
                    // A full-duplex peer may half-close ingress while the
                    // independently owned egress remains writable. Give
                    // every already-admitted id-bearing request a bounded
                    // opportunity to finish its response commit before
                    // shutdown cancellation begins, regardless of era.
                    drain_correlated_before_stop = true;
                    break;
                }
                Err(TransportError::Cancelled) => break,
                Err(error) => {
                    let disposition = classify_receive_error(&error);
                    if enforce_runtime_era
                        && negotiated_era.is_none()
                        && matches!(
                            &disposition,
                            ReceiveErrorDisposition::ReplyWithParseError
                                | ReceiveErrorDisposition::ReplyWithInvalidRequest(_)
                        )
                    {
                        let _ = reject_initial_stdio_malformed(&mut era_classifier);
                        let _ = match disposition {
                            ReceiveErrorDisposition::ReplyWithParseError => {
                                send_uncorrelated_parse_error(&send, cx)
                            }
                            ReceiveErrorDisposition::ReplyWithInvalidRequest(request_id) => {
                                send_invalid_request(&send, cx, request_id)
                            }
                            ReceiveErrorDisposition::Terminate => unreachable!(
                                "only recoverable malformed input reaches the Auto opening rejection"
                            ),
                        };
                        exit_code = 1;
                        break;
                    }
                    match disposition {
                        ReceiveErrorDisposition::ReplyWithParseError => {
                            if send_uncorrelated_parse_error(&send, cx).is_err() {
                                exit_code = 1;
                                break;
                            }
                            continue;
                        }
                        ReceiveErrorDisposition::ReplyWithInvalidRequest(request_id) => {
                            if send_invalid_request(&send, cx, request_id).is_err() {
                                exit_code = 1;
                                break;
                            }
                            continue;
                        }
                        ReceiveErrorDisposition::Terminate => {
                            exit_code = 1;
                            break;
                        }
                    }
                }
            };

            // The receive implementation rechecks its stop predicate after a
            // completed frame, but a worker failure can still race the final
            // closure return. Never admit or mutate state for a frame after a
            // connection-fatal worker exit has become observable.
            if worker_failed.load(Ordering::Acquire) {
                exit_code = 1;
                break;
            }

            if enforce_runtime_era && negotiated_era.is_none() {
                match classify_initial_stdio_envelope(&mut era_classifier, &message) {
                    Ok(era) => negotiated_era = Some(era),
                    Err(decision) if opening_rejection_selected_modern(&decision) => {
                        negotiated_era = Some(ProtocolEra::Modern2026);
                        if let JsonRpcMessage::Request(request) = &message {
                            let sent = if request.validate().is_err() {
                                send_invalid_request(&send, cx, request.id.clone())
                            } else if let Some(response) = modern_request_version_refusal(request) {
                                send.lock()
                                    .unwrap_or_else(std::sync::PoisonError::into_inner)(
                                    cx,
                                    &JsonRpcMessage::Response(response),
                                )
                            } else {
                                Ok(())
                            };
                            if sent.is_err() {
                                exit_code = 1;
                                break;
                            }
                        }
                        continue;
                    }
                    Err(_) => {
                        if let JsonRpcMessage::Request(request) = &message {
                            let _ = if request.validate().is_err() {
                                send_invalid_request(&send, cx, request.id.clone())
                            } else if let Some(response) =
                                era_admission_refusal(server.protocol_policy, request)
                            {
                                send.lock()
                                    .unwrap_or_else(std::sync::PoisonError::into_inner)(
                                    cx,
                                    &JsonRpcMessage::Response(response),
                                )
                            } else {
                                Ok(())
                            };
                        }
                        exit_code = i32::from(owns_server_lifecycle);
                        break;
                    }
                }
            }

            // Account at the receive boundary so queued, rejected, cancelled,
            // and bidirectional-response frames are not omitted from traffic
            // totals merely because they never reach a dispatch worker.
            if let Some(ref stats) = server.stats
                && let Ok(json) = serde_json::to_string(&message)
            {
                stats.add_bytes_received(json.len() as u64 + 1);
            }

            match message {
                JsonRpcMessage::Response(response) => {
                    if response.validate().is_err() {
                        exit_code = 1;
                        break;
                    }
                    let disposition = pending_requests.route_response_with_disposition(&response);
                    if matches!(
                        disposition,
                        bidirectional::PendingResponseDisposition::Delivered
                    ) {
                        debug!(target: targets::SERVER, "Routed response to pending request");
                    } else if matches!(
                        disposition,
                        bidirectional::PendingResponseDisposition::Unmatched
                    ) && matches!(negotiated_era, Some(ProtocolEra::Legacy2024))
                    {
                        match dispatch_sender
                            .try_send(QueuedDispatchMessage::LegacyResponse(response))
                        {
                            Ok(()) => {}
                            Err(
                                asupersync_mpsc::SendError::Full(_)
                                | asupersync_mpsc::SendError::Disconnected(_)
                                | asupersync_mpsc::SendError::Cancelled(_),
                            ) => {
                                exit_code = 1;
                                break;
                            }
                        }
                    } else if matches!(
                        disposition,
                        bidirectional::PendingResponseDisposition::Unmatched
                    ) {
                        debug!(target: targets::SERVER, "Received unmatched JSON-RPC response");
                    }
                }
                JsonRpcMessage::Request(mut request)
                    if request.id.is_none() && request.method == "notifications/cancelled" =>
                {
                    let Some(era) = negotiated_era else {
                        debug!(
                            target: targets::SESSION,
                            "Ignoring cancellation notification before protocol-era negotiation"
                        );
                        continue;
                    };
                    if request.validate().is_err() {
                        debug!(
                            target: targets::SESSION,
                            "Ignoring invalid cancellation notification before request-state mutation"
                        );
                        continue;
                    }
                    if matches!(era, ProtocolEra::Modern2026)
                        && admit_final_client_notification_ingress(&request).is_err()
                    {
                        debug!(
                            target: targets::SESSION,
                            "Ignoring final cancellation notification not admitted from the client"
                        );
                        continue;
                    }
                    match server.authenticate_cancelled_control_notification(
                        cx,
                        &session_principal,
                        era,
                        &mut request,
                        None,
                    ) {
                        Ok(cancellation) => {
                            let cancellation_accepted = if matches!(era, ProtocolEra::Modern2026) {
                                // Progress, final logs, and the terminal
                                // response all commit under this writer lock.
                                // Claim peer cancellation under the same
                                // authority so a winning cancellation cannot
                                // be followed by a queued request-scoped
                                // frame. Exact-2024 retains its adapter-owned
                                // cancellation ordering below.
                                let _writer_fence = send
                                    .lock()
                                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                                let queue_disposition = queue_state.cancel_reserved(
                                    Server::cancellation_wire_request_id(&cancellation),
                                );
                                match queue_disposition {
                                    DispatchCancellationDisposition::Accepted => true,
                                    DispatchCancellationDisposition::Protected
                                    | DispatchCancellationDisposition::AlreadySettled => false,
                                    DispatchCancellationDisposition::NotOwned => server
                                        .handle_cancellation_wire_notification(
                                            session_id,
                                            cancellation,
                                        ),
                                }
                            } else {
                                let queue_disposition = queue_state.cancel_reserved(
                                    Server::cancellation_wire_request_id(&cancellation),
                                );
                                match queue_disposition {
                                    DispatchCancellationDisposition::Accepted => true,
                                    DispatchCancellationDisposition::Protected
                                    | DispatchCancellationDisposition::AlreadySettled => false,
                                    DispatchCancellationDisposition::NotOwned => server
                                        .handle_cancellation_wire_notification(
                                            session_id,
                                            cancellation,
                                        ),
                                }
                            };
                            if cancellation_accepted {
                                let interrupted = pending_requests.cancel_cancelled();
                                if interrupted > 0 {
                                    debug!(
                                        target: targets::SESSION,
                                        "Interrupted {interrupted} pending server-to-client request(s) owned by the cancelled request"
                                    );
                                }
                            }
                        }
                        Err(error) => {
                            error!(
                                target: targets::SERVER,
                                "Rejected cancellation notification before mutation; code={:?}",
                                error.code
                            );
                        }
                    }
                }
                JsonRpcMessage::Request(request) => {
                    if request.validate().is_err() {
                        if send_invalid_request(&send, cx, request.id).is_err() {
                            exit_code = 1;
                            break 'receive;
                        }
                        continue;
                    }
                    let era = if !enforce_runtime_era {
                        ProtocolEra::Legacy2024
                    } else {
                        match negotiated_era {
                            Some(ProtocolEra::Modern2026) => {
                                if modern_protocol_version(&request)
                                    == Some(MODERN_PROTOCOL_VERSION)
                                {
                                    ProtocolEra::Modern2026
                                } else {
                                    // Stateless per-request admission: answer
                                    // this request and keep serving the stream.
                                    if let Some(response) = modern_request_version_refusal(&request)
                                        && send
                                            .lock()
                                            .unwrap_or_else(std::sync::PoisonError::into_inner)(
                                            cx,
                                            &JsonRpcMessage::Response(response),
                                        )
                                        .is_err()
                                    {
                                        exit_code = 1;
                                        break 'receive;
                                    }
                                    continue;
                                }
                            }
                            Some(ProtocolEra::Legacy2024) => {
                                if modern_protocol_version(&request).is_some() {
                                    if let Some(response) = protocol_era_refusal(&request) {
                                        let _ = send
                                            .lock()
                                            .unwrap_or_else(std::sync::PoisonError::into_inner)(
                                            cx,
                                            &JsonRpcMessage::Response(response),
                                        );
                                    }
                                    exit_code = i32::from(owns_server_lifecycle);
                                    break 'receive;
                                }
                                ProtocolEra::Legacy2024
                            }
                            None => match era_classifier
                                .classify_opening(stdio_opening_frame(&request))
                            {
                                StdioEraDecision::Selected {
                                    era: ProtocolEra::Modern2026,
                                    modern_version: Some(ModernVersionSupport::Supported),
                                } => {
                                    negotiated_era = Some(ProtocolEra::Modern2026);
                                    ProtocolEra::Modern2026
                                }
                                StdioEraDecision::Selected {
                                    era: ProtocolEra::Legacy2024,
                                    modern_version: None,
                                } => {
                                    negotiated_era = Some(ProtocolEra::Legacy2024);
                                    ProtocolEra::Legacy2024
                                }
                                decision if opening_rejection_selected_modern(&decision) => {
                                    negotiated_era = Some(ProtocolEra::Modern2026);
                                    if let Some(response) = modern_request_version_refusal(&request)
                                        && send
                                            .lock()
                                            .unwrap_or_else(std::sync::PoisonError::into_inner)(
                                            cx,
                                            &JsonRpcMessage::Response(response),
                                        )
                                        .is_err()
                                    {
                                        exit_code = 1;
                                        break 'receive;
                                    }
                                    continue;
                                }
                                _ => {
                                    if let Some(response) = protocol_era_refusal(&request) {
                                        let _ = send
                                            .lock()
                                            .unwrap_or_else(std::sync::PoisonError::into_inner)(
                                            cx,
                                            &JsonRpcMessage::Response(response),
                                        );
                                    }
                                    exit_code = i32::from(owns_server_lifecycle);
                                    break 'receive;
                                }
                            },
                        }
                    };
                    if matches!(era, ProtocolEra::Modern2026)
                        && admit_final_client_notification_ingress(&request).is_err()
                    {
                        debug!(
                            target: targets::SESSION,
                            "Ignoring final notification not admitted from the client before dispatch; method={}",
                            request.method
                        );
                        continue;
                    }
                    let request_id = request.id.clone();
                    if let Some(id) = request_id.as_ref()
                        && (server.request_id_is_active(session_id, id)
                            || !queue_state.admit(id, request.method != "initialize"))
                    {
                        let duplicate = JsonRpcResponse::error(
                            Some(id.clone()),
                            JsonRpcError {
                                code: McpErrorCode::InvalidRequest.into(),
                                message: "Request id is already active".to_string(),
                                data: None,
                            },
                        );
                        if send
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner)(
                            cx,
                            &JsonRpcMessage::Response(duplicate),
                        )
                        .is_err()
                        {
                            exit_code = 1;
                            break;
                        }
                        continue;
                    }

                    let modern_slot = matches!(era, ProtocolEra::Modern2026);
                    if modern_slot && !queue_state.reserve_modern_slot() {
                        if let Some(id) = request.id {
                            queue_state.discard(&id);
                            let overloaded = JsonRpcResponse::error(
                                Some(id),
                                JsonRpcError {
                                    code: RESOURCE_EXHAUSTED_ERROR_CODE.into(),
                                    message: DISPATCH_QUEUE_CAPACITY_MESSAGE.to_string(),
                                    data: None,
                                },
                            );
                            if send
                                .lock()
                                .unwrap_or_else(std::sync::PoisonError::into_inner)(
                                cx,
                                &JsonRpcMessage::Response(overloaded),
                            )
                            .is_err()
                            {
                                exit_code = 1;
                                break;
                            }
                        }
                        continue;
                    }

                    let serialized_bytes = measure_dispatch_request(&request);
                    if serialized_bytes.is_none_or(|bytes| !queue_state.reserve_queued_bytes(bytes))
                    {
                        if modern_slot {
                            queue_state.release_modern_slot();
                        }
                        if let Some(id) = request.id {
                            queue_state.discard(&id);
                            let overloaded = JsonRpcResponse::error(
                                Some(id),
                                JsonRpcError {
                                    code: RESOURCE_EXHAUSTED_ERROR_CODE.into(),
                                    message: DISPATCH_QUEUE_CAPACITY_MESSAGE.to_string(),
                                    data: None,
                                },
                            );
                            if send
                                .lock()
                                .unwrap_or_else(std::sync::PoisonError::into_inner)(
                                cx,
                                &JsonRpcMessage::Response(overloaded),
                            )
                            .is_err()
                            {
                                exit_code = 1;
                                break;
                            }
                        }
                        continue;
                    }
                    let serialized_bytes = serialized_bytes
                        .expect("a dispatch byte reservation requires a measured request");

                    if modern_slot {
                        let response_id = request.id.clone();
                        let principal_admission = Arc::new(if response_id.is_some() {
                            DispatchPrincipalAdmission::pending()
                        } else {
                            DispatchPrincipalAdmission::admitted()
                        });
                        let reservation = ModernDispatchReservation::new(
                            Arc::clone(&queue_state),
                            response_id.clone(),
                            serialized_bytes,
                            Arc::clone(&worker_failed),
                        );
                        let request_server = Arc::clone(&server);
                        let request_send = Arc::clone(&send);
                        let request_renderer = traffic_renderer.clone();
                        let task_principal_admission = Arc::clone(&principal_admission);
                        let task_modern_connection = dispatch_modern_connection.clone();
                        let task_transport_authorization =
                            transport_authorization.clone().unwrap_or_default();
                        let task_auth_receipt = auth_receipt.clone();
                        let task_auth_custody_generation = auth_custody_generation;
                        let submitted = dispatch_cx.spawn_blocking(move |request_cx| {
                            let mut reservation = reservation;
                            match task_principal_admission
                                .wait_timeout(DISPATCH_WORKER_SHUTDOWN_TIMEOUT)
                            {
                                Some(true) => {}
                                Some(false) => return,
                                None => {
                                    reservation.begin();
                                    return;
                                }
                            }
                            reservation.begin();
                            let dispatched = std::panic::catch_unwind(
                                std::panic::AssertUnwindSafe(|| {
                                    if let Some(renderer) = &request_renderer {
                                        renderer.render_request(&request, &request_server.console);
                                    }
                                    let request_cancellation = reservation.cancellation();
                                    let _active_guard = match request.id.clone() {
                                        Some(id) => match ActiveRequestGuard::try_new_with_cancellation(
                                            Arc::clone(&request_server.active_requests),
                                            session_id,
                                            id.clone(),
                                            request_cx.clone(),
                                            request_cancellation.clone(),
                                        ) {
                                            Ok(guard) => Some(guard),
                                            Err(_) => {
                                                let response = JsonRpcResponse::error(
                                                    Some(id),
                                                    JsonRpcError {
                                                        code: McpErrorCode::InvalidRequest.into(),
                                                        message: "Request id is already active"
                                                            .to_string(),
                                                        data: None,
                                                    },
                                                );
                                                let mut send_guard = request_send
                                                    .lock()
                                                    .unwrap_or_else(
                                                        std::sync::PoisonError::into_inner,
                                                    );
                                                return send_guard(
                                                    &request_cx,
                                                    &JsonRpcMessage::Response(response),
                                                );
                                            }
                                        },
                                        None => None,
                                    };
                                    match reservation
                                        .queue
                                        .begin_modern_dispatch(request.id.as_ref())
                                    {
                                        ModernDispatchStart::Stopping => Ok(()),
                                        ModernDispatchStart::Cancelled => {
                                            let Some(id) = request.id.clone() else {
                                                return Ok(());
                                            };
                                            let response = JsonRpcResponse::error(
                                                Some(id),
                                                JsonRpcError {
                                                    code: McpErrorCode::RequestCancelled.into(),
                                                    message: "Request cancelled before dispatch"
                                                        .to_string(),
                                                    data: None,
                                                },
                                            );
                                            let mut send_guard = request_send
                                                .lock()
                                                .unwrap_or_else(std::sync::PoisonError::into_inner);
                                            send_guard(
                                                &request_cx,
                                                &JsonRpcMessage::Response(response),
                                            )
                                        }
                                        ModernDispatchStart::Ready => {
                                            let inbound = InboundRequestContext::with_modern_connection_context(
                                                request_cx.clone(),
                                                request_id_to_u64(request.id.as_ref()),
                                                InboundRequestTransport::Stdio,
                                                &task_modern_connection,
                                                task_transport_authorization.clone(),
                                            );
                                            let started = Instant::now();
                                            let notification_send = Arc::clone(&request_send);
                                            let notification_cx = request_cx.clone();
                                            let notification_cancellation =
                                                request_cancellation.clone();
                                            let notification_failed =
                                                Arc::clone(&reservation.failed);
                                            #[cfg(test)]
                                            let notification_request_id =
                                                request_id_to_u64(request.id.as_ref());
                                            let notification_sender: NotificationSender = Arc::new(
                                                move |notification| {
                                                    #[cfg(test)]
                                                    wait_for_stdio_progress_commit_fence(
                                                        notification_request_id,
                                                        &notification,
                                                    );
                                                    let mut send_guard = notification_send
                                                        .lock()
                                                        .unwrap_or_else(
                                                            std::sync::PoisonError::into_inner,
                                                        );
                                                    // Peer cancellation
                                                    // acquires this same
                                                    // writer fence before it
                                                    // changes request state.
                                                    // The post-lock check
                                                    // makes that election
                                                    // authoritative for
                                                    // progress and final logs.
                                                    if !notification_cancellation
                                                        .is_cancel_requested()
                                                        && send_guard(
                                                            &notification_cx,
                                                            &JsonRpcMessage::Request(notification),
                                                        )
                                                        .is_err()
                                                    {
                                                        // A later successful cancellation response
                                                        // must not erase this failed notification.
                                                        notification_failed
                                                            .store(true, Ordering::Release);
                                                        notification_cancellation.cancel();
                                                    }
                                                },
                                            );
                                            let response = poll_on_cx(
                                                &request_cx,
                                                Arc::clone(&request_server)
                                                    .dispatch_with_protocol_policy_owned(
                                                        request_server.protocol_policy,
                                                        &inbound,
                                                        request.clone(),
                                                        None,
                                                        task_auth_receipt.clone(),
                                                        task_auth_custody_generation,
                                                        None,
                                                        request_cancellation.clone(),
                                                        None,
                                                        notification_sender,
                                                    ),
                                            );
                                            response.map_or(Ok(()), |mut response| {
                                                let mut send_guard = request_send
                                                    .lock()
                                                    .unwrap_or_else(
                                                        std::sync::PoisonError::into_inner,
                                                    );
                                                // Server shutdown elects a final subscription
                                                // completion before cancelling its request to
                                                // wake this worker. That completion is the
                                                // request's one sanctioned terminal response;
                                                // do not overwrite it with RequestCancelled at
                                                // the stdio writer fence.
                                                let graceful_subscription_completion =
                                                    final_subscription_completion_response(&response);
                                                if !graceful_subscription_completion
                                                    && !request_cancellation.begin_finalization()
                                                {
                                                    response = JsonRpcResponse::error(
                                                        response.id.clone(),
                                                        JsonRpcError {
                                                            code: McpErrorCode::RequestCancelled
                                                                .into(),
                                                            message: "Request cancelled before response finalization"
                                                                .to_string(),
                                                            data: None,
                                                        },
                                                    );
                                                }
                                                send_guard(
                                                    &request_cx,
                                                    &JsonRpcMessage::Response(response.clone()),
                                                )?;
                                                if let Some(renderer) = &request_renderer {
                                                    renderer.render_response(
                                                        &response,
                                                        Some(started.elapsed()),
                                                        &request_server.console,
                                                    );
                                                }
                                                if let Some(stats) = &request_server.stats
                                                    && let Ok(json) = serde_json::to_string(&response)
                                                {
                                                    stats.add_bytes_sent(json.len() as u64 + 1);
                                                }
                                                Ok(())
                                            })
                                        }
                                    }
                                }),
                            );
                            match dispatched {
                                Ok(Ok(())) => reservation.disarm_failure(),
                                Ok(Err(error))
                                    if error.is_cancelled()
                                        && reservation.queue.is_stopping() =>
                                {
                                    reservation.disarm_failure();
                                }
                                Ok(Err(_)) | Err(_) => {}
                            }
                        });
                        if submitted.is_ok() {
                            let principal_result = response_id.as_ref().map_or(Ok(()), |_| {
                                bind_anonymous_connection_principal(&session_principal)
                            });
                            // Id-less messages construct the admission already
                            // admitted; resolving again would trip the
                            // single-transition invariant.
                            if response_id.is_some() {
                                principal_admission.resolve(principal_result.is_ok());
                            }
                            if let Err(error) = principal_result
                                && let Some(id) = response_id
                            {
                                let rejected = JsonRpcResponse::error(
                                    Some(id),
                                    JsonRpcError {
                                        code: error.code.into(),
                                        message: error.message,
                                        data: error.data,
                                    },
                                );
                                if send
                                    .lock()
                                    .unwrap_or_else(std::sync::PoisonError::into_inner)(
                                    cx,
                                    &JsonRpcMessage::Response(rejected),
                                )
                                .is_err()
                                {
                                    exit_code = 1;
                                    break;
                                }
                            }
                        } else if let Some(id) = response_id {
                            let unavailable = JsonRpcResponse::error(
                                Some(id),
                                JsonRpcError {
                                    code: McpErrorCode::InternalError.into(),
                                    message: "Caller runtime could not admit request dispatch"
                                        .to_string(),
                                    data: None,
                                },
                            );
                            if send
                                .lock()
                                .unwrap_or_else(std::sync::PoisonError::into_inner)(
                                cx,
                                &JsonRpcMessage::Response(unavailable),
                            )
                            .is_err()
                            {
                                exit_code = 1;
                                break;
                            }
                        }
                        continue;
                    }

                    let permit = match dispatch_sender.try_reserve() {
                        Ok(permit) => permit,
                        Err(asupersync_mpsc::SendError::Full(())) => {
                            queue_state.release_queued_bytes(serialized_bytes);
                            if let Some(id) = request.id {
                                queue_state.discard(&id);
                                let overloaded = JsonRpcResponse::error(
                                    Some(id),
                                    JsonRpcError {
                                        code: RESOURCE_EXHAUSTED_ERROR_CODE.into(),
                                        message: DISPATCH_QUEUE_CAPACITY_MESSAGE.to_string(),
                                        data: None,
                                    },
                                );
                                if send
                                    .lock()
                                    .unwrap_or_else(std::sync::PoisonError::into_inner)(
                                    cx,
                                    &JsonRpcMessage::Response(overloaded),
                                )
                                .is_err()
                                {
                                    exit_code = 1;
                                    break;
                                }
                            }
                            continue;
                        }
                        Err(
                            asupersync_mpsc::SendError::Disconnected(())
                            | asupersync_mpsc::SendError::Cancelled(()),
                        ) => {
                            queue_state.release_queued_bytes(serialized_bytes);
                            if let Some(id) = request.id {
                                queue_state.discard(&id);
                            }
                            exit_code = 1;
                            break;
                        }
                    };
                    let response_id = request.id.clone();
                    let principal_admission = Arc::new(if response_id.is_some() {
                        DispatchPrincipalAdmission::pending()
                    } else {
                        DispatchPrincipalAdmission::admitted()
                    });
                    let queued = QueuedDispatchMessage::Request(QueuedDispatchRequest {
                        request,
                        era,
                        serialized_bytes,
                        principal_admission: Arc::clone(&principal_admission),
                    });
                    match permit.try_send(queued) {
                        Ok(()) => {
                            let principal_result =
                                response_id
                                    .as_ref()
                                    .map_or(Ok(()), |_| match &auth_receipt {
                                        Some(custody) => bind_connection_principal(
                                            &session_principal,
                                            custody.connection_fingerprint(),
                                        ),
                                        None => {
                                            bind_anonymous_connection_principal(&session_principal)
                                        }
                                    });
                            // Id-less messages construct the admission already
                            // admitted; resolving again would trip the
                            // single-transition invariant.
                            if response_id.is_some() {
                                principal_admission.resolve(principal_result.is_ok());
                            }
                            if let Err(error) = principal_result
                                && let Some(id) = response_id
                            {
                                let rejected = JsonRpcResponse::error(
                                    Some(id),
                                    JsonRpcError {
                                        code: error.code.into(),
                                        message: error.message,
                                        data: error.data,
                                    },
                                );
                                if send
                                    .lock()
                                    .unwrap_or_else(std::sync::PoisonError::into_inner)(
                                    cx,
                                    &JsonRpcMessage::Response(rejected),
                                )
                                .is_err()
                                {
                                    exit_code = 1;
                                    break;
                                }
                            }
                        }
                        Err(asupersync_mpsc::SendError::Full(QueuedDispatchMessage::Request(
                            request,
                        ))) => {
                            queue_state.release_queued_bytes(request.serialized_bytes);
                            if let Some(id) = request.request.id {
                                queue_state.discard(&id);
                                let overloaded = JsonRpcResponse::error(
                                    Some(id),
                                    JsonRpcError {
                                        code: RESOURCE_EXHAUSTED_ERROR_CODE.into(),
                                        message: DISPATCH_QUEUE_CAPACITY_MESSAGE.to_string(),
                                        data: None,
                                    },
                                );
                                if send
                                    .lock()
                                    .unwrap_or_else(std::sync::PoisonError::into_inner)(
                                    cx,
                                    &JsonRpcMessage::Response(overloaded),
                                )
                                .is_err()
                                {
                                    exit_code = 1;
                                    break;
                                }
                            }
                        }
                        Err(
                            asupersync_mpsc::SendError::Disconnected(
                                QueuedDispatchMessage::Request(request),
                            )
                            | asupersync_mpsc::SendError::Cancelled(QueuedDispatchMessage::Request(
                                request,
                            )),
                        ) => {
                            queue_state.release_queued_bytes(request.serialized_bytes);
                            if let Some(id) = request.request.id {
                                queue_state.discard(&id);
                            }
                            exit_code = 1;
                            break;
                        }
                        Err(
                            asupersync_mpsc::SendError::Full(
                                QueuedDispatchMessage::LegacyResponse(_),
                            )
                            | asupersync_mpsc::SendError::Disconnected(
                                QueuedDispatchMessage::LegacyResponse(_),
                            )
                            | asupersync_mpsc::SendError::Cancelled(
                                QueuedDispatchMessage::LegacyResponse(_),
                            ),
                        ) => unreachable!("only a request is sent on this queue path"),
                    }
                }
            }
        }

        // Elect graceful final-subscription completion while the writer and
        // dispatch worker still own their response path. The election sends
        // its correlated stdio control, then wakes the listen future by
        // cancellation; cancelling children first would erase that completion
        // before the writer can commit it.
        if owns_server_lifecycle {
            let _ = server.terminate_subscription_streams_for_shutdown();
        }
        // Notification children have no response commit to protect, so they
        // are cancelled before the drain windows instead of being waited out.
        queue_state.cancel_uncorrelated_modern_children();
        if drain_correlated_before_stop
            && !queue_state.wait_for_correlated_response_drain(DISPATCH_WORKER_SHUTDOWN_TIMEOUT)
        {
            exit_code = 1;
        }
        queue_state.stop();
        drop(dispatch_sender);
        if owns_server_lifecycle {
            server.cancel_active_requests(CancelKind::Shutdown, false);
        }
        pending_requests.cancel_all();
        let modern_children_quiesced = if queue_state
            .wait_for_modern_drain(DISPATCH_WORKER_SHUTDOWN_TIMEOUT)
        {
            true
        } else {
            error!(
                target: targets::SERVER,
                "Modern request children did not drain within the bounded shutdown deadline"
            );
            exit_code = 1;
            if detach_on_worker_timeout {
                false
            } else {
                error!(
                    target: targets::SERVER,
                    "Returning server pump is waiting for modern-child quiescence before cleanup"
                );
                queue_state.wait_for_modern_drain_unbounded();
                true
            }
        };
        let worker_quiesced = match worker_completion_receiver
            .recv_timeout(DISPATCH_WORKER_SHUTDOWN_TIMEOUT)
        {
            Ok(()) => {
                if worker.join().is_err() {
                    exit_code = 1;
                }
                true
            }
            Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
                if worker.join().is_err() {
                    exit_code = 1;
                }
                true
            }
            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
                error!(
                    target: targets::SERVER,
                    "Dispatch worker did not stop within the bounded shutdown deadline"
                );
                exit_code = 1;
                if detach_on_worker_timeout {
                    // `run_stdio_with_cx` exits the process immediately
                    // after this return. Rust cannot safely preempt an
                    // arbitrary blocking handler; detaching is the only
                    // bounded process-exit fallback here.
                    drop(worker);
                    false
                } else {
                    error!(
                        target: targets::SERVER,
                        "Returning server pump is waiting for dispatch-worker quiescence before running shutdown hooks"
                    );
                    let _ = worker_completion_receiver.recv();
                    if worker.join().is_err() {
                        exit_code = 1;
                    }
                    true
                }
            }
        };
        // Recheck all producer-owned failure latches after the dispatch worker
        // has quiesced. This closes the final-load race where notification
        // output fails immediately after recv classifies concurrent EOF as a
        // clean close.
        if worker_failed.load(Ordering::Acquire)
            || connection_failure
                .as_ref()
                .is_some_and(|failed| failed.load(Ordering::Acquire))
        {
            exit_code = 1;
        }
        #[cfg(feature = "tasks")]
        let task_service_succeeded =
            Self::settle_hosted_task_service_blocking(hosted_task_service).is_ok();
        #[cfg(not(feature = "tasks"))]
        let task_service_succeeded = true;
        if !task_service_succeeded {
            error!(target: targets::SERVER, "Hosted Task service did not settle successfully");
            exit_code = 1;
        }
        if owns_server_lifecycle {
            if worker_quiesced && modern_children_quiesced {
                server.run_shutdown_hook();
            } else {
                error!(
                    target: targets::SERVER,
                    "Skipping shutdown hook because dispatch-child quiescence was not established"
                );
            }
        }
        if let Some(ref stats) = server.stats {
            stats.connection_closed();
        }
        exit_code
    }

    /// Shared server loop for embedding/testing, returning on shutdown instead of exiting.
    ///
    /// This is intentionally separate from
    /// [`run_loop_with_dispatch_cx`](Self::run_loop_with_dispatch_cx) because the primary server
    /// entrypoints use `std::process::exit` on shutdown for subprocess use-cases. Clean EOF and
    /// cancellation return success; startup, protocol, and fatal transport failures return errors.
    #[allow(clippy::too_many_lines)]
    fn run_loop_returning<R, S>(
        self,
        cx: &Cx,
        mut recv: R,
        send: S,
        notification_sender: NotificationSender,
        connection_failure: Option<Arc<AtomicBool>>,
        transport_label: &'static str,
    ) -> McpResult<()>
    where
        R: FnMut(&Cx) -> Result<JsonRpcMessage, TransportError>,
        S: FnMut(&Cx, &JsonRpcMessage) -> Result<(), TransportError> + Send + Sync + 'static,
    {
        let server = Arc::new(self);
        #[cfg(feature = "legacy-2024-11-05")]
        let mut session = Session::new(server.info.clone(), server.capabilities.clone());
        #[cfg(feature = "legacy-2024-11-05")]
        let connection_id = session.id();
        // This returning API consumes its Server and owns exactly one
        // connection. Its active-request registry is already isolated from
        // other Server values; no legacy Session is needed for that key.
        #[cfg(not(feature = "legacy-2024-11-05"))]
        let connection_id = 0;
        #[cfg(feature = "legacy-2024-11-05")]
        let legacy_binding = runtime_legacy_binding(session.id());
        #[cfg(feature = "legacy-2024-11-05")]
        let mut legacy_adapter: Option<
            Legacy2024ServerAdapter<LiveLegacy2024RuntimeHandler<'_>>,
        > = None;
        #[cfg(feature = "legacy-2024-11-05")]
        let legacy_active_request = Arc::new(Mutex::new(None));
        let mut era_classifier =
            StdioEraClassifier::new(runtime_stdio_policy(server.protocol_policy));
        let mut negotiated_era = None;

        // Keep response output and inbound pending-response routing connection-scoped.
        let send = Arc::new(Mutex::new(send));
        let background_send_failure = Arc::new(Mutex::new(None));
        let modern_queue = Arc::new(DispatchQueueState::default());
        #[cfg(feature = "legacy-2024-11-05")]
        let pending_requests = server.new_pending_requests_for_connection();
        #[cfg(feature = "legacy-2024-11-05")]
        let legacy_runtime = LiveLegacy2024ConnectionRuntime::new(
            SessionState::new(),
            Arc::clone(&notification_sender),
            None,
            server.logging.level,
        );
        let modern_connection = ModernConnection::new();

        // Track connection opened
        if let Some(ref stats) = server.stats {
            stats.connection_opened();
        }

        // Render startup banner if enabled (respects both config and legacy env var)
        if server.console_config.show_banner && !banner_suppressed() {
            server.render_startup_banner(transport_label);
        }

        // Complete the operation first so temporary output guards are released
        // before shutdown waits for active request owners. Every exit retains
        // cleanup failure, including protocol and response-send failures.
        #[cfg(feature = "tasks")]
        let mut hosted_task_service = None;
        let run_result = (|| {
            // Run startup hook
            if !server.run_startup_hook() {
                error!(target: targets::SERVER, "Startup hook failed, stopping");
                return Err(server_run_error(
                    "startup",
                    "hook_failure",
                    "Server startup hook failed",
                ));
            }
            #[cfg(feature = "tasks")]
            {
                hosted_task_service = server.start_hosted_task_service_blocking(cx, true)?;
            }

            // Create traffic renderer if enabled
            let traffic_renderer = server.configured_traffic_renderer();

            // Main request loop
            loop {
                #[cfg(feature = "tasks")]
                if let Some(hosted) = hosted_task_service.as_ref() {
                    hosted.check_running()?;
                }
                if let Some(error) = background_send_failure
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .take()
                {
                    return Err(error);
                }
                if connection_failure
                    .as_ref()
                    .is_some_and(|failed| failed.load(Ordering::Acquire))
                {
                    return Err(server_run_error(
                        "notification",
                        "send_failure",
                        "Server notification send failed",
                    ));
                }
                // Check for cancellation
                if cx.checkpoint().is_err() {
                    info!(target: targets::SERVER, "Cancellation requested, stopping");
                    return Ok(());
                }

                // Receive next message
                let receive_result = recv(cx);
                if let Some(error) = background_send_failure
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .take()
                {
                    return Err(error);
                }
                if connection_failure
                    .as_ref()
                    .is_some_and(|failed| failed.load(Ordering::Acquire))
                {
                    return Err(server_run_error(
                        "notification",
                        "send_failure",
                        "Server notification send failed",
                    ));
                }
                let message = match receive_result {
                    Ok(msg) => msg,
                    Err(TransportError::Closed) => {
                        return Ok(());
                    }
                    Err(TransportError::Cancelled) => {
                        info!(target: targets::SERVER, "Transport cancelled");
                        return Ok(());
                    }
                    Err(error) => match classify_receive_error(&error) {
                        ReceiveErrorDisposition::ReplyWithParseError => {
                            // A JSON syntax failure is a transport-isolated complete
                            // frame, so JSON-RPC requires the fixed uncorrelated parse
                            // error even before MCP protocol-era negotiation. The
                            // response shape is era-independent and the following
                            // complete message remains admissible.
                            error!(target: targets::TRANSPORT, "Rejected malformed transport message");
                            if let Err(send_error) = send_uncorrelated_parse_error(&send, cx) {
                                error!(target: targets::TRANSPORT, "Failed to send parse-error response; terminating transport");
                                return returning_send_result_with_connection_failure(
                                    &send_error,
                                    &connection_failure,
                                );
                            }
                            continue;
                        }
                        ReceiveErrorDisposition::ReplyWithInvalidRequest(request_id) => {
                            error!(target: targets::TRANSPORT, "Rejected invalid JSON-RPC request");
                            if let Err(send_error) = send_invalid_request(&send, cx, request_id) {
                                error!(target: targets::TRANSPORT, "Failed to send invalid-request response; terminating transport");
                                return returning_send_result_with_connection_failure(
                                    &send_error,
                                    &connection_failure,
                                );
                            }
                            continue;
                        }
                        ReceiveErrorDisposition::Terminate => {
                            error!(target: targets::TRANSPORT, "Fatal transport receive failure; terminating transport");
                            return Err(transport_run_error("receive", &error));
                        }
                    },
                };

                // Log request traffic
                if let Some(renderer) = &traffic_renderer {
                    if let JsonRpcMessage::Request(req) = &message {
                        renderer.render_request(req, &server.console);
                    }
                }

                let start_time = Instant::now();

                // Handle the message
                let response_opt = match message {
                    JsonRpcMessage::Request(request) => {
                        if request.validate().is_err() {
                            if let Err(send_error) = send_invalid_request(&send, cx, request.id) {
                                return returning_send_result_with_connection_failure(
                                    &send_error,
                                    &connection_failure,
                                );
                            }
                            continue;
                        }
                        // Track bytes received (approximate from serialized request size)
                        if let Some(ref stats) = server.stats {
                            // Estimate request size by serializing back to JSON
                            // This is approximate but accurate enough for statistics
                            if let Ok(json) = serde_json::to_string(&request) {
                                stats.add_bytes_received(json.len() as u64 + 1); // +1 for newline
                            }
                        }
                        let era = match negotiated_era {
                            Some(ProtocolEra::Modern2026)
                                if modern_protocol_version(&request)
                                    == Some(MODERN_PROTOCOL_VERSION) =>
                            {
                                ProtocolEra::Modern2026
                            }
                            #[cfg(feature = "legacy-2024-11-05")]
                            Some(ProtocolEra::Legacy2024)
                                if modern_protocol_version(&request).is_none() =>
                            {
                                ProtocolEra::Legacy2024
                            }
                            Some(ProtocolEra::Modern2026) => {
                                // Stateless per-request admission: answer this
                                // request and keep serving the stream.
                                if let Some(response) = modern_request_version_refusal(&request)
                                    && let Err(send_error) = send
                                        .lock()
                                        .unwrap_or_else(std::sync::PoisonError::into_inner)(
                                        cx,
                                        &JsonRpcMessage::Response(response),
                                    )
                                {
                                    return returning_send_result_with_connection_failure(
                                        &send_error,
                                        &connection_failure,
                                    );
                                }
                                continue;
                            }
                            Some(_) => {
                                if let Some(response) = protocol_era_refusal(&request)
                                    && let Err(send_error) = send
                                        .lock()
                                        .unwrap_or_else(std::sync::PoisonError::into_inner)(
                                        cx,
                                        &JsonRpcMessage::Response(response),
                                    )
                                {
                                    return returning_send_result_with_connection_failure(
                                        &send_error,
                                        &connection_failure,
                                    );
                                }
                                return Err(server_run_error(
                                    "protocol",
                                    "era_admission",
                                    "Request does not match the negotiated MCP protocol era",
                                ));
                            }
                            None => {
                                match era_classifier.classify_opening(stdio_opening_frame(&request))
                                {
                                    StdioEraDecision::Selected {
                                        era: ProtocolEra::Modern2026,
                                        modern_version: Some(ModernVersionSupport::Supported),
                                    } => {
                                        negotiated_era = Some(ProtocolEra::Modern2026);
                                        ProtocolEra::Modern2026
                                    }
                                    #[cfg(feature = "legacy-2024-11-05")]
                                    StdioEraDecision::Selected {
                                        era: ProtocolEra::Legacy2024,
                                        modern_version: None,
                                    } => {
                                        negotiated_era = Some(ProtocolEra::Legacy2024);
                                        ProtocolEra::Legacy2024
                                    }
                                    decision if opening_rejection_selected_modern(&decision) => {
                                        negotiated_era = Some(ProtocolEra::Modern2026);
                                        if let Some(response) =
                                            modern_request_version_refusal(&request)
                                            && let Err(send_error) = send
                                                .lock()
                                                .unwrap_or_else(std::sync::PoisonError::into_inner)(
                                                cx,
                                                &JsonRpcMessage::Response(response),
                                            )
                                        {
                                            return returning_send_result_with_connection_failure(
                                                &send_error,
                                                &connection_failure,
                                            );
                                        }
                                        continue;
                                    }
                                    _ => {
                                        if let Some(response) = protocol_era_refusal(&request)
                                            && let Err(send_error) = send
                                                .lock()
                                                .unwrap_or_else(std::sync::PoisonError::into_inner)(
                                                cx,
                                                &JsonRpcMessage::Response(response),
                                            )
                                        {
                                            return returning_send_result_with_connection_failure(
                                                &send_error,
                                                &connection_failure,
                                            );
                                        }
                                        return Err(server_run_error(
                                            "protocol",
                                            "era_admission",
                                            "Request does not match the negotiated MCP protocol era",
                                        ));
                                    }
                                }
                            }
                        };

                        if matches!(era, ProtocolEra::Modern2026) {
                            // Stdio is a local trusted pipe with no transport-layer
                            // authorization; dispatch carries no auth custody for it.
                            let inbound =
                                InboundRequestContext::with_modern_connection_and_transport_authorization(
                                    cx.clone(),
                                    request_id_to_u64(request.id.as_ref()),
                                    InboundRequestTransport::Stdio,
                                    &modern_connection,
                                    TransportAuthorization::default(),
                                );
                            let response = Self::dispatch_or_schedule_stdio_modern_request(
                                Arc::clone(&server),
                                cx,
                                cx,
                                connection_id,
                                inbound,
                                request,
                                None,
                                None,
                                Arc::clone(&notification_sender),
                                Arc::clone(&send),
                                Arc::clone(&background_send_failure),
                                Arc::clone(&modern_queue),
                            );
                            #[cfg(feature = "legacy-2024-11-05")]
                            let response = response.map(HandledRequest::untracked);
                            response
                        } else {
                            #[cfg(not(feature = "legacy-2024-11-05"))]
                            return Err(server_run_error(
                                "protocol",
                                "era_admission",
                                "Request does not match the negotiated MCP protocol era",
                            ));
                            #[cfg(feature = "legacy-2024-11-05")]
                            {
                                let adapter = match legacy_adapter.as_mut() {
                                    Some(adapter) => adapter,
                                    None => {
                                        let adapter = server.install_legacy_2024_adapter(
                                            legacy_binding,
                                            LiveLegacy2024RuntimeHandler {
                                                server: server.as_ref(),
                                                cx: cx.clone(),
                                                session_id: legacy_binding.generation(),
                                                session_principal: session.principal_binding(),
                                                runtime: legacy_runtime.clone(),
                                                queue_state: None,
                                                active_request: Arc::clone(&legacy_active_request),
                                                connection_auth: None,
                                            },
                                        );
                                        let Ok(adapter) = adapter else {
                                            return Err(server_run_error(
                                                "protocol",
                                                "legacy_adapter_install",
                                                "Legacy MCP 2024-11-05 adapter could not be installed",
                                            ));
                                        };
                                        legacy_adapter.insert(adapter)
                                    }
                                };
                                let legacy_response = poll_on_cx(
                                    cx,
                                    legacy_adapter_response_async(
                                        adapter,
                                        legacy_binding,
                                        &request,
                                    ),
                                );
                                sync_live_legacy_runtime_from_adapter(&legacy_runtime, adapter);
                                let active_request =
                                    take_live_legacy_active_request(&legacy_active_request);
                                match legacy_response {
                                    Ok(response) => response.map(|response| {
                                        legacy_handled_response(response, active_request, cx)
                                    }),
                                    // A peer-fault rejection of an id-less frame has no
                                    // response channel; JSON-RPC drops it without
                                    // advancing lifecycle, and one malformed peer
                                    // notification must not terminate the connection.
                                    Err(error)
                                        if matches!(
                                            error.code().as_i32(),
                                            Some(-32602..=-32600)
                                        ) =>
                                    {
                                        debug!(
                                            target: targets::SESSION,
                                            "Dropped invalid exact-2024 notification; code={}",
                                            error.code()
                                        );
                                        None
                                    }
                                    Err(_) => {
                                        return Err(server_run_error(
                                            "protocol",
                                            "legacy_adapter",
                                            "Legacy MCP 2024-11-05 adapter rejected a notification",
                                        ));
                                    }
                                }
                            }
                        }
                    }
                    JsonRpcMessage::Response(response) => {
                        if response.validate().is_err() {
                            return Err(server_run_error(
                                "receive",
                                "invalid_response",
                                "Received invalid JSON-RPC response",
                            ));
                        }
                        #[cfg(feature = "legacy-2024-11-05")]
                        {
                            // Preserve generic pending responses first; otherwise an
                            // exact-2024 response completes the adapter-owned reverse
                            // request for this one selected legacy connection.
                            let disposition =
                                pending_requests.route_response_with_disposition(&response);
                            if matches!(
                                disposition,
                                bidirectional::PendingResponseDisposition::Delivered
                            ) {
                                debug!(target: targets::SERVER, "Routed response to pending request");
                            } else if matches!(
                                disposition,
                                bidirectional::PendingResponseDisposition::Unmatched
                            ) && matches!(negotiated_era, Some(ProtocolEra::Legacy2024))
                            {
                                let Some(adapter) = legacy_adapter.as_mut() else {
                                    return Err(server_run_error(
                                        "protocol",
                                        "legacy_adapter",
                                        "Legacy MCP 2024-11-05 adapter is unavailable for a client response",
                                    ));
                                };
                                if !legacy_adapter_accept_response(
                                    adapter,
                                    legacy_binding,
                                    &response,
                                ) {
                                    return Err(server_run_error(
                                        "protocol",
                                        "legacy_adapter",
                                        "Legacy MCP 2024-11-05 adapter rejected a client response",
                                    ));
                                }
                            } else if matches!(
                                disposition,
                                bidirectional::PendingResponseDisposition::Unmatched
                            ) {
                                let request_key = response.id.as_ref().map(request_id_log_key);
                                debug!(
                                    target: targets::SERVER,
                                    "Received unexpected response (id_present={}, request_key={:016x})",
                                    response.id.is_some(),
                                    request_key.unwrap_or_default()
                                );
                            }
                        }
                        #[cfg(not(feature = "legacy-2024-11-05"))]
                        {
                            // Modern requests do not create reverse JSON-RPC
                            // requests. A well-formed unmatched response has
                            // no recipient, but invalid responses above must
                            // still terminate the transport before more input.
                            let request_key = response.id.as_ref().map(request_id_log_key);
                            debug!(
                                target: targets::SERVER,
                                "Received unexpected response (id_present={}, request_key={:016x})",
                                response.id.is_some(),
                                request_key.unwrap_or_default()
                            );
                        }
                        continue;
                    }
                };

                if connection_failure
                    .as_ref()
                    .is_some_and(|failed| failed.load(Ordering::Acquire))
                {
                    return Err(server_run_error(
                        "notification",
                        "send_failure",
                        "Server notification send failed",
                    ));
                }

                let duration = start_time.elapsed();

                if let Some(response) = response_opt {
                    let mut guard = match send.lock() {
                        Ok(guard) => guard,
                        Err(poisoned) => {
                            error!(
                                target: targets::TRANSPORT,
                                "Send channel lock poisoned; continuing with inner guard"
                            );
                            poisoned.into_inner()
                        }
                    };
                    #[cfg(feature = "legacy-2024-11-05")]
                    let send_result = response.send_with(&mut session, |response| {
                        guard(cx, &JsonRpcMessage::Response(response.clone()))
                    });
                    #[cfg(not(feature = "legacy-2024-11-05"))]
                    let send_result = guard(cx, &JsonRpcMessage::Response(response.clone()))
                        .map(|()| Some(response));
                    drop(guard);
                    if let Ok(Some(response)) = &send_result {
                        if let Some(renderer) = &traffic_renderer {
                            renderer.render_response(response, Some(duration), &server.console);
                        }
                        if let Some(ref stats) = server.stats
                            && let Ok(json) = serde_json::to_string(response)
                        {
                            stats.add_bytes_sent(json.len() as u64 + 1);
                        }
                    }
                    if let Err(send_error) = send_result {
                        error!(target: targets::TRANSPORT, "Failed to send response; terminating transport");
                        return returning_send_result_with_connection_failure(
                            &send_error,
                            &connection_failure,
                        );
                    }
                }
            }
        })();
        #[cfg(feature = "tasks")]
        let task_service_result = Self::settle_hosted_task_service_blocking(hosted_task_service);
        #[cfg(not(feature = "tasks"))]
        let task_service_result: McpResult<()> = Ok(());
        let cleanup = server.graceful_shutdown_returning();
        let run_result = run_result.and(task_service_result);
        // A worker can finish its response attempt during the shutdown drain.
        // Read its failure after ownership retirement, including on clean EOF.
        let send_error = background_send_failure
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .take();
        let run_result = match (run_result, send_error) {
            (Ok(()), Some(error)) => Err(error),
            (Err(run_error), Some(send_error)) => Err(McpError::with_data(
                McpErrorCode::InternalError,
                "Server operation and background response send both failed",
                serde_json::json!({
                    "stage": "run_and_send",
                    "kind": "multiple_failures",
                    "run": run_error,
                    "send": send_error,
                }),
            )),
            (result, None) => result,
        };
        match run_result {
            Ok(()) => cleanup.into_error().map_or(Ok(()), Err),
            Err(error) => Err(combined_operation_and_cleanup_error(error, cleanup)),
        }
    }

    /// Handles a single JSON-RPC request.
    async fn handle_request(
        &self,
        cx: &Cx,
        session: &mut Session,
        request: JsonRpcRequest,
        notification_sender: &NotificationSender,
        request_sender: &bidirectional::RequestSender,
    ) -> Option<JsonRpcResponse> {
        self.handle_request_internal(
            cx,
            session,
            request,
            notification_sender,
            request_sender,
            None,
            None,
        )
        .await
        .map(|handled| handled.finalize_for_return(session))
    }

    async fn handle_request_internal(
        &self,
        cx: &Cx,
        session: &mut Session,
        request: JsonRpcRequest,
        notification_sender: &NotificationSender,
        request_sender: &bidirectional::RequestSender,
        dispatch_queue: Option<&DispatchQueueState>,
        transport_authorization: Option<&str>,
    ) -> Option<HandledRequest> {
        let id = request.id.clone();
        let method = request.method.clone();
        let is_notification = id.is_none();

        // Start timing for stats
        let start_time = Instant::now();

        if !is_notification && is_notification_only_method(&method) {
            let deferred_stats = DeferredRequestStats::new(
                self.stats.as_ref(),
                &method,
                start_time,
                DeferredRequestOutcome::Failure,
            );
            return Some(
                HandledRequest::untracked(JsonRpcResponse::error(
                    id,
                    JsonRpcError {
                        code: McpErrorCode::InvalidRequest.into(),
                        message: "MCP notification method must not carry a request id".to_string(),
                        data: None,
                    },
                ))
                .with_deferred_stats(deferred_stats),
            );
        }

        if is_notification && is_request_only_method(&method) {
            if let Some(ref stats) = self.stats {
                stats.record_request(&method, start_time.elapsed(), false);
            }
            error!(
                target: targets::SERVER,
                "Rejected request-only MCP method sent without an id; method_key={:016x}",
                stable_hash_request_id(&method)
            );
            return None;
        }

        // Generate internal request ID for tracing
        let request_id = request_id_to_u64(id.as_ref());

        // Create a budget for this request based on timeout configuration
        let budget = self.create_request_budget(cx);

        // Reject an already-cancelled or exhausted request before it acquires
        // request tracking or enters authentication/middleware.
        if let Some(error) = Self::request_budget_error(cx, budget) {
            // If it's a notification, we don't send an error response
            let outcome = if error.code == McpErrorCode::RequestCancelled {
                DeferredRequestOutcome::Cancelled
            } else {
                DeferredRequestOutcome::Failure
            };
            let Some(response_id) = id.clone() else {
                if let Some(stats) =
                    DeferredRequestStats::new(self.stats.as_ref(), &method, start_time, outcome)
                {
                    stats.record();
                }
                return None;
            };
            let deferred_stats =
                DeferredRequestStats::new(self.stats.as_ref(), &method, start_time, outcome);
            return Some(
                HandledRequest::untracked(JsonRpcResponse::error(
                    Some(response_id),
                    JsonRpcError {
                        code: error.code.into(),
                        message: error.message,
                        data: error.data,
                    },
                ))
                .with_deferred_stats(deferred_stats),
            );
        }

        let request_cx = cx.clone();

        let active_guard = match id.clone() {
            Some(request_id) => {
                // Reuse the queue-admitted cancellation token when this
                // request came through the dispatch queue. `cancel_reserved`
                // cancels the admitted token, so an in-band cancellation that
                // arrives while the request is dispatching must act on the
                // same token the dispatch observes and finalizes against.
                let admitted_cancellation = dispatch_queue
                    .and_then(|queue| queue.admitted_request_cancellation(&request_id))
                    .unwrap_or_default();
                match ActiveRequestGuard::try_new_with_cancellation(
                    Arc::clone(&self.active_requests),
                    session.id(),
                    request_id.clone(),
                    request_cx.clone(),
                    admitted_cancellation,
                ) {
                    Ok(guard) => Some(guard),
                    Err(_duplicate_id) => {
                        let message = "Request id is already active; wait for the earlier request to finish before reusing it".to_string();
                        let deferred_stats = DeferredRequestStats::new(
                            self.stats.as_ref(),
                            &method,
                            start_time,
                            DeferredRequestOutcome::Failure,
                        );
                        return Some(
                            HandledRequest::untracked(JsonRpcResponse::error(
                                Some(request_id),
                                JsonRpcError {
                                    code: McpErrorCode::InvalidRequest.into(),
                                    message,
                                    data: None,
                                },
                            ))
                            .with_deferred_stats(deferred_stats),
                        );
                    }
                }
            }
            None => None,
        };
        let request_cancellation = active_guard.as_ref().map_or_else(
            McpRequestCancellation::new,
            ActiveRequestGuard::cancellation,
        );
        if let (Some(queue), Some(request_id)) = (dispatch_queue, id.as_ref())
            && queue.begin_dispatch(request_id)
        {
            let _ = request_cancellation.cancel();
        }

        // Dispatch based on method, passing the budget, notification sender, and request sender
        let mut session_mutation_rollback = None;
        let mut result = self
            .dispatch_method(
                &request_cx,
                session,
                request,
                request_id,
                &request_cancellation,
                &budget,
                notification_sender,
                request_sender,
                &mut session_mutation_rollback,
                transport_authorization,
            )
            .await;
        result = Self::enforce_post_dispatch_liveness(
            &request_cancellation,
            &request_cx,
            budget,
            result,
        );
        if result.is_err()
            && let Some(rollback) = session_mutation_rollback.take()
        {
            rollback.apply(session);
        }

        let stats_outcome = match &result {
            Ok(_) => DeferredRequestOutcome::Success,
            Err(e) if e.code == McpErrorCode::RequestCancelled => DeferredRequestOutcome::Cancelled,
            Err(_) => DeferredRequestOutcome::Failure,
        };

        // If it's a notification (no ID), we must not reply
        if is_notification {
            if let Err(e) = result {
                fastmcp_core::logging::error!(
                    target: targets::HANDLER,
                    "Notification method={} failed with code={:?}",
                    safe_peer_log_key(&method),
                    e.code
                );
            }
            if let Some(stats) =
                DeferredRequestStats::new(self.stats.as_ref(), &method, start_time, stats_outcome)
            {
                stats.record();
            }
            return None;
        }

        // We only reach here if `is_notification` is false, which implies `id` is present.
        // Use `?` to avoid `unwrap()` and keep the control-flow explicit.
        let response_id = id.clone()?;

        let response = match result {
            Ok(value) => JsonRpcResponse::success(response_id, value),
            Err(e) => {
                // Log full error before masking if this is an internal error
                if self.mask_error_details && e.is_internal() {
                    fastmcp_core::logging::error!(
                        target: targets::HANDLER,
                        "Request method={} failed with masked internal code={:?}",
                        safe_peer_log_key(&method),
                        e.code
                    );
                }

                // Apply masking if enabled
                let masked = mask_peer_error(e, self.mask_error_details);
                JsonRpcResponse::error(
                    id,
                    JsonRpcError {
                        code: masked.code.into(),
                        message: masked.message,
                        data: masked.data,
                    },
                )
            }
        };

        let deferred_stats =
            DeferredRequestStats::new(self.stats.as_ref(), &method, start_time, stats_outcome);
        Some(
            HandledRequest::tracked(
                response,
                request_cancellation,
                active_guard,
                session_mutation_rollback,
                request_cx,
                budget,
            )
            // An accepted in-band notifications/cancelled must suppress the
            // request's response entirely (2024-11-05 cancellation contract);
            // ambient cancellation and deadline expiry still produce their
            // ordinary terminal error responses.
            .suppress_cancelled_response()
            .with_deferred_stats(deferred_stats),
        )
    }

    /// Creates a budget for a new request based on server configuration.
    fn create_request_budget(&self, cx: &Cx) -> Budget {
        if self.request_timeout_secs == 0 {
            // No timeout - unlimited budget
            Budget::INFINITE
        } else {
            // Keep the ceiling in the caller context's clock domain so router
            // admission and post-completion checks compare like with like.
            // The legacy synchronous handler dispatcher uses a private runtime
            // for its timeout future and therefore does not itself drive a
            // foreign virtual clock.
            let now = cx.now();
            let timeout_ns = self.request_timeout_secs.saturating_mul(1_000_000_000);
            let deadline = now.saturating_add_nanos(timeout_ns);
            Budget::new().with_deadline(deadline)
        }
    }

    fn request_budget_error(cx: &Cx, budget: Budget) -> Option<McpError> {
        // The runtime also cancels a Cx whose deadline passed, so classify the
        // deadline first; a passed deadline is not reported as a plain
        // cancellation. Explicit request cancellation is checked by callers.
        let effective_budget = cx.budget().meet(budget);
        if effective_budget.is_past_deadline(cx.now()) {
            return Some(McpError::new(
                McpErrorCode::RequestCancelled,
                "Request timeout exceeded",
            ));
        }
        if cx.is_cancel_requested() {
            return Some(McpError::request_cancelled());
        }
        None
    }

    fn enforce_request_budget(cx: &Cx, budget: Budget) -> McpResult<()> {
        match Self::request_budget_error(cx, budget) {
            Some(error) => Err(error),
            None => Ok(()),
        }
    }

    fn enforce_post_dispatch_liveness(
        request_cancellation: &McpRequestCancellation,
        cx: &Cx,
        budget: Budget,
        mut result: McpResult<serde_json::Value>,
    ) -> McpResult<serde_json::Value> {
        if request_cancellation.is_cancel_requested() {
            return Err(McpError::request_cancelled());
        }
        if let Some(error) = Self::request_budget_error(cx, budget) {
            result = Err(error);
        }
        result
    }

    fn request_context_error(ctx: &McpContext) -> Option<McpError> {
        if ctx.ensure_live().is_err() {
            if ctx.deadline_expired() {
                return Some(McpError::new(
                    McpErrorCode::RequestCancelled,
                    "Request timeout exceeded",
                ));
            }
            return Some(McpError::request_cancelled());
        }
        None
    }

    fn enforce_request_context(ctx: &McpContext) -> McpResult<()> {
        match Self::request_context_error(ctx) {
            Some(error) => Err(error),
            None => Ok(()),
        }
    }

    /// Builds the single shared authority object for one request.
    ///
    /// Authentication, middleware, top-level handlers, and any nested
    /// tool/resource dispatch all derive from this context so request-local
    /// budget accounting remains shared and the committed authenticated
    /// principal cannot be replaced between layers.
    fn request_context(
        &self,
        cx: &Cx,
        request_id: u64,
        state: SessionState,
        request_cancellation: McpRequestCancellation,
        budget: Budget,
    ) -> McpResult<(McpContext, McpContextLeaseGuard)> {
        let ctx = McpContext::with_state(cx.clone(), request_id, state)
            .with_request_cancellation(request_cancellation)
            .with_budget_ceiling(budget);
        // A handler that mutates the catalog on this path must still reach the
        // `subscriptions/listen` publisher; dropping it here silently stopped
        // every handler-driven `list_changed` from reaching modern listeners.
        self.attach_request_scoped_component_access(self.with_final_catalog_publisher(ctx))
            .begin_request_scope()
            .ok_or_else(|| McpError::internal_error("request scope could not be established"))
    }

    /// Attaches request-scoped nested tool/resource access to one context.
    ///
    /// Modern HTTP dispatch used to build the inbound context without these
    /// callers, so `ctx.call_tool` / `ctx.read_resource` failed as a masked
    /// internal error even after the nested router path awaited instead of
    /// `block_on`.
    fn attach_request_scoped_component_access(&self, ctx: McpContext) -> McpContext {
        let state = ctx
            .session_state()
            .cloned()
            .unwrap_or_else(SessionState::ephemeral);
        // Request contexts must not extend the server router's lifetime. The
        // Server remains its strong owner throughout dispatch, while escaped
        // context clones lose both their lease and their ability to upgrade
        // this weak access once the Server is consumed or dropped.
        ctx.with_tool_caller(Arc::new(RouterToolCaller::request_scoped(
            Arc::downgrade(&self.router),
            state.clone(),
        )))
        .with_resource_reader(Arc::new(RouterResourceReader::request_scoped(
            Arc::downgrade(&self.router),
            state.clone(),
        )))
        .with_prompt_caller(Arc::new(RouterPromptCaller::request_scoped(
            Arc::downgrade(&self.router),
            state,
        )))
        .with_server_capabilities(self.handler_visible_server_capabilities())
    }

    /// Handler-visible slice of the advertised server capability document.
    fn handler_visible_server_capabilities(&self) -> ServerCapabilityInfo {
        let advertised = &self.capabilities;
        let mut info = ServerCapabilityInfo::new();
        if advertised.tools.is_some() {
            info = info.with_tools();
        }
        if let Some(resources) = advertised.resources.as_ref() {
            info = info.with_resources(resources.subscribe);
        }
        if advertised.prompts.is_some() {
            info = info.with_prompts();
        }
        if advertised.logging.is_some() {
            info = info.with_logging();
        }
        info
    }

    /// Handler-visible slice of a negotiated client capability document.
    fn handler_visible_client_capabilities(caps: &ClientCapabilities) -> ClientCapabilityInfo {
        let (elicitation_form, elicitation_url) = caps
            .elicitation
            .as_ref()
            .map_or((false, false), |elicitation| {
                (elicitation.supports_form(), elicitation.supports_url())
            });
        let mut info =
            ClientCapabilityInfo::new().with_elicitation(elicitation_form, elicitation_url);
        if caps.sampling.is_some() {
            info = info.with_sampling();
        }
        if let Some(roots) = caps.roots.as_ref() {
            info = info.with_roots(roots.list_changed);
        }
        info
    }

    fn attach_session_client_capabilities(
        ctx: McpContext,
        capabilities: Option<&ClientCapabilities>,
    ) -> McpContext {
        match capabilities {
            Some(capabilities) => ctx
                .with_client_capabilities(Self::handler_visible_client_capabilities(capabilities)),
            None => ctx,
        }
    }

    fn handler_visible_legacy_client_implementation(
        info: &fastmcp_protocol::ClientInfo,
    ) -> fastmcp_core::ClientImplementationInfo {
        fastmcp_core::ClientImplementationInfo {
            name: info.name.clone(),
            version: info.version.clone(),
            title: None,
            description: None,
            website_url: None,
            icon_sources: Vec::new(),
        }
    }

    fn attach_session_client_implementation(
        ctx: McpContext,
        client_info: Option<&fastmcp_protocol::ClientInfo>,
    ) -> McpContext {
        match client_info {
            Some(info) => ctx.with_client_implementation(
                Self::handler_visible_legacy_client_implementation(info),
            ),
            None => ctx,
        }
    }

    fn with_final_catalog_publisher(&self, ctx: McpContext) -> McpContext {
        ctx.with_catalog_publisher(Arc::new(FinalCatalogPublisher {
            registry: Arc::clone(&self.final_subscriptions),
        }))
    }

    fn attach_session_log_floor(ctx: McpContext, level: Option<LogLevel>) -> McpContext {
        ctx.with_min_log_level(level.map(crate::handler::mcp_log_level))
    }

    fn attach_session_resource_subscriptions<'a>(
        ctx: McpContext,
        uris: impl IntoIterator<Item = &'a str>,
    ) -> McpContext {
        ctx.with_resource_subscriptions(uris)
    }

    /// Dispatches a request to the appropriate handler.
    #[allow(clippy::too_many_arguments, clippy::too_many_lines)]
    async fn dispatch_method(
        &self,
        cx: &Cx,
        session: &mut Session,
        mut request: JsonRpcRequest,
        request_id: u64,
        request_cancellation: &McpRequestCancellation,
        budget: &Budget,
        notification_sender: &NotificationSender,
        request_sender: &bidirectional::RequestSender,
        session_mutation_rollback: &mut Option<SessionMutationRollback>,
        transport_authorization: Option<&str>,
    ) -> Result<serde_json::Value, McpError> {
        let (mw_ctx, _request_lease_guard) = self.request_context(
            cx,
            request_id,
            session.state().clone(),
            request_cancellation.clone(),
            *budget,
        )?;
        let mw_ctx = Self::attach_session_log_floor(mw_ctx, session.log_level());
        let mw_ctx =
            Self::attach_session_client_capabilities(mw_ctx, session.client_capabilities());
        let mw_ctx = Self::attach_session_client_implementation(mw_ctx, session.client_info());
        let mw_ctx =
            Self::attach_session_resource_subscriptions(mw_ctx, session.subscribed_resource_uris());
        if let Err(error) = Self::enforce_request_context(&mw_ctx) {
            let result =
                Self::enforce_post_dispatch_liveness(request_cancellation, cx, *budget, Err(error));
            self.maybe_emit_log_notification(
                session,
                notification_sender,
                &request.method,
                &result,
            );
            return result;
        }

        // Reject before authentication or extension middleware can claim the
        // method. Quarantine must be invariant under server configuration.
        if is_quarantined_task_rpc(&request.method) {
            let result = Self::enforce_post_dispatch_liveness(
                request_cancellation,
                cx,
                *budget,
                Err(McpError::method_not_found(&request.method)),
            );
            self.maybe_emit_log_notification(
                session,
                notification_sender,
                &request.method,
                &result,
            );
            return result;
        }

        // Check initialization state
        if !session.is_initialized() && request.method != "initialize" && request.method != "ping" {
            let result = Self::enforce_post_dispatch_liveness(
                request_cancellation,
                cx,
                *budget,
                Err(McpError::invalid_request(
                    "Server not initialized. Client must send 'initialize' first.",
                )),
            );
            self.maybe_emit_log_notification(
                session,
                notification_sender,
                &request.method,
                &result,
            );
            return result;
        }

        let auth_result = {
            let auth_request = AuthRequest {
                method: &request.method,
                params: request.params.as_ref(),
                transport_authorization,
                request_id,
            };
            self.authenticate_request(&mw_ctx, auth_request)
                .and_then(|fingerprint| {
                    if session.principal_binding().bind_or_verify(fingerprint) {
                        Self::enforce_request_context(&mw_ctx)
                    } else {
                        Err(McpError::new(
                            McpErrorCode::ResourceForbidden,
                            "Authenticated principal does not own this session",
                        ))
                    }
                })
        };
        auth::strip_recognized_access_credentials(&mut request.params);
        if let Err(err) = auth_result {
            let err = Self::request_context_error(&mw_ctx).unwrap_or(err);
            let err =
                self.finalize_global_middleware_error(request_cancellation, &mw_ctx, &request, err);
            let result = Err(err);
            self.maybe_emit_log_notification(
                session,
                notification_sender,
                &request.method,
                &result,
            );
            return result;
        }

        // Middleware: on_request
        // We use a temporary context derived from the request context for middleware
        // so they can access session state, request auth, and share the request's lifecycle.
        let mut entered_middleware: Vec<&dyn crate::Middleware> = Vec::new();

        for m in self.middleware.iter() {
            if let Some(error) = Self::request_context_error(&mw_ctx) {
                let result = self.finalize_middleware_result(
                    request_cancellation,
                    &entered_middleware,
                    &mw_ctx,
                    &request,
                    Err(error),
                );
                self.maybe_emit_log_notification(
                    session,
                    notification_sender,
                    &request.method,
                    &result,
                );
                return result;
            }
            entered_middleware.push(m.as_ref());
            let decision = match catch_extension_unwind(|| m.on_request(&mw_ctx, &request)) {
                Ok(decision) => decision,
                Err(_payload) => Err(extension_panic_error("middleware_on_request")),
            };
            if let Some(error) = Self::request_context_error(&mw_ctx) {
                let result = self.finalize_middleware_result(
                    request_cancellation,
                    &entered_middleware,
                    &mw_ctx,
                    &request,
                    Err(error),
                );
                self.maybe_emit_log_notification(
                    session,
                    notification_sender,
                    &request.method,
                    &result,
                );
                return result;
            }
            match decision {
                Ok(crate::MiddlewareDecision::Continue) => {}
                Ok(crate::MiddlewareDecision::Respond(v)) => {
                    let short_circuit_result = if is_session_mutation(&request.method) {
                        Err(McpError::internal_error(
                            "Middleware cannot short-circuit session mutations",
                        ))
                    } else {
                        Ok(v)
                    };
                    let result = self.finalize_middleware_result(
                        request_cancellation,
                        &entered_middleware,
                        &mw_ctx,
                        &request,
                        short_circuit_result,
                    );
                    self.maybe_emit_log_notification(
                        session,
                        notification_sender,
                        &request.method,
                        &result,
                    );
                    return result;
                }
                Err(e) => {
                    let result = self.finalize_middleware_result(
                        request_cancellation,
                        &entered_middleware,
                        &mw_ctx,
                        &request,
                        Err(e),
                    );
                    self.maybe_emit_log_notification(
                        session,
                        notification_sender,
                        &request.method,
                        &result,
                    );
                    return result;
                }
            }
        }

        // Everything after middleware entry must flow through `result` so that:
        // - `on_response` runs for successes in reverse middleware order
        // - `on_error` runs for handler/middleware errors in reverse middleware order
        //
        // Without this, `?` would early-return from `dispatch_method` and bypass middleware error
        // rewriting, contradicting the ordering semantics documented in `middleware.rs`.
        let result: Result<serde_json::Value, McpError> = async {
            Self::enforce_request_context(&mw_ctx)?;
            let method = &request.method;
            let params = request.params.clone();

            // Create bidirectional senders based on client capabilities
            let bidirectional_senders = self.create_bidirectional_senders(
                session,
                request_sender,
                request_cancellation,
                &mw_ctx,
            );

            match method.as_str() {
                "initialize" => {
                    let params: InitializeParams = parse_params(params)?;
                    *session_mutation_rollback =
                        Some(SessionMutationRollback::RestoreInitialization(
                            session.initialization_snapshot(),
                        ));
                    let result = self.router.handle_initialize(
                        &mw_ctx,
                        session,
                        params,
                        self.instructions.as_deref(),
                    )?;
                    Ok(serde_json::to_value(result).map_err(McpError::from)?)
                }
                "notifications/initialized" => {
                    // Notification, no response needed (but we send empty ok)
                    Ok(serde_json::Value::Null)
                }
                "notifications/cancelled" => {
                    let params: CancelledParams = parse_params(params)?;
                    self.handle_cancelled_notification(session.id(), params);
                    Ok(serde_json::Value::Null)
                }
                "logging/setLevel" => {
                    let params: SetLogLevelParams = parse_params(params)?;
                    *session_mutation_rollback = Some(SessionMutationRollback::RestoreLogLevel(
                        session.log_level(),
                    ));
                    self.handle_set_log_level(session, params);
                    Ok(serde_json::Value::Null)
                }
                "tools/list" => {
                    let params: ListToolsParams = parse_params_or_default(params)?;
                    let result =
                        self.router
                            .handle_tools_list(&mw_ctx, params, Some(session.state()))?;
                    Ok(serde_json::to_value(result).map_err(McpError::from)?)
                }
                "tools/call" => {
                    let params: CallToolParams = parse_params(params)?;
                    let result = self
                        .router
                        .handle_tools_call(
                            &mw_ctx,
                            params,
                            session.state().clone(),
                            Some(notification_sender),
                            bidirectional_senders.as_ref(),
                        )
                        .await?;
                    Ok(serde_json::to_value(result).map_err(McpError::from)?)
                }
                "resources/list" => {
                    let params: ListResourcesParams = parse_params_or_default(params)?;
                    let result = self.router.handle_resources_list(
                        &mw_ctx,
                        params,
                        Some(session.state()),
                    )?;
                    Ok(serde_json::to_value(result).map_err(McpError::from)?)
                }
                "resources/templates/list" => {
                    let params: ListResourceTemplatesParams = parse_params_or_default(params)?;
                    let result = self.router.handle_resource_templates_list(
                        &mw_ctx,
                        params,
                        Some(session.state()),
                    )?;
                    Ok(serde_json::to_value(result).map_err(McpError::from)?)
                }
                "resources/read" => {
                    let params: ReadResourceParams = parse_params(params)?;
                    let result = self
                        .router
                        .handle_resources_read(
                            &mw_ctx,
                            &params,
                            session.state().clone(),
                            Some(notification_sender),
                            bidirectional_senders.as_ref(),
                        )
                        .await?;
                    Ok(serde_json::to_value(result).map_err(McpError::from)?)
                }
                "resources/subscribe" => {
                    let params: SubscribeResourceParams = parse_params(params)?;
                    let uri = params.uri;
                    // Enforce the individual retention bound before router
                    // lookup/template matching can hash or scan an impossible
                    // peer-controlled URI.
                    if uri.len() > MAX_RESOURCE_SUBSCRIPTION_BYTES_PER_SESSION {
                        return Err(resource_subscription_capacity_error());
                    }
                    if !self.router.resource_exists(&uri) {
                        return Err(McpError::resource_not_found(&uri));
                    }
                    match session.subscribe_resource(&mw_ctx, uri.clone()) {
                        Ok(SubscriptionAdmission::Accepted) => {
                            *session_mutation_rollback = Some(
                                SessionMutationRollback::RemoveResourceSubscription(uri.clone()),
                            );
                            self.router.notify_resource_subscribed(&mw_ctx, &uri)?;
                            Ok(serde_json::json!({}))
                        }
                        Ok(SubscriptionAdmission::Duplicate) => {
                            self.router.notify_resource_subscribed(&mw_ctx, &uri)?;
                            Ok(serde_json::json!({}))
                        }
                        Err(SubscriptionAdmissionError::CapacityExceeded) => {
                            Err(resource_subscription_capacity_error())
                        }
                        Err(SubscriptionAdmissionError::RequestNotLive) => {
                            Err(McpError::request_cancelled())
                        }
                    }
                }
                "resources/unsubscribe" => {
                    let params: UnsubscribeResourceParams = parse_params(params)?;
                    let uri = params.uri;
                    match session.unsubscribe_resource(&mw_ctx, &uri) {
                        Ok(SubscriptionRemoval::Removed) => {
                            *session_mutation_rollback = Some(
                                SessionMutationRollback::RestoreResourceSubscription(uri.clone()),
                            );
                            self.router.notify_resource_unsubscribed(&mw_ctx, &uri)?;
                            Ok(serde_json::json!({}))
                        }
                        Ok(SubscriptionRemoval::NotSubscribed) => Ok(serde_json::json!({})),
                        Err(SubscriptionRemovalError::RequestNotLive) => {
                            Err(McpError::request_cancelled())
                        }
                    }
                }
                "prompts/list" => {
                    let params: ListPromptsParams = parse_params_or_default(params)?;
                    let result =
                        self.router
                            .handle_prompts_list(&mw_ctx, params, Some(session.state()))?;
                    Ok(serde_json::to_value(result).map_err(McpError::from)?)
                }
                "prompts/get" => {
                    let params: GetPromptParams = parse_params(params)?;
                    let result = self
                        .router
                        .handle_prompts_get(
                            &mw_ctx,
                            params,
                            session.state().clone(),
                            Some(notification_sender),
                            bidirectional_senders.as_ref(),
                        )
                        .await?;
                    Ok(serde_json::to_value(result).map_err(McpError::from)?)
                }
                "ping" => {
                    // Simple ping-pong for health checks
                    Ok(serde_json::json!({}))
                }
                "completion/complete" => {
                    self.router
                        .dispatch_legacy_completion(&mw_ctx, &request)
                        .await
                }
                _ => Err(McpError::method_not_found(method)),
            }
        }
        .await;
        let result = self.maybe_dispatch_extension_fallback(&mw_ctx, &request, result);
        let final_result = self.finalize_middleware_result(
            request_cancellation,
            &entered_middleware,
            &mw_ctx,
            &request,
            result,
        );

        if final_result.is_err()
            && let Some(rollback) = session_mutation_rollback.take()
        {
            rollback.apply(session);
        }

        self.maybe_emit_log_notification(
            session,
            notification_sender,
            &request.method,
            &final_result,
        );

        final_result
    }

    fn apply_middleware_response(
        &self,
        stack: &[&dyn crate::Middleware],
        ctx: &McpContext,
        request: &JsonRpcRequest,
        value: serde_json::Value,
    ) -> Result<serde_json::Value, McpError> {
        self.apply_middleware_response_with_liveness(stack, ctx, request, value, true)
    }

    fn apply_middleware_response_with_liveness(
        &self,
        stack: &[&dyn crate::Middleware],
        ctx: &McpContext,
        request: &JsonRpcRequest,
        value: serde_json::Value,
        enforce_liveness: bool,
    ) -> Result<serde_json::Value, McpError> {
        if enforce_liveness && let Some(error) = Self::request_context_error(ctx) {
            return Err(error);
        }
        let mut response = value;
        for m in stack.iter().rev() {
            let invocation = catch_extension_unwind(|| m.on_response(ctx, request, response));
            match invocation {
                Ok(Ok(next)) => {
                    response = next;
                    if enforce_liveness && let Some(error) = Self::request_context_error(ctx) {
                        return Err(error);
                    }
                }
                Ok(Err(err)) => return Err(err),
                Err(_payload) => {
                    return Err(extension_panic_error("middleware_on_response"));
                }
            }
        }
        Ok(response)
    }

    fn finalize_middleware_result(
        &self,
        request_cancellation: &McpRequestCancellation,
        stack: &[&dyn crate::Middleware],
        ctx: &McpContext,
        request: &JsonRpcRequest,
        result: McpResult<serde_json::Value>,
    ) -> McpResult<serde_json::Value> {
        let initial = Self::request_context_error(ctx).map_or(result, Err);
        let mut terminal_cancellation = initial
            .as_ref()
            .is_err_and(|error| error.code == McpErrorCode::RequestCancelled);
        let (result, error_hooks_applied) = match initial {
            Ok(value) => match self.apply_middleware_response(stack, ctx, request, value) {
                Ok(value) => (Ok(value), false),
                Err(error) => {
                    terminal_cancellation |= error.code == McpErrorCode::RequestCancelled;
                    (
                        Err(self.apply_middleware_error(stack, ctx, request, error)),
                        true,
                    )
                }
            },
            Err(error) => (
                Err(self.apply_middleware_error(stack, ctx, request, error)),
                true,
            ),
        };

        // Response/error middleware is part of request dispatch. Cancellation
        // remains eligible throughout those callbacks and until the caller's
        // actual response-commit boundary. Error hooks may observe and clean
        // up a cancellation, but may not rewrite its terminal wire class.
        let cancellation_observed = terminal_cancellation
            || Self::request_context_error(ctx).is_some()
            || request_cancellation.is_cancel_requested();
        if cancellation_observed {
            if !error_hooks_applied {
                let _ =
                    self.apply_middleware_error(stack, ctx, request, McpError::request_cancelled());
            }
            return Err(McpError::request_cancelled());
        }

        result
    }

    fn apply_middleware_error(
        &self,
        stack: &[&dyn crate::Middleware],
        ctx: &McpContext,
        request: &JsonRpcRequest,
        error: McpError,
    ) -> McpError {
        let mut err = error;
        for m in stack.iter().rev() {
            err = match catch_extension_unwind(|| m.on_error(ctx, request, err)) {
                Ok(next) => next,
                // A panicking error hook must not prevent earlier middleware
                // from running their reverse-order cleanup. Replace the
                // in-flight error with the fixed peer-safe failure and keep
                // unwinding the entered middleware stack.
                Err(_payload) => extension_panic_error("middleware_on_error"),
            };
        }
        err
    }

    fn apply_global_middleware_error(
        &self,
        ctx: &McpContext,
        request: &JsonRpcRequest,
        error: McpError,
    ) -> McpError {
        let mut err = error;
        for m in self.middleware.iter().rev() {
            err = match catch_extension_unwind(|| m.on_error(ctx, request, err)) {
                Ok(next) => next,
                // Auth and other pre-entry failures use the full registered
                // stack. Preserve reverse cleanup even if one hook panics.
                Err(_payload) => extension_panic_error("middleware_on_error"),
            };
        }
        err
    }

    fn finalize_global_middleware_error(
        &self,
        request_cancellation: &McpRequestCancellation,
        ctx: &McpContext,
        request: &JsonRpcRequest,
        error: McpError,
    ) -> McpError {
        let terminal_cancellation = error.code == McpErrorCode::RequestCancelled;
        let mapped = self.apply_global_middleware_error(ctx, request, error);
        if terminal_cancellation
            || Self::request_context_error(ctx).is_some()
            || request_cancellation.is_cancel_requested()
        {
            return McpError::request_cancelled();
        }
        mapped
    }

    /// Creates bidirectional senders based on client capabilities.
    ///
    /// Returns `Some(BidirectionalSenders)` if the client supports any
    /// bidirectional feature (sampling, elicitation, roots), or `None` if it
    /// supports none.
    fn create_bidirectional_senders(
        &self,
        session: &Session,
        request_sender: &bidirectional::RequestSender,
        request_cancellation: &McpRequestCancellation,
        request_context: &McpContext,
    ) -> Option<handler::BidirectionalSenders> {
        self.create_bidirectional_senders_from_capabilities(
            session.supports_sampling(),
            session.supports_elicitation(),
            session.supports_roots(),
            request_sender,
            request_cancellation,
            request_context,
        )
    }

    fn create_bidirectional_senders_from_capabilities(
        &self,
        supports_sampling: bool,
        supports_elicitation: bool,
        supports_roots: bool,
        request_sender: &bidirectional::RequestSender,
        request_cancellation: &McpRequestCancellation,
        request_context: &McpContext,
    ) -> Option<handler::BidirectionalSenders> {
        if !supports_sampling && !supports_elicitation && !supports_roots {
            return None;
        }

        let mut senders = handler::BidirectionalSenders::new();
        let request_sender = request_sender.for_request(request_cancellation.clone());

        if supports_sampling {
            let sampling_sender: Arc<dyn fastmcp_core::SamplingSender> =
                Arc::new(bidirectional::TransportSamplingSender::new(
                    request_context.clone(),
                    request_sender.clone(),
                ));
            senders = senders.with_sampling(sampling_sender);
        }

        if supports_elicitation {
            let elicitation_sender: Arc<dyn fastmcp_core::ElicitationSender> =
                Arc::new(bidirectional::TransportElicitationSender::new(
                    request_context.clone(),
                    request_sender.clone(),
                ));
            senders = senders.with_elicitation(elicitation_sender);
        }

        if supports_roots {
            let roots_provider: Arc<dyn fastmcp_core::RootsProvider> = Arc::new(
                bidirectional::TransportRootsProvider::new(request_context.clone(), request_sender),
            );
            senders = senders.with_roots(roots_provider);
        }

        Some(senders)
    }

    /// Authenticates a native HTTP request before session pin, SSE-body
    /// mutation, or exact-2024 admission can observe it.
    fn preauthenticate_http_request(
        &self,
        cx: &Cx,
        request: &JsonRpcRequest,
        transport_authorization: &TransportAuthorization,
    ) -> Result<AuthAdmissionReceipt, HttpResponse> {
        let auth_request = transport_authorization.auth_request(
            &request.method,
            request.params.as_ref(),
            request_id_to_u64(request.id.as_ref()),
        );
        if auth_request.has_in_band_credential_source() {
            return Err(native_http_credential_location_rejection());
        }
        if self.auth_provider.is_some() && auth_request.transport_authorization.is_none() {
            return Err(native_http_authentication_rejection());
        }
        let budget = self.create_request_budget(cx);
        Self::enforce_request_budget(cx, budget)
            .map_err(|_| native_http_authentication_rejection())?;
        let (request_ctx, _request_lease_guard) =
            McpContext::new(cx.clone(), request_id_to_u64(request.id.as_ref()))
                .with_budget_ceiling(budget)
                .begin_request_scope()
                .ok_or_else(native_http_authentication_rejection)?;
        let admitted = self.authenticate_request_without_commit(&request_ctx, auth_request);
        Self::enforce_request_context(&request_ctx)
            .map_err(|_| native_http_authentication_rejection())?;
        admitted
            .map(|(fingerprint, authenticated)| {
                let mut sanitized = request.clone();
                auth::strip_recognized_access_credentials(&mut sanitized.params);
                AuthAdmissionReceipt {
                    method: sanitized.method,
                    request_id: sanitized.id,
                    sanitized_params: sanitized.params,
                    fingerprint,
                    authenticated,
                }
            })
            .map_err(|_| native_http_authentication_rejection())
    }

    /// Authenticates one modern ingress request before extension middleware
    /// sees it. Native authorization remains in the inbound custody object;
    /// recognized JSON credentials are removed after authentication and before
    /// any extension callback. Connection-backed ingress additionally fences
    /// retained state to the first authenticated principal.
    fn authenticate_modern_request(
        &self,
        ctx: &McpContext,
        inbound: &InboundRequestContext,
        request: &mut JsonRpcRequest,
        auth_receipt: Option<&AuthDispatchCustody>,
        websocket_connection_generation: Option<u64>,
    ) -> McpResult<()> {
        let fingerprint = match auth_receipt {
            Some(receipt) => {
                receipt.commit(ctx, inbound, request, websocket_connection_generation)?
            }
            None => {
                let auth_request = inbound.auth_request(&request.method, request.params.as_ref());
                let fingerprint = self.authenticate_request(ctx, auth_request)?;
                auth::strip_recognized_access_credentials(&mut request.params);
                fingerprint
            }
        };
        if !inbound.bind_or_verify_principal(fingerprint) {
            return Err(McpError::new(
                McpErrorCode::ResourceForbidden,
                "Authenticated principal does not own an admitted session",
            ));
        }
        Self::enforce_request_context(ctx)
    }

    fn admit_modern_pump_authentication(
        &self,
        inbound: &InboundRequestContext,
        request: &JsonRpcRequest,
        auth_receipt: Option<&AuthDispatchCustody>,
        websocket_connection_generation: Option<u64>,
    ) -> McpResult<AuthDispatchCustody> {
        let context = inbound.request_context();
        let budget = self.create_request_budget(context.cx());
        let (context, _lease) = context
            .with_budget_ceiling(budget)
            .begin_request_scope()
            .ok_or_else(|| McpError::internal_error("request scope could not be established"))?;
        Self::enforce_request_context(&context)?;
        let mut sanitized = request.clone();
        let (fingerprint, authenticated) = match auth_receipt {
            Some(receipt) => (
                receipt.commit(
                    &context,
                    inbound,
                    &mut sanitized,
                    websocket_connection_generation,
                )?,
                context.auth(),
            ),
            None => self.authenticate_request_without_commit(
                &context,
                inbound.auth_request(&request.method, request.params.as_ref()),
            )?,
        };
        Self::enforce_request_context(&context)?;
        auth::strip_recognized_access_credentials(&mut sanitized.params);
        if !inbound.bind_or_verify_principal(fingerprint) {
            return Err(McpError::new(
                McpErrorCode::ResourceForbidden,
                "Authenticated principal does not own an admitted connection",
            ));
        }
        Ok(AuthDispatchCustody::Http(AuthAdmissionReceipt {
            method: sanitized.method,
            request_id: sanitized.id,
            sanitized_params: sanitized.params,
            fingerprint,
            authenticated,
        }))
    }

    /// A control message may cancel an existing principal's request, but may
    /// never establish that principal's connection ownership itself.
    fn authenticate_modern_cancelled_control(
        &self,
        inbound: &InboundRequestContext,
        request: &mut JsonRpcRequest,
        auth_receipt: Option<&AuthDispatchCustody>,
        websocket_connection_generation: Option<u64>,
    ) -> McpResult<CancellationWireMessage> {
        let context = inbound.request_context();
        let budget = self.create_request_budget(context.cx());
        let (context, _lease) = context
            .with_budget_ceiling(budget)
            .begin_request_scope()
            .ok_or_else(|| McpError::internal_error("request scope could not be established"))?;
        Self::enforce_request_context(&context)?;
        let fingerprint = match auth_receipt {
            Some(receipt) => {
                receipt.commit(&context, inbound, request, websocket_connection_generation)?
            }
            None => {
                let fingerprint = self.authenticate_request(
                    &context,
                    inbound.auth_request(&request.method, request.params.as_ref()),
                )?;
                auth::strip_recognized_access_credentials(&mut request.params);
                fingerprint
            }
        };
        let cancellation = CancellationWireMessage::decode(
            ProtocolEra::Modern2026,
            CancellationSender::Client,
            request,
        )
        .map_err(|error| McpError::invalid_params(error.to_string()))?;
        if !inbound.verify_existing_principal(fingerprint) {
            return Err(McpError::new(
                McpErrorCode::ResourceForbidden,
                "Authenticated principal does not own an admitted connection",
            ));
        }
        Self::enforce_request_context(&context)?;
        Ok(cancellation)
    }

    fn authenticate_request(
        &self,
        ctx: &McpContext,
        request: AuthRequest<'_>,
    ) -> Result<Sha256Digest, McpError> {
        let (fingerprint, authenticated) =
            self.authenticate_request_without_commit(ctx, request)?;
        Self::enforce_request_context(ctx)?;
        match authenticated {
            Some(auth) => {
                if ctx.set_auth(auth) {
                    Ok(fingerprint)
                } else if let Some(error) = Self::request_context_error(ctx) {
                    Err(error)
                } else {
                    Err(McpError::internal_error(
                        "authentication context was already committed",
                    ))
                }
            }
            None if ctx.commit_anonymous_auth() => Ok(fingerprint),
            None => Err(Self::request_context_error(ctx).unwrap_or_else(|| {
                McpError::internal_error("authentication admission was already committed")
            })),
        }
    }

    /// Evaluates authentication without mutating the caller's request context.
    /// Native HTTP and WebSocket ingress turn these private facts into an
    /// [`AuthAdmissionReceipt`] before acquiring session or response-body
    /// ownership; dispatch commits that receipt without re-evaluating a
    /// provider.
    fn authenticate_request_without_commit(
        &self,
        ctx: &McpContext,
        request: AuthRequest<'_>,
    ) -> Result<(Sha256Digest, Option<AuthContext>), McpError> {
        if !request.credential_sources_are_admissible() {
            return Err(McpError::new(
                McpErrorCode::ResourceForbidden,
                "Authentication failed",
            ));
        }
        let credential_present = request.has_any_credential_source();
        let Some(provider) = &self.auth_provider else {
            if credential_present {
                return Err(McpError::new(
                    McpErrorCode::ResourceForbidden,
                    "Authentication failed",
                ));
            }
            return auth::principal_fingerprint(None).map(|fingerprint| (fingerprint, None));
        };
        let auth = {
            let staged_ctx = ctx.clone().with_isolated_auth();
            let result = catch_extension_unwind(|| provider.authenticate(&staged_ctx, request))
                .map_err(|_payload| extension_panic_error("auth_provider"))?;
            result.map_err(|provider_error| {
                debug!(
                    target: targets::SERVER,
                    "Authentication provider denied request; code={:?}",
                    provider_error.code
                );
                McpError::new(McpErrorCode::ResourceForbidden, "Authentication failed")
            })?
        };
        if credential_present && auth.subject.as_deref().is_none_or(str::is_empty) {
            error!(
                target: targets::SERVER,
                "Authentication provider admitted a credential without a stable subject"
            );
            return Err(McpError::new(
                McpErrorCode::ResourceForbidden,
                "Authentication failed",
            ));
        }
        let fingerprint = auth::principal_fingerprint(Some(&auth)).map_err(|provider_error| {
            debug!(
                target: targets::SERVER,
                "Authentication provider returned inadmissible facts; code={:?}",
                provider_error.code
            );
            McpError::new(McpErrorCode::ResourceForbidden, "Authentication failed")
        })?;
        Ok((fingerprint, Some(auth)))
    }

    /// Validates Upgrade authorization before the WebSocket `101` commits.
    /// The resulting transport-private field is carried to every connection
    /// request, where normal request-scoped authentication still strips any
    /// recognized in-band fields before middleware can observe them.
    #[cfg(feature = "websocket")]
    fn authenticate_websocket_upgrade(
        &self,
        cx: &Cx,
        transport_authorization: &TransportAuthorization,
        connection_generation: u64,
    ) -> McpResult<Arc<WebSocketAuthCustody>> {
        let request = transport_authorization.auth_request("websocket/upgrade", None, 0);
        if self.auth_provider.is_some() && !request.has_any_credential_source() {
            return Err(McpError::new(
                McpErrorCode::ResourceForbidden,
                "Authentication failed",
            ));
        }
        self.authenticate_request_without_commit(&McpContext::new(cx.clone(), 0), request)
            .map(|(fingerprint, authenticated)| {
                Arc::new(WebSocketAuthCustody {
                    connection_generation,
                    fingerprint,
                    authenticated,
                    rejected_inband_request_ids: Mutex::new(HashSet::new()),
                })
            })
    }

    /// Authenticates and parses an out-of-band cancellation before any queue,
    /// active-request, or bidirectional waiter state is mutated.
    #[cfg(feature = "legacy-2024-11-05")]
    fn authenticate_cancelled_control_notification(
        &self,
        cx: &Cx,
        principal_binding: &SessionPrincipalBinding,
        era: ProtocolEra,
        request: &mut JsonRpcRequest,
        http_receipt: Option<&AuthAdmissionReceipt>,
    ) -> McpResult<CancellationWireMessage> {
        let budget = self.create_request_budget(cx);
        Self::enforce_request_budget(cx, budget)?;
        let (request_ctx, _request_lease_guard) =
            McpContext::new(cx.clone(), request_id_to_u64(request.id.as_ref()))
                .with_budget_ceiling(budget)
                .begin_request_scope()
                .ok_or_else(|| {
                    McpError::internal_error("request scope could not be established")
                })?;
        let fingerprint = match http_receipt {
            Some(receipt) => receipt.commit_legacy(&request_ctx, request)?,
            None => self.authenticate_request(
                &request_ctx,
                AuthRequest {
                    method: &request.method,
                    params: request.params.as_ref(),
                    transport_authorization: None,
                    request_id: request_id_to_u64(request.id.as_ref()),
                },
            )?,
        };
        auth::strip_recognized_access_credentials(&mut request.params);
        let cancellation =
            CancellationWireMessage::decode(era, CancellationSender::Client, request)
                .map_err(|error| McpError::invalid_params(error.to_string()))?;
        if !principal_binding.verify_existing(fingerprint) {
            return Err(McpError::new(
                McpErrorCode::ResourceForbidden,
                "Authenticated principal does not own an admitted session",
            ));
        }
        Self::enforce_request_context(&request_ctx)?;
        Ok(cancellation)
    }

    #[cfg(feature = "legacy-2024-11-05")]
    fn request_id_is_active(&self, session_id: u64, request_id: &RequestId) -> bool {
        let Ok(key) = ActiveRequestKey::new(session_id, request_id) else {
            return false;
        };
        self.active_requests
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .contains_key(&key)
    }

    /// Requests cancellation of exactly one active request in the originating
    /// session.
    ///
    /// A cancellation notification is advisory: malformed IDs, IDs not owned
    /// by this session, and IDs whose request has already left the registry
    /// are all ignored. In particular, none of those inputs may trigger
    /// cleanup of unrelated bidirectional waiters or alter connection-wide
    /// state.
    fn handle_cancelled_notification(&self, session_id: u64, params: CancelledParams) -> bool {
        self.handle_request_cancellation(session_id, &params.request_id, params.reason.as_deref())
    }

    fn cancellation_wire_request_id(cancellation: &CancellationWireMessage) -> &RequestId {
        match cancellation {
            CancellationWireMessage::Legacy2024 { params, .. } => &params.request_id,
            CancellationWireMessage::Modern2026 { params, .. } => &params.request_id,
        }
    }

    fn handle_cancellation_wire_notification(
        &self,
        session_id: u64,
        cancellation: CancellationWireMessage,
    ) -> bool {
        match cancellation {
            CancellationWireMessage::Legacy2024 { params, .. } => {
                self.handle_cancelled_notification(session_id, params)
            }
            CancellationWireMessage::Modern2026 { params, .. } => self.handle_request_cancellation(
                session_id,
                &params.request_id,
                params.reason.as_deref(),
            ),
        }
    }

    fn handle_request_cancellation(
        &self,
        session_id: u64,
        request_id: &RequestId,
        reason: Option<&str>,
    ) -> bool {
        let reason_present = reason.is_some();
        let reason = reason.unwrap_or("unspecified");
        info!(
            target: targets::SESSION,
            "Cancellation requested for request_key={:016x} (reason_present={}, reason_bytes={})",
            request_id_log_key(request_id),
            reason_present,
            reason.len()
        );
        let Ok(active_key) = ActiveRequestKey::new(session_id, request_id) else {
            debug!(
                target: targets::SESSION,
                "Ignoring cancellation with invalid request key={:016x}",
                request_id_log_key(request_id)
            );
            return false;
        };
        // Keep registry membership and the cancellation transition in the
        // same critical section. A finishing request removes itself under this
        // lock, so a late notification cannot race from an observed entry into
        // a completed request.
        let accepted = {
            let guard = self.active_requests.lock().unwrap_or_else(|poisoned| {
                error!(target: targets::SERVER, "active_requests lock poisoned, recovering");
                poisoned.into_inner()
            });
            guard
                .get(&active_key)
                .map(|entry| entry.cancellation.cancel())
        };
        let Some(accepted) = accepted else {
            debug!(
                target: targets::SESSION,
                "Ignoring cancellation for unknown or completed request_key={:016x}",
                request_id_log_key(request_id)
            );
            return false;
        };

        if !accepted {
            debug!(
                target: targets::SESSION,
                "Ignoring duplicate or finalized cancellation for request_key={:016x}",
                request_id_log_key(request_id)
            );
        }
        accepted
    }

    /// Cancels every active request as part of server-owned shutdown.
    ///
    /// `wait_for_shutdown_cleanup` is an internal lifecycle control and is
    /// deliberately unrelated to MCP cancellation notification parameters.
    fn cancel_active_requests(
        &self,
        kind: CancelKind,
        wait_for_shutdown_cleanup: bool,
    ) -> ShutdownCleanupOutcome {
        let active: Vec<(
            ActiveRequestKey,
            RegionId,
            Arc<OnceLock<Cx>>,
            McpRequestCancellation,
            Arc<RequestCompletion>,
        )> = {
            let guard = self.active_requests.lock().unwrap_or_else(|poisoned| {
                error!(target: targets::SERVER, "active_requests lock poisoned in cancel_active_requests, recovering");
                poisoned.into_inner()
            });
            guard
                .iter()
                .map(|(key, entry)| {
                    (
                        key.clone(),
                        entry.region_id,
                        entry.cx.clone(),
                        entry.cancellation.clone(),
                        entry.completion.clone(),
                    )
                })
                .collect()
        };
        if active.is_empty() {
            return ShutdownCleanupOutcome::Quiescent;
        }
        info!(
            target: targets::SESSION,
            "Cancelling {} active request(s) (kind={:?}, wait_for_shutdown_cleanup={})",
            active.len(),
            kind,
            wait_for_shutdown_cleanup
        );
        for (_, _, cx, cancellation, _) in &active {
            cancellation.cancel();
            if let Some(cx) = cx.get() {
                cx.cancel_with(kind, None);
            }
        }

        if wait_for_shutdown_cleanup {
            let cleanup_started = Instant::now();
            let mut remaining = 0;
            for (key, region_id, _cx, _cancellation, completion) in active {
                let timeout = SHUTDOWN_CLEANUP_TIMEOUT.saturating_sub(cleanup_started.elapsed());
                let completed = completion.wait_timeout(timeout);
                if !completed {
                    remaining += 1;
                    fastmcp_core::logging::warn!(
                        target: targets::SESSION,
                        "Shutdown cancel timed out for session={} request_key={:016x} (ambient_region={:?})",
                        key.session_id,
                        key.log_key(),
                        region_id
                    );
                }
            }
            let still_active = self
                .active_requests
                .lock()
                .unwrap_or_else(|poisoned| {
                    error!(target: targets::SERVER, "active_requests lock poisoned after shutdown cleanup, recovering");
                    poisoned.into_inner()
                })
                .len();
            if remaining != 0 || still_active != 0 {
                return ShutdownCleanupOutcome::TimedOut {
                    remaining: remaining.max(still_active),
                };
            }
        }
        ShutdownCleanupOutcome::Quiescent
    }

    fn handle_set_log_level(&self, session: &mut Session, params: SetLogLevelParams) {
        let requested = match params.level {
            LogLevel::Debug => LevelFilter::Debug,
            LogLevel::Info | LogLevel::Notice => LevelFilter::Info,
            LogLevel::Warning => LevelFilter::Warn,
            LogLevel::Error | LogLevel::Critical | LogLevel::Alert | LogLevel::Emergency => {
                LevelFilter::Error
            }
        };

        let configured = self.logging.level;
        let effective = if requested > configured {
            configured
        } else {
            requested
        };

        if effective == LevelFilter::Off {
            session.restore_log_level(None);
            fastmcp_core::logging::warn!(
                target: targets::SESSION,
                "Client requested log level {:?}; server logging is disabled",
                params.level
            );
            return;
        }

        let effective_level = if effective == requested {
            params.level
        } else {
            match effective {
                LevelFilter::Debug => LogLevel::Debug,
                LevelFilter::Info => LogLevel::Info,
                LevelFilter::Warn => LogLevel::Warning,
                LevelFilter::Error => LogLevel::Error,
                // A client cannot request Trace through MCP; defensively clamp a
                // future/internal Trace value to the most verbose protocol level.
                LevelFilter::Trace => LogLevel::Debug,
                // Handled by the early return above.
                LevelFilter::Off => LogLevel::Error,
            }
        };
        session.set_log_level(effective_level);

        if effective != requested {
            fastmcp_core::logging::warn!(
                target: targets::SESSION,
                "Client requested log level {:?}; provisional session level clamped to server level {:?}",
                params.level,
                effective
            );
        } else {
            info!(
                target: targets::SESSION,
                "Provisional session log level set to {:?}",
                params.level
            );
        }
    }

    fn log_level_rank(level: LogLevel) -> u8 {
        match level {
            LogLevel::Debug => 1,
            LogLevel::Info => 2,
            LogLevel::Notice => 3,
            LogLevel::Warning => 4,
            LogLevel::Error => 5,
            LogLevel::Critical => 6,
            LogLevel::Alert => 7,
            LogLevel::Emergency => 8,
        }
    }

    fn request_progress_marker(request: &JsonRpcRequest) -> Option<ProgressMarker> {
        request
            .params
            .as_ref()?
            .get("_meta")?
            .get("progressToken")
            .cloned()
            .and_then(|marker| serde_json::from_value(marker).ok())
    }

    fn final_log_level_rank(level: LoggingLevel) -> u8 {
        match level {
            LoggingLevel::Debug => 1,
            LoggingLevel::Info => 2,
            LoggingLevel::Notice => 3,
            LoggingLevel::Warning => 4,
            LoggingLevel::Error => 5,
            LoggingLevel::Critical => 6,
            LoggingLevel::Alert => 7,
            LoggingLevel::Emergency => 8,
        }
    }

    fn final_logging_ceiling(&self) -> Option<LoggingLevel> {
        match self.logging.level {
            LevelFilter::Off => None,
            LevelFilter::Trace | LevelFilter::Debug => Some(LoggingLevel::Debug),
            LevelFilter::Info => Some(LoggingLevel::Info),
            LevelFilter::Warn => Some(LoggingLevel::Warning),
            LevelFilter::Error => Some(LoggingLevel::Error),
        }
    }

    fn mcp_log_level_from_final(level: LoggingLevel) -> McpLogLevel {
        match level {
            LoggingLevel::Debug => McpLogLevel::Debug,
            LoggingLevel::Info => McpLogLevel::Info,
            LoggingLevel::Notice => McpLogLevel::Notice,
            LoggingLevel::Warning => McpLogLevel::Warning,
            LoggingLevel::Error => McpLogLevel::Error,
            LoggingLevel::Critical => McpLogLevel::Critical,
            LoggingLevel::Alert => McpLogLevel::Alert,
            LoggingLevel::Emergency => McpLogLevel::Emergency,
        }
    }

    fn final_request_log_level(&self, request: &JsonRpcRequest) -> Option<LoggingLevel> {
        if modern_protocol_version(request) != Some(MODERN_PROTOCOL_VERSION) {
            return None;
        }
        let entries: BTreeMap<String, serde_json::Value> = request
            .params
            .as_ref()?
            .get("_meta")?
            .as_object()?
            .iter()
            .map(|(key, value)| (key.clone(), value.clone()))
            .collect();
        let requested = OpenMetadata::try_from_entries(entries)
            .ok()?
            .log_level()
            .ok()??;
        let ceiling = self.final_logging_ceiling()?;
        Some(
            if Self::final_log_level_rank(requested) < Self::final_log_level_rank(ceiling) {
                ceiling
            } else {
                requested
            },
        )
    }

    fn modern_request_requires_owned_sse(&self, request: &JsonRpcRequest) -> bool {
        if request.id.is_none() || request.method.starts_with("notifications/") {
            return false;
        }
        if Self::request_progress_marker(request).is_some() {
            return true;
        }
        self.final_request_log_level(request)
            .is_some_and(|minimum| {
                Self::final_log_level_rank(LoggingLevel::Error)
                    >= Self::final_log_level_rank(minimum)
            })
    }

    fn final_log_notification_metadata(&self) -> Option<OpenMetadata> {
        let server_info =
            Implementation::try_new(self.info.name.clone(), self.info.version.clone()).ok()?;
        OpenMetadata::try_from_entries([(
            FINAL_SERVER_INFO_META_KEY.to_owned(),
            serde_json::to_value(server_info).ok()?,
        )])
        .ok()
    }

    fn maybe_emit_final_log_notification(
        &self,
        request: &JsonRpcRequest,
        sender: &NotificationSender,
        result_is_ok: bool,
    ) {
        if request.method.starts_with("notifications/") {
            return;
        }
        let Some(min_level) = self.final_request_log_level(request) else {
            return;
        };
        let level = if result_is_ok {
            LoggingLevel::Info
        } else {
            LoggingLevel::Error
        };
        if Self::final_log_level_rank(level) < Self::final_log_level_rank(min_level) {
            return;
        }
        let Some(meta) = self.final_log_notification_metadata() else {
            return;
        };
        let method_key = safe_peer_log_key(&request.method);
        let message = if result_is_ok {
            format!("Handled method={method_key}")
        } else {
            format!("Error handling method={method_key}")
        };
        let notification = ServerNotification::Message(FinalLogMessageParams {
            level,
            logger: Some("fastmcp_rust::server".to_owned()),
            data: serde_json::Value::String(message),
            meta: Some(meta),
            additional: BTreeMap::new(),
        })
        .encode();
        let Ok(notification) = notification else {
            return;
        };
        if catch_extension_unwind(|| sender(notification)).is_err() {
            let _ = extension_panic_error("final_log_notification_sender");
        }
    }

    fn emit_log_notification_for_level(
        &self,
        min_level: Option<LogLevel>,
        sender: &NotificationSender,
        level: LogLevel,
        message: impl Into<String>,
    ) {
        let Some(min_level) = min_level else {
            return;
        };
        if Self::log_level_rank(level) < Self::log_level_rank(min_level) {
            return;
        }

        let ts = chrono::Utc::now().to_rfc3339();
        let text = format!("{ts} {}", message.into());
        let params = LogMessageParams {
            level,
            logger: Some("fastmcp_rust::server".to_string()),
            data: serde_json::Value::String(text),
        };
        let payload = match serde_json::to_value(params) {
            Ok(value) => value,
            Err(err) => {
                fastmcp_core::logging::warn!(
                    target: targets::SESSION,
                    "Failed to serialize log message notification: {}",
                    err
                );
                return;
            }
        };
        let notification = JsonRpcRequest::notification("notifications/message", Some(payload));
        if catch_extension_unwind(|| sender(notification)).is_err() {
            // Notification delivery is an application-supplied extension
            // boundary. A broken callback must not unwind across dispatch and
            // discard the already-computed JSON-RPC response. Keep both this
            // diagnostic and the panic hook payload-free.
            let _ = extension_panic_error("log_notification_sender");
        }
    }

    fn emit_log_notification(
        &self,
        session: &Session,
        sender: &NotificationSender,
        level: LogLevel,
        message: impl Into<String>,
    ) {
        self.emit_log_notification_for_level(session.log_level(), sender, level, message);
    }

    #[cfg(feature = "legacy-2024-11-05")]
    fn maybe_emit_log_notification_for_level(
        &self,
        min_level: Option<LogLevel>,
        sender: &NotificationSender,
        method: &str,
        result: &McpResult<serde_json::Value>,
    ) {
        if method.starts_with("notifications/") || method == "logging/setLevel" {
            return;
        }
        let level = if result.is_ok() {
            LogLevel::Info
        } else {
            LogLevel::Error
        };
        let method_key = safe_peer_log_key(method);
        let message = if result.is_ok() {
            format!("Handled method={method_key}")
        } else {
            format!("Error handling method={method_key}")
        };
        self.emit_log_notification_for_level(min_level, sender, level, message);
    }

    fn maybe_emit_log_notification(
        &self,
        session: &Session,
        sender: &NotificationSender,
        method: &str,
        result: &McpResult<serde_json::Value>,
    ) {
        if method.starts_with("notifications/") || method == "logging/setLevel" {
            return;
        }
        let level = if result.is_ok() {
            LogLevel::Info
        } else {
            LogLevel::Error
        };
        let method_key = safe_peer_log_key(method);
        let message = if result.is_ok() {
            format!("Handled method={method_key}")
        } else {
            format!("Error handling method={method_key}")
        };
        self.emit_log_notification(session, sender, level, message);
    }
}

/// Upper bound for server-owned shutdown settlement after cancellation.
const SHUTDOWN_CLEANUP_TIMEOUT: Duration = Duration::from_secs(5);

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ShutdownCleanupOutcome {
    Quiescent,
    TimedOut { remaining: usize },
}

impl ShutdownCleanupOutcome {
    fn into_error(self) -> Option<McpError> {
        match self {
            Self::Quiescent => None,
            Self::TimedOut { remaining } => Some(McpError::with_data(
                McpErrorCode::InternalError,
                "Server shutdown cleanup did not quiesce within its bound",
                serde_json::json!({
                    "stage": "shutdown",
                    "kind": "non_quiescent",
                    "remaining": remaining,
                }),
            )),
        }
    }
}

struct RequestCompletion {
    done: Mutex<bool>,
    cv: Condvar,
}

impl RequestCompletion {
    fn new() -> Self {
        Self {
            done: Mutex::new(false),
            cv: Condvar::new(),
        }
    }

    fn mark_done(&self) {
        let mut done = self
            .done
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if !*done {
            *done = true;
            self.cv.notify_all();
        }
    }

    fn wait_timeout(&self, timeout: Duration) -> bool {
        let mut done = self
            .done
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if *done {
            return true;
        }
        let start = Instant::now();
        let mut remaining = timeout;
        loop {
            let (guard, result) = self
                .cv
                .wait_timeout(done, remaining)
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            done = guard;
            if *done {
                return true;
            }
            if result.timed_out() {
                return false;
            }
            let elapsed = start.elapsed();
            remaining = match timeout.checked_sub(elapsed) {
                Some(left) if !left.is_zero() => left,
                _ => return false,
            };
        }
    }

    #[cfg(test)]
    fn is_done(&self) -> bool {
        let done = self
            .done
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        *done
    }
}

struct ActiveRequest {
    cx: Arc<OnceLock<Cx>>,
    cancellation: McpRequestCancellation,
    region_id: RegionId,
    completion: Arc<RequestCompletion>,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct ActiveRequestKey {
    session_id: u64,
    correlation_key: CorrelationKey,
}

impl ActiveRequestKey {
    fn new(session_id: u64, request_id: &RequestId) -> Result<Self, &'static str> {
        Ok(Self {
            session_id,
            correlation_key: request_id.correlation_key()?,
        })
    }

    fn log_key(&self) -> u64 {
        let (domain, value) = match &self.correlation_key {
            CorrelationKey::String(value) => ("string:", value),
            CorrelationKey::Integer(value) => ("integer:", value),
        };
        stable_hash_request_id(domain) ^ stable_hash_request_id(value)
    }
}

impl ActiveRequest {
    #[cfg(test)]
    fn new(cx: Cx, completion: Arc<RequestCompletion>) -> Self {
        Self::with_cancellation(cx, completion, McpRequestCancellation::new())
    }

    fn with_cancellation(
        cx: Cx,
        completion: Arc<RequestCompletion>,
        cancellation: McpRequestCancellation,
    ) -> Self {
        let region_id = cx.region_id();
        Self {
            cx: Arc::new(OnceLock::from(cx)),
            cancellation,
            region_id,
            completion,
        }
    }
}

struct ActiveRequestGuard {
    map: Arc<Mutex<HashMap<ActiveRequestKey, ActiveRequest>>>,
    key: ActiveRequestKey,
    cx: Arc<OnceLock<Cx>>,
    cancellation: McpRequestCancellation,
    completion: Arc<RequestCompletion>,
}

impl ActiveRequestGuard {
    #[cfg(test)]
    fn try_new(
        map: Arc<Mutex<HashMap<ActiveRequestKey, ActiveRequest>>>,
        session_id: u64,
        id: RequestId,
        cx: Cx,
    ) -> Result<Self, RequestId> {
        Self::try_new_with_cancellation(map, session_id, id, cx, McpRequestCancellation::new())
    }

    fn try_new_with_cancellation(
        map: Arc<Mutex<HashMap<ActiveRequestKey, ActiveRequest>>>,
        session_id: u64,
        id: RequestId,
        cx: Cx,
        cancellation: McpRequestCancellation,
    ) -> Result<Self, RequestId> {
        let completion = Arc::new(RequestCompletion::new());
        let entry = ActiveRequest::with_cancellation(cx, completion, cancellation);
        Self::try_insert(map, session_id, id, entry)
    }

    fn try_reserve(
        map: Arc<Mutex<HashMap<ActiveRequestKey, ActiveRequest>>>,
        session_id: u64,
        id: RequestId,
        owner_region_id: RegionId,
        cancellation: McpRequestCancellation,
    ) -> Result<Self, RequestId> {
        Self::try_insert(
            map,
            session_id,
            id,
            ActiveRequest {
                cx: Arc::new(OnceLock::new()),
                cancellation,
                region_id: owner_region_id,
                completion: Arc::new(RequestCompletion::new()),
            },
        )
    }

    fn try_insert(
        map: Arc<Mutex<HashMap<ActiveRequestKey, ActiveRequest>>>,
        session_id: u64,
        id: RequestId,
        entry: ActiveRequest,
    ) -> Result<Self, RequestId> {
        let key = ActiveRequestKey::new(session_id, &id).map_err(|_| id.clone())?;
        let cx = Arc::clone(&entry.cx);
        let completion = Arc::clone(&entry.completion);
        let cancellation = entry.cancellation.clone();
        let mut guard = map
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if guard.contains_key(&key) {
            fastmcp_core::logging::warn!(
                target: targets::SESSION,
                "Duplicate active request_key={:016x} rejected while an earlier request is still running",
                request_id_log_key(&id)
            );
            return Err(id);
        }
        guard.insert(key.clone(), entry);
        drop(guard);
        Ok(Self {
            map,
            key,
            cx,
            cancellation,
            completion,
        })
    }

    fn activate(&self, cx: Cx) -> bool {
        // Publish before checking the token. Shutdown cancels the token before
        // reading this same cell, so either it sees the child or activation
        // observes cancellation. Never cancel the receive pump's parent Cx.
        if self.cx.set(cx.clone()).is_err() {
            return false;
        }
        if self.cancellation.is_cancel_requested() {
            cx.cancel_with(CancelKind::Shutdown, None);
            return false;
        }
        true
    }

    fn cancellation(&self) -> McpRequestCancellation {
        self.cancellation.clone()
    }
}

impl Drop for ActiveRequestGuard {
    fn drop(&mut self) {
        {
            let mut guard = self
                .map
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            match guard.get(&self.key) {
                Some(entry) if Arc::ptr_eq(&entry.completion, &self.completion) => {
                    guard.remove(&self.key);
                }
                Some(_) => {
                    fastmcp_core::logging::warn!(
                        target: targets::SESSION,
                        "Active request replaced before drop for session={} request_key={:016x}",
                        self.key.session_id,
                        self.key.log_key()
                    );
                }
                None => {
                    fastmcp_core::logging::warn!(
                        target: targets::SESSION,
                        "Active request missing on drop for session={} request_key={:016x}",
                        self.key.session_id,
                        self.key.log_key()
                    );
                }
            }
        }
        self.completion.mark_done();
    }
}

/// Keeps request cancellation ownership and reversible session mutations alive
/// until a direct caller accepts the response or the transport path has
/// acquired exclusive output ownership for one response attempt.
///
/// Exclusive ownership prevents another frame from overtaking the response,
/// but synchronous `Write`/`flush` remain fallible and cannot provide an atomic
/// wire-commit primitive. A failed attempt therefore still rolls back reversible
/// session mutations and is never counted as a sent response.
struct HandledRequest {
    response: JsonRpcResponse,
    cancellation: Option<McpRequestCancellation>,
    suppress_cancelled_response: bool,
    _active_guard: Option<ActiveRequestGuard>,
    session_mutation_rollback: Option<SessionMutationRollback>,
    deferred_stats: Option<DeferredRequestStats>,
    commit_liveness: Option<CommitLiveness>,
}

struct CommitLiveness {
    cx: Cx,
    budget: Budget,
}

#[derive(Clone, Copy)]
enum DeferredRequestOutcome {
    Success,
    Failure,
    Cancelled,
}

struct DeferredRequestStats {
    collector: ServerStats,
    method: String,
    started_at: Instant,
    outcome: DeferredRequestOutcome,
}

impl DeferredRequestStats {
    fn new(
        collector: Option<&ServerStats>,
        method: &str,
        started_at: Instant,
        outcome: DeferredRequestOutcome,
    ) -> Option<Self> {
        collector.map(|collector| Self {
            collector: collector.clone(),
            method: method.to_string(),
            started_at,
            outcome,
        })
    }

    fn record(self) {
        let latency = self.started_at.elapsed();
        match self.outcome {
            DeferredRequestOutcome::Success => {
                self.collector.record_request(&self.method, latency, true);
            }
            DeferredRequestOutcome::Failure => {
                self.collector.record_request(&self.method, latency, false);
            }
            DeferredRequestOutcome::Cancelled => {
                self.collector.record_cancelled(&self.method, latency);
            }
        }
    }
}

impl HandledRequest {
    fn untracked(response: JsonRpcResponse) -> Self {
        Self {
            response,
            cancellation: None,
            suppress_cancelled_response: false,
            _active_guard: None,
            session_mutation_rollback: None,
            deferred_stats: None,
            commit_liveness: None,
        }
    }

    fn tracked(
        response: JsonRpcResponse,
        cancellation: McpRequestCancellation,
        active_guard: Option<ActiveRequestGuard>,
        session_mutation_rollback: Option<SessionMutationRollback>,
        commit_cx: Cx,
        commit_budget: Budget,
    ) -> Self {
        Self {
            response,
            cancellation: Some(cancellation),
            suppress_cancelled_response: false,
            _active_guard: active_guard,
            session_mutation_rollback,
            deferred_stats: None,
            commit_liveness: Some(CommitLiveness {
                cx: commit_cx,
                budget: commit_budget,
            }),
        }
    }

    fn with_deferred_stats(mut self, deferred_stats: Option<DeferredRequestStats>) -> Self {
        self.deferred_stats = deferred_stats;
        self
    }

    fn suppress_cancelled_response(mut self) -> Self {
        self.suppress_cancelled_response = true;
        self
    }

    fn commit_liveness_error(&self) -> Option<McpError> {
        self.commit_liveness
            .as_ref()
            .and_then(|liveness| Server::request_budget_error(&liveness.cx, liveness.budget))
    }

    fn replace_with_terminal_error(&mut self, session: &mut Session, error: McpError) {
        if let Some(rollback) = self.session_mutation_rollback.take() {
            rollback.apply(session);
        }
        if let Some(stats) = self.deferred_stats.as_mut() {
            stats.outcome = DeferredRequestOutcome::Cancelled;
        }
        self.response = JsonRpcResponse::error(
            self.response.id.clone(),
            JsonRpcError {
                code: error.code.into(),
                message: error.message,
                data: error.data,
            },
        );
    }

    /// Resolves the final response/cancellation race and reports whether an
    /// explicit request cancellation won. Ambient cancellation and deadline
    /// expiry still produce their ordinary terminal error response.
    fn resolve_commit_race(&mut self, session: &mut Session) -> bool {
        // An explicit in-band cancellation that already linearized wins
        // outright: its suppression contract holds even when ambient shutdown
        // or deadline expiry lands concurrently with response finalization.
        // This must not eagerly CAS to FINALIZING, because ambient death below
        // still needs to propagate into the token for `cancelled()` waiters.
        let explicit_cancellation_linearized = self
            .cancellation
            .as_ref()
            .is_some_and(McpRequestCancellation::is_cancel_requested);
        if explicit_cancellation_linearized {
            // A server-side graceful election cancels its listen as the
            // dispatch wake; the elected terminal completion is that
            // request's sanctioned final frame, not a response that lost a
            // cancellation race.
            if final_subscription_completion_response(&self.response) {
                return false;
            }
            self.replace_with_terminal_error(session, McpError::request_cancelled());
            return true;
        }

        if let Some(error) = self.commit_liveness_error() {
            if let Some(cancellation) = &self.cancellation {
                let _ = cancellation.cancel();
            }
            self.replace_with_terminal_error(session, error);
            return false;
        }

        let cancellation_won = self
            .cancellation
            .as_ref()
            .is_some_and(|cancellation| !cancellation.begin_finalization());
        if cancellation_won {
            if final_subscription_completion_response(&self.response) {
                return false;
            }
            self.replace_with_terminal_error(session, McpError::request_cancelled());
            return true;
        }

        // The token CAS is the explicit-cancellation linearization point. A
        // second ambient/deadline check closes the interval between the first
        // liveness snapshot and that CAS. Cancellation after this snapshot
        // loses to response finalization.
        if let Some(error) = self.commit_liveness_error() {
            self.replace_with_terminal_error(session, error);
        }
        false
    }

    fn finalize_for_return(mut self, session: &mut Session) -> JsonRpcResponse {
        let _ = self.resolve_commit_race(session);
        self.session_mutation_rollback.take();
        if let Some(stats) = self.deferred_stats.take() {
            stats.record();
        }
        self.response
    }

    #[cfg(feature = "legacy-2024-11-05")]
    fn send_with<F>(
        mut self,
        session: &mut Session,
        send: F,
    ) -> Result<Option<JsonRpcResponse>, TransportError>
    where
        F: FnOnce(&JsonRpcResponse) -> Result<(), TransportError>,
    {
        // Callers must acquire exclusive output ownership before entering this
        // method. Finalization then linearizes against cancellation immediately
        // before the single fallible write/flush attempt.
        let cancellation_won = self.resolve_commit_race(session);
        if cancellation_won && self.suppress_cancelled_response {
            if let Some(stats) = self.deferred_stats.take() {
                stats.record();
            }
            return Ok(None);
        }
        match send(&self.response) {
            Ok(()) => {
                self.session_mutation_rollback.take();
                if let Some(stats) = self.deferred_stats.take() {
                    stats.record();
                }
                Ok(Some(self.response))
            }
            Err(error) => {
                if let Some(rollback) = self.session_mutation_rollback.take() {
                    rollback.apply(session);
                }
                Err(error)
            }
        }
    }
}

/// Checks if banner should be suppressed via environment variable.
///
/// This is a legacy check. Prefer using `ConsoleConfig` for banner control.
fn banner_suppressed() -> bool {
    std::env::var("FASTMCP_NO_BANNER")
        .map(|value| matches!(value.to_lowercase().as_str(), "1" | "true" | "yes"))
        .unwrap_or(false)
}

/// Parses required parameters from JSON.
fn parse_params<T: serde::de::DeserializeOwned>(
    params: Option<serde_json::Value>,
) -> Result<T, McpError> {
    let value = params.ok_or_else(|| McpError::invalid_params("Missing required parameters"))?;
    serde_json::from_value(value).map_err(|e| McpError::invalid_params(e.to_string()))
}

/// Parses optional parameters from JSON, using default if not provided.
fn parse_params_or_default<T: serde::de::DeserializeOwned + Default>(
    params: Option<serde_json::Value>,
) -> Result<T, McpError> {
    match params {
        Some(value) => {
            serde_json::from_value(value).map_err(|e| McpError::invalid_params(e.to_string()))
        }
        None => Ok(T::default()),
    }
}

/// Converts a JSON-RPC RequestId to a u64 for internal tracking.
///
/// If the ID is representable as an `i64`, uses that number. Arbitrary-
/// precision integer and string IDs use a stable hash; absent IDs use zero.
fn request_id_to_u64(id: Option<&RequestId>) -> u64 {
    match id {
        Some(RequestId::Number(n)) => *n as u64,
        Some(RequestId::Integer(integer)) => stable_hash_request_id(integer),
        Some(RequestId::String(s)) => stable_hash_request_id(s),
        None => 0,
    }
}

fn request_id_log_key(id: &RequestId) -> u64 {
    request_id_to_u64(Some(id))
}

const PEER_LOG_KEY_INPUT_BYTES: usize = 4 * 1024;
const PEER_LOG_KEY_PREFIX_BYTES: usize = 8;

#[derive(Clone, Copy)]
struct SafePeerLogKey {
    byte_len: usize,
    hashed_bytes: usize,
    digest_prefix: [u8; PEER_LOG_KEY_PREFIX_BYTES],
}

impl std::fmt::Display for SafePeerLogKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "bytes={},sha256_prefix=", self.byte_len)?;
        for byte in self.digest_prefix {
            write!(f, "{byte:02x}")?;
        }
        if self.hashed_bytes < self.byte_len {
            write!(f, ",hashed_prefix_bytes={}", self.hashed_bytes)?;
        }
        Ok(())
    }
}

fn safe_peer_log_key(value: &str) -> SafePeerLogKey {
    let bytes = value.as_bytes();
    let hashed_bytes = bytes.len().min(PEER_LOG_KEY_INPUT_BYTES);
    let mut digest_prefix = [0_u8; PEER_LOG_KEY_PREFIX_BYTES];
    if let Ok(digest) = sha256_bounded(&bytes[..hashed_bytes], PEER_LOG_KEY_INPUT_BYTES) {
        digest_prefix.copy_from_slice(&digest.as_bytes()[..PEER_LOG_KEY_PREFIX_BYTES]);
    }
    SafePeerLogKey {
        byte_len: bytes.len(),
        hashed_bytes,
        digest_prefix,
    }
}

fn stable_hash_request_id(value: &str) -> u64 {
    const FNV_OFFSET: u64 = 0xcbf29ce484222325;
    const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
    let mut hash = FNV_OFFSET;
    for byte in value.as_bytes() {
        hash ^= u64::from(*byte);
        hash = hash.wrapping_mul(FNV_PRIME);
    }
    if hash == 0 { FNV_OFFSET } else { hash }
}

/// An unsplit [`Transport`] shared by the receive pump and every writer.
///
/// `recv` and `send` both need `&mut T`, so the pump owns the I/O handle for as
/// long as a `recv` blocks. A send from another thread in that window (a listen
/// acknowledgement, a notification, a worker's response) is queued in
/// [`UnsplitOutput`] instead of failing, and the owner writes the queue in
/// order before it gives the handle up. Output produced while `recv` blocks
/// therefore reaches the peer as soon as that `recv` returns, ahead of anything
/// written later (bd-8bcfq).
struct SharedTransport<T> {
    inner: Arc<Mutex<Option<T>>>,
    output: Arc<UnsplitOutput>,
}

/// Output queued behind one owner of an unsplit transport is bounded; past
/// this a send fails instead of growing without limit.
const UNSPLIT_OUTPUT_QUEUE_LIMIT: usize = 1024;

struct UnsplitOutput {
    state: Mutex<UnsplitOutputState>,
    released: Condvar,
    /// Latched when queued output cannot be written. Its senders were already
    /// told `Ok`, so the pump must fail the connection rather than lose it.
    failure: Arc<AtomicBool>,
}

#[derive(Default)]
struct UnsplitOutputState {
    owned: bool,
    queue: VecDeque<JsonRpcMessage>,
    failed: bool,
}

impl UnsplitOutput {
    fn new(failure: Arc<AtomicBool>) -> Self {
        Self {
            state: Mutex::new(UnsplitOutputState::default()),
            released: Condvar::new(),
            failure,
        }
    }

    fn state(&self) -> std::sync::MutexGuard<'_, UnsplitOutputState> {
        self.state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    /// Takes the handle for a receive or close, waiting out a writer.
    fn claim(&self) -> UnsplitOwnership<'_> {
        let mut state = self.state();
        while state.owned {
            state = self
                .released
                .wait(state)
                .unwrap_or_else(std::sync::PoisonError::into_inner);
        }
        state.owned = true;
        UnsplitOwnership {
            output: self,
            released: false,
        }
    }

    /// Takes the handle for a send, or queues `message` behind the current
    /// owner, which writes it before releasing the handle (`Ok(None)`).
    fn claim_or_queue(
        &self,
        message: &JsonRpcMessage,
    ) -> Result<Option<UnsplitOwnership<'_>>, TransportError> {
        let mut state = self.state();
        if state.failed {
            return Err(TransportError::Io(std::io::Error::other(
                "an earlier queued send on this unsplit transport failed",
            )));
        }
        if !state.owned {
            state.owned = true;
            return Ok(Some(UnsplitOwnership {
                output: self,
                released: false,
            }));
        }
        if state.queue.len() >= UNSPLIT_OUTPUT_QUEUE_LIMIT {
            return Err(TransportError::Io(std::io::Error::new(
                std::io::ErrorKind::WouldBlock,
                "unsplit transport output queue is full while another caller owns the I/O handle",
            )));
        }
        state.queue.push_back(message.clone());
        Ok(None)
    }

    fn fail(&self, error: &TransportError) {
        self.state().failed = true;
        self.failure.store(true, Ordering::Release);
        log::error!(
            target: targets::TRANSPORT,
            "Failed to send queued unsplit transport output: {}",
            error
        );
    }
}

/// Ownership of an unsplit transport's I/O handle. Releasing it writes all
/// output queued behind it first; an unwind releases it without writing.
struct UnsplitOwnership<'a> {
    output: &'a UnsplitOutput,
    released: bool,
}

impl UnsplitOwnership<'_> {
    fn release<T: Transport>(mut self, cx: &Cx, mut transport: Option<&mut T>) {
        loop {
            let batch = {
                let mut state = self.output.state();
                if state.queue.is_empty() {
                    // Checked and released under one lock, so a sender either
                    // queued before this point or finds the handle free.
                    state.owned = false;
                    drop(state);
                    self.released = true;
                    self.output.released.notify_all();
                    return;
                }
                std::mem::take(&mut state.queue)
            };
            let Some(writer) = transport.as_deref_mut() else {
                // Closed (or already failed): nothing queued can be written.
                continue;
            };
            for message in &batch {
                if let Err(error) = writer.send(cx, message) {
                    if !error.is_cancelled() {
                        self.output.fail(&error);
                    }
                    transport = None;
                    break;
                }
            }
        }
    }
}

impl Drop for UnsplitOwnership<'_> {
    fn drop(&mut self) {
        if self.released {
            return;
        }
        let mut state = self.output.state();
        state.owned = false;
        if !state.queue.is_empty() {
            state.queue.clear();
            state.failed = true;
            self.output.failure.store(true, Ordering::Release);
        }
        drop(state);
        self.output.released.notify_all();
    }
}

struct SharedRecvHalf<R> {
    inner: Arc<Mutex<R>>,
}

impl<R> Clone for SharedRecvHalf<R> {
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
        }
    }
}

impl<R: TransportRecvHalf> SharedRecvHalf<R> {
    fn new(inner: R) -> Self {
        Self {
            inner: Arc::new(Mutex::new(inner)),
        }
    }

    fn recv(&self, cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
        self.inner
            .lock()
            .map_err(|_| transport_lock_error())?
            .recv(cx)
    }

    fn close(&self, cx: &Cx) -> Result<(), TransportError> {
        self.inner
            .lock()
            .map_err(|_| transport_lock_error())?
            .close(cx)
    }
}

struct SharedSendHalf<S> {
    inner: Arc<Mutex<S>>,
}

impl<S> Clone for SharedSendHalf<S> {
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
        }
    }
}

impl<S: TransportSendHalf> SharedSendHalf<S> {
    fn new(inner: S) -> Self {
        Self {
            inner: Arc::new(Mutex::new(inner)),
        }
    }

    fn send(&self, cx: &Cx, message: &JsonRpcMessage) -> Result<(), TransportError> {
        self.inner
            .lock()
            .map_err(|_| transport_lock_error())?
            .send(cx, message)
    }

    fn close(&self, cx: &Cx) -> Result<(), TransportError> {
        self.inner
            .lock()
            .map_err(|_| transport_lock_error())?
            .close(cx)
    }
}

impl<T> Clone for SharedTransport<T> {
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
            output: Arc::clone(&self.output),
        }
    }
}

impl<T: Transport> SharedTransport<T> {
    #[cfg(test)]
    fn new(transport: T) -> Self {
        Self::with_output_failure(transport, Arc::new(AtomicBool::new(false)))
    }

    /// `output_failure` is latched when output queued during another owner's
    /// I/O cannot be written; the pump checks it after every `recv`.
    fn with_output_failure(transport: T, output_failure: Arc<AtomicBool>) -> Self {
        Self {
            inner: Arc::new(Mutex::new(Some(transport))),
            output: Arc::new(UnsplitOutput::new(output_failure)),
        }
    }

    fn recv(&self, cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
        let ownership = self.output.claim();
        let mut guard = self.inner.lock().map_err(|_| transport_lock_error())?;
        let result = guard
            .as_mut()
            .map_or(Err(TransportError::Closed), |transport| transport.recv(cx));
        // Output queued while this `recv` blocked goes out before the pump
        // dispatches what it returned.
        ownership.release(cx, guard.as_mut());
        result
    }

    fn send(&self, cx: &Cx, message: &JsonRpcMessage) -> Result<(), TransportError> {
        let Some(ownership) = self.output.claim_or_queue(message)? else {
            return Ok(());
        };
        let mut guard = self.inner.lock().map_err(|_| transport_lock_error())?;
        let result = guard
            .as_mut()
            .map_or(Err(TransportError::Closed), |transport| {
                transport.send(cx, message)
            });
        ownership.release(cx, guard.as_mut());
        result
    }

    fn close(&self, cx: &Cx) -> Result<(), TransportError> {
        let ownership = self.output.claim();
        let transport = {
            let mut guard = self.inner.lock().map_err(|_| transport_lock_error())?;
            ownership.release(cx, guard.as_mut());
            guard.take()
        };
        let Some(mut transport) = transport else {
            return Ok(());
        };
        transport.close(cx)
    }
}

fn transport_lock_error() -> TransportError {
    TransportError::Io(std::io::Error::other("transport lock poisoned"))
}

fn create_transport_notification_sender<T>(
    transport: SharedTransport<T>,
    cx: Cx,
    failure: Arc<AtomicBool>,
) -> NotificationSender
where
    T: Transport + Send + 'static,
{
    Arc::new(move |request: JsonRpcRequest| {
        let message = JsonRpcMessage::Request(request);
        if let Err(e) = transport.send(&cx, &message) {
            if !e.is_cancelled() {
                failure.store(true, Ordering::Release);
            }
            log::error!(
                target: targets::TRANSPORT,
                "Failed to send notification: {}",
                e
            );
        }
    })
}

fn create_split_transport_notification_sender<S>(
    transport: SharedSendHalf<S>,
    cx: Cx,
    failure: Arc<AtomicBool>,
) -> NotificationSender
where
    S: TransportSendHalf + 'static,
{
    Arc::new(move |request: JsonRpcRequest| {
        if let Err(error) = transport.send(&cx, &JsonRpcMessage::Request(request))
            && !error.is_cancelled()
        {
            failure.store(true, Ordering::Release);
        }
    })
}

fn combine_split_transport_results(
    run: McpResult<()>,
    recv_close: McpResult<()>,
    send_close: McpResult<()>,
) -> McpResult<()> {
    [recv_close, send_close]
        .into_iter()
        .fold(run, |result, close| match (result, close) {
            (Ok(()), Ok(())) => Ok(()),
            (Err(error), Ok(())) | (Ok(()), Err(error)) => Err(error),
            (Err(run_error), Err(close_error)) => {
                Err(combined_run_and_close_error(run_error, close_error))
            }
        })
}

/// Creates a notification sender that writes JSON-RPC notifications to stdout.
///
/// This creates a separate stdout handle for sending notifications, allowing
/// notifications (like progress updates) to be sent during handler execution
/// independently of the main transport.
///
/// The sender uses NDJSON format (newline-delimited JSON) to match the
/// standard MCP transport format.
fn create_notification_sender(fatal_output: Arc<AtomicBool>) -> NotificationSender {
    use std::sync::Mutex;

    // Use AsyncStdout so notifications share the global stdout lock used by
    // the transport writer, preventing interleaved NDJSON writes.
    let stdout = Mutex::new(AsyncStdout::new());
    let codec = Codec::new();

    Arc::new(move |request: JsonRpcRequest| {
        let bytes = match codec.encode_request(&request) {
            Ok(b) => b,
            Err(e) => {
                log::error!(target: targets::SERVER, "Failed to encode notification: {}", e);
                fatal_output.store(true, Ordering::Release);
                return;
            }
        };

        let Ok(mut stdout) = stdout.lock() else {
            log::error!(target: targets::SERVER, "Failed to acquire stdout lock for notification");
            fatal_output.store(true, Ordering::Release);
            return;
        };
        #[cfg(unix)]
        let write_result = stdout.write_all_bounded(&bytes, STDIO_OUTPUT_COMMIT_TIMEOUT);
        #[cfg(not(unix))]
        let write_result = stdout.write_all_unchecked(&bytes);
        if let Err(e) = write_result {
            log::error!(target: targets::TRANSPORT, "Failed to send notification: {}", e);
            fatal_output.store(true, Ordering::Release);
            #[cfg(not(unix))]
            return;
        }
        #[cfg(not(unix))]
        if let Err(e) = stdout.flush_unchecked() {
            log::error!(target: targets::TRANSPORT, "Failed to flush notification: {}", e);
            fatal_output.store(true, Ordering::Release);
        }
    })
}

/// Test-only construction of this build's live HTTP endpoint.
///
/// The dual-era build takes the origin its exact-legacy SSE route advertises;
/// a no-legacy build has no such route and takes none. A modern test names an
/// origin once and runs in both feature lanes.
#[cfg(test)]
pub(crate) trait TestHttpEndpoint {
    fn test_http_endpoint(
        self,
        legacy_origin: &str,
    ) -> Result<ServerHttpEndpoint, ServerHttpEndpointError>;
}

#[cfg(test)]
impl TestHttpEndpoint for Server {
    fn test_http_endpoint(
        self,
        legacy_origin: &str,
    ) -> Result<ServerHttpEndpoint, ServerHttpEndpointError> {
        #[cfg(feature = "legacy-2024-11-05")]
        {
            self.into_http_endpoint(legacy_origin)
        }
        #[cfg(not(feature = "legacy-2024-11-05"))]
        {
            let _ = legacy_origin;
            self.into_http_endpoint()
        }
    }
}

#[cfg(test)]
impl TestHttpEndpoint for ServerBuilder {
    fn test_http_endpoint(
        self,
        legacy_origin: &str,
    ) -> Result<ServerHttpEndpoint, ServerHttpEndpointError> {
        #[cfg(feature = "legacy-2024-11-05")]
        {
            self.build_http_endpoint(legacy_origin)
        }
        #[cfg(not(feature = "legacy-2024-11-05"))]
        {
            let _ = legacy_origin;
            self.build_http_endpoint()
        }
    }
}

#[cfg(test)]
mod lib_unit_tests {
    use super::*;
    use asupersync::io::AsyncReadExt;
    use asupersync::runtime::RuntimeBuilder;
    use asupersync::runtime::reactor::create_reactor;
    use fastmcp_derive::tool;
    #[cfg(feature = "tasks")]
    use fastmcp_protocol::ExtensionDescriptorRegistry;
    use fastmcp_protocol::extensions::ExtensionNegotiationError;
    #[cfg(all(feature = "apps", feature = "tasks"))]
    use fastmcp_protocol::extensions::{ExtensionInactiveReason, McpAppsClientSettings};
    #[cfg(feature = "tasks")]
    use fastmcp_protocol::extensions::{
        official_tasks_empty_settings, register_official_tasks_extension,
    };
    use fastmcp_protocol::{
        CallToolResult, CompletionValues, Content, FinalCompletionParams, LegacyCompletionParams,
        LegacyContent,
    };
    use fastmcp_protocol::{
        CoreResultDiscriminatorPolicy, DecodedResult, ResultPeerEra, decode_peer_result,
    };
    use std::future::Future;
    #[cfg(feature = "builtin-auth-server")]
    use std::pin::Pin;
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
    use std::sync::mpsc::{Receiver, TryRecvError, sync_channel};
    use std::sync::{Condvar, OnceLock};
    use std::thread;
    use std::time::Duration;

    #[derive(Debug, Default)]
    struct HttpOverlapMetrics {
        current: AtomicUsize,
        max: AtomicUsize,
    }

    static HTTP_OVERLAP_METRICS: OnceLock<HttpOverlapMetrics> = OnceLock::new();
    static HTTP_OVERLAP_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
    static HTTP_OVERLAP_CONTROL: OnceLock<HttpOverlapControl> = OnceLock::new();
    static LIVE_HTTP_LISTENER_WAITS: AtomicUsize = AtomicUsize::new(0);
    static LIVE_HTTP_CONNECTION_READ_WAITS: AtomicUsize = AtomicUsize::new(0);
    // Live loopback probes include listener admission, socket I/O, request
    // dispatch, cancellation, and structured shutdown. Two seconds was below
    // the observed floor on loaded RCH workers and converted otherwise useful
    // assertions into harness timeouts. Keep this bounded, but leave enough
    // room for the scenario itself to report the precise failed invariant.
    const LIVE_HTTP_TEST_TIMEOUT_NANOS: u64 = 10_000_000_000;
    // Blocking fixtures and individual setup steps must expire before the
    // outer test watchdog so their exact invariant failure is observable.
    const LIVE_HTTP_STEP_TIMEOUT_NANOS: u64 = LIVE_HTTP_TEST_TIMEOUT_NANOS / 2;

    /// A same-run control for host load. A heartbeat thread asks to sleep
    /// [`Self::TICK`] at a time, and whatever it oversleeps is time a runnable
    /// thread of this process waited for a CPU. A bound measured in runnable
    /// time (wall time less that lag) stretches under host load but still
    /// expires on a hang, where the process could run and made no progress.
    /// Ten times the bound in wall time expires it regardless, so no amount of
    /// lag removes a bound. Reports state the lag, which tells the two apart.
    #[derive(Clone)]
    pub(crate) struct RunnableClock {
        lag_micros: Arc<std::sync::atomic::AtomicU64>,
    }

    impl RunnableClock {
        const TICK: Duration = Duration::from_millis(5);

        /// Starts the heartbeat; it stops once every clone is dropped.
        pub(crate) fn start() -> Self {
            let lag_micros = Arc::new(std::sync::atomic::AtomicU64::new(0));
            let heartbeat = Arc::downgrade(&lag_micros);
            thread::spawn(move || {
                loop {
                    let asked = Instant::now();
                    thread::sleep(Self::TICK);
                    let late = asked.elapsed().saturating_sub(Self::TICK);
                    let Some(lag) = heartbeat.upgrade() else {
                        break;
                    };
                    lag.fetch_add(
                        u64::try_from(late.as_micros()).unwrap_or(u64::MAX),
                        Ordering::AcqRel,
                    );
                }
            });
            Self { lag_micros }
        }

        fn lag(&self) -> Duration {
            Duration::from_micros(self.lag_micros.load(Ordering::Acquire))
        }

        /// A point to measure from: the wall instant and the lag so far.
        pub(crate) fn mark(&self) -> (Instant, Duration) {
            (Instant::now(), self.lag())
        }

        /// Wall time from `mark` to `now`, less the lag accrued between them.
        fn runnable_between(mark: (Instant, Duration), now: (Instant, Duration)) -> Duration {
            now.0
                .saturating_duration_since(mark.0)
                .saturating_sub(now.1.saturating_sub(mark.1))
        }

        /// Whether `bound` of runnable time, or ten times it of wall time,
        /// passed from `mark` to `now`.
        fn expired_between(
            mark: (Instant, Duration),
            now: (Instant, Duration),
            bound: Duration,
        ) -> bool {
            Self::runnable_between(mark, now) >= bound
                || now.0.saturating_duration_since(mark.0) >= bound.saturating_mul(10)
        }

        pub(crate) fn expired(&self, mark: (Instant, Duration), bound: Duration) -> bool {
            Self::expired_between(mark, self.mark(), bound)
        }

        #[cfg(all(unix, feature = "proxy", feature = "legacy-2024-11-05"))]
        pub(crate) fn remaining(&self, mark: (Instant, Duration), bound: Duration) -> Duration {
            bound.saturating_sub(Self::runnable_between(mark, self.mark()))
        }

        pub(crate) fn describe(&self, mark: (Instant, Duration)) -> String {
            let now = self.mark();
            format!(
                "{:?} runnable ({:?} wall, {:?} host lag)",
                Self::runnable_between(mark, now),
                now.0.saturating_duration_since(mark.0),
                now.1.saturating_sub(mark.1)
            )
        }
    }

    /// Awaits `future` for at most `bound` of runnable time from `started`.
    /// Only the short wall-clock slice around it is re-armed, never the
    /// future itself, so a slice expiring cancels nothing. `None` means the
    /// bound expired and the future is still pending.
    // Exact-2024 era: used only by legacy HTTP SSE tests.
    #[cfg(feature = "legacy-2024-11-05")]
    async fn within_runnable<F: Future>(
        cx: &Cx,
        host: &RunnableClock,
        started: (Instant, Duration),
        bound: Duration,
        future: F,
    ) -> Option<F::Output> {
        let mut future = std::pin::pin!(future);
        loop {
            match asupersync::time::timeout(cx.now(), Duration::from_millis(50), future.as_mut())
                .await
            {
                Ok(output) => return Some(output),
                Err(_) if host.expired(started, bound) => return None,
                Err(_) => {}
            }
        }
    }

    /// One second of wall time between two marks; only the lag accrued in
    /// it differs between the arms.
    #[test]
    fn runnable_clock_discounts_host_lag_and_keeps_a_wall_backstop() {
        let start = Instant::now();
        let mark = (start, Duration::from_millis(40));
        let later = |lag_ms: u64| {
            (
                start + Duration::from_secs(1),
                Duration::from_millis(40 + lag_ms),
            )
        };
        let bound = Duration::from_millis(500);
        // Unloaded: the whole second was runnable, so the bound expired.
        assert_eq!(
            RunnableClock::runnable_between(mark, later(0)),
            Duration::from_secs(1)
        );
        assert!(RunnableClock::expired_between(mark, later(0), bound));
        // Loaded: 900 ms of it was host lag, so the same bound has not.
        assert_eq!(
            RunnableClock::runnable_between(mark, later(900)),
            Duration::from_millis(100)
        );
        assert!(!RunnableClock::expired_between(mark, later(900), bound));
        // Nearly all lag: 10 ms runnable is under a 90 ms bound, but the
        // second of wall time is past ten times it, so the backstop expires.
        assert_eq!(
            RunnableClock::runnable_between(mark, later(990)),
            Duration::from_millis(10)
        );
        assert!(RunnableClock::expired_between(
            mark,
            later(990),
            Duration::from_millis(90)
        ));
        assert!(!RunnableClock::expired_between(
            mark,
            later(990),
            Duration::from_millis(101)
        ));
    }

    #[cfg(feature = "builtin-auth-server")]
    const OIDC_TEST_PUBLIC_MODULUS: &str = "jlHZ9nzuIuM4aiAQSAgEJMBaYS7qm7Z_3mtGYDdzReIkzxPHHr21oeXQyUJI89eQG13fsUdyoodcuh5kmndPCrODJekfr_zgor6sNspcB88iQEqEc9yf9YAf5v-cNH1Evh82KABuWb26LMaNAzZFR3BMhMEQ1FD6fLFGAbX76Drd5_UZ-1xcU07IXEc_9zvQvOwXckhO7P5Yil1fVzLTrHye_6zTbGWvdqi45095bKPnSqjrLBCTVrUW8o02Gi6mt7Ls9pZeWx2DXV8SqV06DdlqiovtKWRooQ1zV-v7BGsLsVk6T6d-8mNMGNrh0fpNb_5kdaHphAt_Ji6eE1wQPw";
    #[cfg(feature = "builtin-auth-server")]
    const OIDC_TEST_CANARY_COMPACT_JWS: &str = concat!(
        "eyJhbGciOiJSUzI1NiIsImtpZCI6ImZpeGVkLXJzMjU2In0.",
        "eyJzdWIiOiJmaXhlZC12ZWN0b3IiLCJhdWQiOiJzZXJ2ZXItcG9saWN5LWxhdGVyIn0.",
        "Oak9UDEtrL-pNcPIFw31uzuCoCTyXywF5i3jxDixd0gHonZYPFfSlyPwhNSTrqmlzPsL-wNFcDn1zFlug6Ae1vK_QaL-bZBSxq-lOrMDUI_5_3P_HUrngtZaNk8ru88-wdGByGm1jRZa-LfeoSkESHVKPIcQ_WT7wqhq1RX3ZrPiq9QkHFE8nWIgiIesu8DFOXsdN05rmOxHheCbDGRpf8cQAG0ZENpJvYugD-SX9Sg9Kds5HOlOt6csIQBexCeKM2rIrN0r7qCp6jx_0aevqU6rNr6oxCxCGoH3UZGJa5xRh2KeJ6NVBE9BpPW3Kdi3dEfKlKldjzlUW-zEREdeEw"
    );

    #[cfg(feature = "builtin-auth-server")]
    struct OidcPublicCanaryBackend;

    #[cfg(feature = "builtin-auth-server")]
    impl fastmcp_protocol::jose::ExternalRs256SignerBackend for OidcPublicCanaryBackend {
        fn sign<'a>(
            &'a self,
            _: &'a Cx,
            request: fastmcp_protocol::jose::ExternalRs256SigningRequest,
        ) -> Pin<
            Box<
                dyn Future<Output = fastmcp_protocol::jose::ExternalRs256SignDisposition>
                    + Send
                    + 'a,
            >,
        > {
            Box::pin(async move {
                use base64::Engine as _;
                use fastmcp_protocol::jose::{
                    ExternalRs256OperationReceipt, ExternalRs256SignDisposition, RawRs256Signature,
                    RedactedSignerProvenance,
                };

                let (input, signature) = OIDC_TEST_CANARY_COMPACT_JWS
                    .rsplit_once('.')
                    .expect("retained public test canary has a signature");
                assert!(
                    request
                        .input()
                        .with_bytes(|bytes| bytes == input.as_bytes())
                );
                let signature = base64::engine::general_purpose::URL_SAFE_NO_PAD
                    .decode(signature)
                    .expect("retained public canary signature decodes");
                let receipt = ExternalRs256OperationReceipt::new(
                    request.binding(),
                    1,
                    RedactedSignerProvenance::new("oidc-live-public-canary")
                        .expect("bounded redacted provenance"),
                )
                .expect("valid dispatched operation receipt");
                ExternalRs256SignDisposition::Dispatched(
                    RawRs256Signature::from_bytes(signature)
                        .expect("retained RS256 signature has exact length"),
                    receipt,
                )
            })
        }
    }

    #[cfg(feature = "builtin-auth-server")]
    fn oidc_public_canary_signer() -> Arc<fastmcp_protocol::jose::ExternalRs256Signer> {
        use base64::Engine as _;
        use fastmcp_protocol::jose::{
            AttestedRs256PublicKey, ExternalRs256Signer, RedactedSignerProvenance,
            Rs256SigningBinding,
        };

        let modulus = base64::engine::general_purpose::URL_SAFE_NO_PAD
            .decode(OIDC_TEST_PUBLIC_MODULUS)
            .expect("retained public verification modulus");
        let binding = Rs256SigningBinding::new(71, 72, 73, 74)
            .expect("well-formed external signer generations");
        let key = AttestedRs256PublicKey::admit(
            "fixed-rs256",
            modulus,
            binding,
            RedactedSignerProvenance::new("oidc-live-public-test")
                .expect("bounded redacted provenance"),
        )
        .expect("retained public key admits");
        Arc::new(ExternalRs256Signer::new(
            Arc::new(OidcPublicCanaryBackend),
            key,
        ))
    }

    /// Test-only embedding verifier: it performs a fresh loopback HTTP fetch
    /// of the shipped JWKS route and returns evidence bound to the configured
    /// public HTTPS URI/origin. It never reads the provider's route buffer.
    #[cfg(feature = "builtin-auth-server")]
    struct LiveLoopbackOidcReadBackVerifier {
        address: Mutex<Option<SocketAddr>>,
        generation: u64,
    }

    #[cfg(feature = "builtin-auth-server")]
    impl LiveLoopbackOidcReadBackVerifier {
        fn set_address(&self, address: SocketAddr) {
            *self.address.lock().expect("loopback verifier address lock") = Some(address);
        }
    }

    #[cfg(feature = "builtin-auth-server")]
    impl oidc::OidcJwksReadBackVerifier for LiveLoopbackOidcReadBackVerifier {
        fn read_back<'a>(
            &'a self,
            _: &'a Cx,
            endpoints: &'a [String],
        ) -> Pin<
            Box<
                dyn Future<
                        Output = Result<
                            Vec<fastmcp_protocol::jose::JwksEndpointReadBack>,
                            oidc::OidcError,
                        >,
                    > + Send
                    + 'a,
            >,
        > {
            let address = *self.address.lock().expect("loopback verifier address lock");
            let generation = self.generation;
            Box::pin(async move {
                let address = address.ok_or_else(|| {
                    oidc::OidcError::SigningError(
                        "loopback read-back endpoint is not bound".to_string(),
                    )
                })?;
                let mut evidence = Vec::with_capacity(endpoints.len());
                for endpoint in endpoints {
                    if endpoint != "https://fastmcp.invalid/oidc/jwks" {
                        return Err(oidc::OidcError::SigningError(
                            "loopback verifier was asked for an unconfigured public JWKS URI"
                                .to_string(),
                        ));
                    }
                    let response = live_http_exchange(
                        address,
                        b"GET /oidc/jwks HTTP/1.1\r\nHost: loopback\r\nConnection: close\r\n\r\n"
                            .to_vec(),
                    )
                    .await
                    .map_err(oidc::OidcError::SigningError)?;
                    if !response.starts_with(b"HTTP/1.1 200") {
                        return Err(oidc::OidcError::SigningError(
                            "loopback JWKS read-back did not return HTTP 200".to_string(),
                        ));
                    }
                    let body = live_http_response_body(&response)
                        .map_err(oidc::OidcError::SigningError)?
                        .to_vec();
                    evidence.push(
                        fastmcp_protocol::jose::JwksEndpointReadBack::new(
                            endpoint.clone(),
                            "https://fastmcp.invalid",
                            body,
                            generation,
                        )
                        .map_err(|_| {
                            oidc::OidcError::SigningError(
                                "loopback JWKS evidence is outside admission bounds".to_string(),
                            )
                        })?,
                    );
                }
                Ok(evidence)
            })
        }
    }

    #[cfg(feature = "builtin-auth-server")]
    #[derive(Default)]
    struct LiveOidcActivationStore {
        record: Mutex<Option<oidc::OidcSigningActivationStoreRecord>>,
    }

    #[cfg(feature = "builtin-auth-server")]
    impl oidc::OidcSigningActivationStore for LiveOidcActivationStore {
        fn load(
            &self,
            _: &Cx,
            issuer: &str,
        ) -> Result<Option<oidc::OidcSigningActivationStoreRecord>, oidc::OidcError> {
            Ok(self
                .record
                .lock()
                .map_err(|_| {
                    oidc::OidcError::SigningError("live OIDC store unavailable".to_string())
                })?
                .clone()
                .filter(|record| record.issuer() == issuer))
        }

        fn compare_and_set(
            &self,
            _: &Cx,
            expected_generation: Option<u64>,
            next: oidc::OidcSigningActivationStoreRecord,
        ) -> Result<oidc::OidcSigningActivationStoreRecord, oidc::OidcError> {
            let mut record = self.record.lock().map_err(|_| {
                oidc::OidcError::SigningError("live OIDC store unavailable".to_string())
            })?;
            if record
                .as_ref()
                .map(oidc::OidcSigningActivationStoreRecord::activation_generation)
                != expected_generation
            {
                return Err(oidc::OidcError::SigningError(
                    "live OIDC activation CAS lost".to_string(),
                ));
            }
            *record = Some(next.clone());
            Ok(next)
        }
    }

    #[test]
    fn websocket_profile_exposes_turnkey_server_endpoint_behind_its_feature() {
        let source = include_str!("lib.rs").replace("\r\n", "\n");
        assert!(source.contains("#[cfg(feature = \"websocket\")]\nimpl Server"));
        assert!(source.contains("pub async fn bind_websocket"));
        assert!(source.contains("pub async fn serve_websocket"));
        assert!(source.contains("pub async fn run_http"));
    }

    #[cfg(feature = "websocket")]
    async fn websocket_upgrade(
        cx: &Cx,
        address: std::net::SocketAddr,
        request: &[u8],
    ) -> Result<(AsyncTcpStream, Vec<u8>), String> {
        use asupersync::io::{AsyncReadExt, AsyncWriteExt};

        let deadline = cx.now().saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
        let mut stream = asupersync::time::timeout_at(deadline, AsyncTcpStream::connect(address))
            .await
            .map_err(|_| "WebSocket client connect timed out".to_owned())?
            .map_err(|error| format!("WebSocket client connect failed: {error}"))?;
        asupersync::time::timeout_at(deadline, stream.write_all(request))
            .await
            .map_err(|_| "WebSocket handshake write timed out".to_owned())?
            .map_err(|error| format!("WebSocket handshake write failed: {error}"))?;
        asupersync::time::timeout_at(deadline, stream.flush())
            .await
            .map_err(|_| "WebSocket handshake flush timed out".to_owned())?
            .map_err(|error| format!("WebSocket handshake flush failed: {error}"))?;

        let mut received = Vec::new();
        while !received.windows(4).any(|window| window == b"\r\n\r\n") {
            let mut chunk = [0_u8; 512];
            let read = asupersync::time::timeout_at(deadline, stream.read(&mut chunk))
                .await
                .map_err(|_| "WebSocket handshake response timed out".to_owned())?
                .map_err(|error| format!("WebSocket handshake response failed: {error}"))?;
            if read == 0 {
                break;
            }
            received.extend_from_slice(&chunk[..read]);
        }
        Ok((stream, received))
    }

    #[cfg(feature = "websocket")]
    #[test]
    fn live_websocket_successful_child_reports_quiescent_before_shutdown_cleanup() {
        run_live_http_test(|cx| async move {
            use asupersync::io::{AsyncReadExt, AsyncWriteExt};

            let peer_closed = Arc::new(AtomicBool::new(false));
            let cleanup_after_peer_close = Arc::new(AtomicBool::new(false));
            let shutdown_calls = Arc::new(AtomicUsize::new(0));
            let observed_peer_close = Arc::clone(&peer_closed);
            let observed_cleanup = Arc::clone(&cleanup_after_peer_close);
            let observed_shutdown_calls = Arc::clone(&shutdown_calls);
            let listener = Server::new("live-websocket-successful-child", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("modern-only policy is available")
                .on_shutdown(move || {
                    observed_shutdown_calls.fetch_add(1, Ordering::AcqRel);
                    observed_cleanup.store(
                        observed_peer_close.load(Ordering::Acquire),
                        Ordering::Release,
                    );
                })
                .build()
                .bind_websocket(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("successful-child WebSocket bind failed: {error}"))?;
            let address = listener
                .local_addr()
                .map_err(|error| format!("successful-child WebSocket address failed: {error}"))?;
            let scope = cx.scope();
            let mut listener_task = cx
                .spawn_in(&scope, move |listener_cx| async move {
                    listener.serve(&listener_cx).await
                })
                .map_err(|error| {
                    format!("successful-child WebSocket listener admission failed: {error}")
                })?;
            let opening = concat!(
                "GET /mcp HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\n",
                "Connection: Upgrade\r\nSec-WebSocket-Version: 13\r\n",
                "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n"
            );
            let (mut client, accepted) =
                websocket_upgrade(&cx, address, opening.as_bytes()).await?;
            if !accepted.starts_with(b"HTTP/1.1 101") {
                return Err("successful WebSocket child was not upgraded".to_owned());
            }
            client
                .write_all(&masked_websocket_frame(0x08, &[]))
                .await
                .map_err(|error| format!("successful WebSocket close write failed: {error}"))?;
            client
                .flush()
                .await
                .map_err(|error| format!("successful WebSocket close flush failed: {error}"))?;
            let deadline = cx.now().saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
            let mut close_reply = [0_u8; 32];
            let close_read = asupersync::time::timeout_at(deadline, client.read(&mut close_reply))
                .await
                .map_err(|_| "successful WebSocket close reply timed out".to_owned())?
                .map_err(|error| format!("successful WebSocket close reply failed: {error}"))?;
            if close_read < 2 || close_reply[0] & 0x0f != 0x08 {
                return Err("successful WebSocket child did not complete a close reply".to_owned());
            }
            peer_closed.store(true, Ordering::Release);
            drop(client);
            listener_task.abort();
            let join_cx = Cx::for_testing();
            let shutdown = listener_task
                .join(&join_cx)
                .await
                .map_err(|error| format!("successful WebSocket listener join failed: {error:?}"))?
                .map_err(|error| format!("successful WebSocket listener failed: {error}"))?;
            if !matches!(shutdown, WebSocketServerShutdown::Quiescent)
                || shutdown_calls.load(Ordering::Acquire) != 1
                || !cleanup_after_peer_close.load(Ordering::Acquire)
            {
                return Err(
                    "successful WebSocket child did not settle before quiescent cleanup".to_owned(),
                );
            }
            Ok(())
        });
    }

    #[cfg(feature = "websocket")]
    #[test]
    fn rh5_websocket_rejects_server_notification_without_dispatch_or_connection_loss() {
        run_live_http_test(|cx| async move {
            use asupersync::io::{AsyncReadExt, AsyncWriteExt};

            let handler_calls = Arc::new(AtomicUsize::new(0));
            let middleware_calls = Arc::new(AtomicUsize::new(0));
            let saw_credential = Arc::new(AtomicBool::new(false));
            let listener = Server::new("websocket-wrong-direction-notification", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("modern-only policy is available")
                .middleware(ModernHttpAuthMiddleware {
                    calls: Arc::clone(&middleware_calls),
                    saw_credential: Arc::clone(&saw_credential),
                })
                .tool(ModernHttpAuthCounterTool {
                    calls: Arc::clone(&handler_calls),
                })
                .build()
                .bind_websocket(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("wrong-direction WebSocket bind failed: {error}"))?;
            let address = listener
                .local_addr()
                .map_err(|error| format!("wrong-direction WebSocket address failed: {error}"))?;
            let scope = cx.scope();
            let mut listener_task = cx
                .spawn_in(&scope, move |listener_cx| async move {
                    listener.serve(&listener_cx).await
                })
                .map_err(|error| {
                    format!("wrong-direction WebSocket listener admission failed: {error}")
                })?;
            let opening = concat!(
                "GET /mcp HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\n",
                "Connection: Upgrade\r\nSec-WebSocket-Version: 13\r\n",
                "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n"
            );
            let (mut client, accepted) =
                websocket_upgrade(&cx, address, opening.as_bytes()).await?;
            if !accepted.starts_with(b"HTTP/1.1 101") {
                return Err("wrong-direction WebSocket was not upgraded".to_owned());
            }
            let server_notification = JsonRpcMessage::Request(JsonRpcRequest::notification(
                "notifications/progress",
                Some(serde_json::json!({
                    "progressToken": "server-only",
                    "progress": 1,
                    "_meta": {
                        MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    },
                })),
            ));
            let resumed_client_request = JsonRpcMessage::Request(JsonRpcRequest::new(
                "tools/call",
                Some(serde_json::json!({
                    "name": "modern_http_auth_counter",
                    "arguments": {},
                    "_meta": {
                        MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                        FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                    },
                })),
                7_402_i64,
            ));
            let mut frames = masked_websocket_message(modern_discovery_request(7_401));
            frames.extend(masked_websocket_message(server_notification));
            frames.extend(masked_websocket_message(resumed_client_request));
            client
                .write_all(&frames)
                .await
                .map_err(|error| format!("wrong-direction WebSocket write failed: {error}"))?;
            client
                .flush()
                .await
                .map_err(|error| format!("wrong-direction WebSocket flush failed: {error}"))?;

            let deadline = cx.now().saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
            let mut responses = Vec::new();
            while !(responses
                .windows(b"serverInfo".len())
                .any(|window| window == b"serverInfo")
                && responses
                    .windows(b"authenticated modern HTTP dispatch".len())
                    .any(|window| window == b"authenticated modern HTTP dispatch"))
            {
                let mut chunk = [0_u8; 1024];
                let read = asupersync::time::timeout_at(deadline, client.read(&mut chunk))
                    .await
                    .map_err(|_| "wrong-direction WebSocket response timed out".to_owned())?
                    .map_err(|error| {
                        format!("wrong-direction WebSocket response failed: {error}")
                    })?;
                if read == 0 {
                    return Err(
                        "wrong-direction notification closed the WebSocket connection".to_owned(),
                    );
                }
                responses.extend_from_slice(&chunk[..read]);
            }
            if handler_calls.load(Ordering::Acquire) != 1
                || middleware_calls.load(Ordering::Acquire) != 2
                || saw_credential.load(Ordering::Acquire)
            {
                return Err(
                    "wrong-direction notification reached middleware or handler before the resumed request"
                        .to_owned(),
                );
            }

            client
                .write_all(&masked_websocket_frame(0x08, &[]))
                .await
                .map_err(|error| {
                    format!("wrong-direction WebSocket close write failed: {error}")
                })?;
            client.flush().await.map_err(|error| {
                format!("wrong-direction WebSocket close flush failed: {error}")
            })?;
            drop(client);
            listener_task.abort();
            let join_cx = Cx::for_testing();
            let shutdown = listener_task
                .join(&join_cx)
                .await
                .map_err(|error| {
                    format!("wrong-direction WebSocket listener join failed: {error:?}")
                })?
                .map_err(|error| format!("wrong-direction WebSocket listener failed: {error}"))?;
            if !matches!(shutdown, WebSocketServerShutdown::Quiescent) {
                return Err("wrong-direction WebSocket listener did not quiesce".to_owned());
            }
            Ok(())
        });
    }

    #[cfg(feature = "websocket")]
    #[test]
    fn live_websocket_failing_child_is_reported_after_cleanup_observes_terminal_peer() {
        run_live_http_test(|cx| async move {
            use asupersync::io::{AsyncReadExt, AsyncWriteExt};

            let peer_terminal = Arc::new(AtomicBool::new(false));
            let cleanup_after_peer_terminal = Arc::new(AtomicBool::new(false));
            let shutdown_calls = Arc::new(AtomicUsize::new(0));
            let observed_peer_terminal = Arc::clone(&peer_terminal);
            let observed_cleanup = Arc::clone(&cleanup_after_peer_terminal);
            let observed_shutdown_calls = Arc::clone(&shutdown_calls);
            let listener = Server::new("live-websocket-failing-child", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("modern-only policy is available")
                .on_shutdown(move || {
                    observed_shutdown_calls.fetch_add(1, Ordering::AcqRel);
                    observed_cleanup.store(
                        observed_peer_terminal.load(Ordering::Acquire),
                        Ordering::Release,
                    );
                })
                .build()
                .bind_websocket(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("failing-child WebSocket bind failed: {error}"))?;
            let address = listener
                .local_addr()
                .map_err(|error| format!("failing-child WebSocket address failed: {error}"))?;
            let scope = cx.scope();
            let mut listener_task = cx
                .spawn_in(&scope, move |listener_cx| async move {
                    listener.serve(&listener_cx).await
                })
                .map_err(|error| {
                    format!("failing-child WebSocket listener admission failed: {error}")
                })?;
            let opening = concat!(
                "GET /mcp HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\n",
                "Connection: Upgrade\r\nSec-WebSocket-Version: 13\r\n",
                "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n"
            );
            let (mut client, accepted) =
                websocket_upgrade(&cx, address, opening.as_bytes()).await?;
            if !accepted.starts_with(b"HTTP/1.1 101") {
                return Err("failing WebSocket child was not upgraded".to_owned());
            }
            // Reserved opcode 0x03 is a decoded-frame failure, not a clean
            // peer close. The real connection child must return that failure
            // to the listener-owned TaskHandle.
            client
                .write_all(&masked_websocket_frame(0x03, &[]))
                .await
                .map_err(|error| format!("failing WebSocket frame write failed: {error}"))?;
            client
                .flush()
                .await
                .map_err(|error| format!("failing WebSocket frame flush failed: {error}"))?;
            let deadline = cx.now().saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
            let mut terminal = [0_u8; 32];
            let terminal_read = asupersync::time::timeout_at(deadline, client.read(&mut terminal))
                .await
                .map_err(|_| "failing WebSocket terminal response timed out".to_owned())?
                .map_err(|error| format!("failing WebSocket terminal response failed: {error}"))?;
            if terminal_read != 0 && (terminal_read < 2 || terminal[0] & 0x0f != 0x08) {
                return Err(
                    "failing WebSocket child did not terminate the invalid frame".to_owned(),
                );
            }
            peer_terminal.store(true, Ordering::Release);
            drop(client);

            // A second accepted socket makes the listener reap the first
            // terminal child on its real accept-loop path before shutdown.
            let reaper_trigger = opening.replace("Connection: Upgrade", "Connection: keep-alive");
            let (_trigger, rejected) =
                websocket_upgrade(&cx, address, reaper_trigger.as_bytes()).await?;
            if !rejected.starts_with(b"HTTP/1.1 400") {
                return Err("failing-child reaper trigger did not reach the listener".to_owned());
            }
            listener_task.abort();
            let join_cx = Cx::for_testing();
            let listener_result = listener_task
                .join(&join_cx)
                .await
                .map_err(|error| format!("failing WebSocket listener join failed: {error:?}"))?;
            let error = match listener_result {
                Err(error) => error,
                Ok(_) => {
                    return Err(
                        "failing WebSocket child unexpectedly produced a quiescent success result"
                            .to_owned(),
                    );
                }
            };
            if !error
                .message
                .contains("WebSocket connection child settlement failure")
                || shutdown_calls.load(Ordering::Acquire) != 1
                || !cleanup_after_peer_terminal.load(Ordering::Acquire)
            {
                return Err(
                    "failing WebSocket child was hidden or cleanup preceded terminal settlement"
                        .to_owned(),
                );
            }
            Ok(())
        });
    }

    #[cfg(feature = "websocket")]
    #[test]
    fn live_websocket_upgrade_owns_connection_teardown_and_preserves_peer_isolation() {
        run_live_http_test(|cx| async move {
            use asupersync::io::{AsyncReadExt, AsyncWriteExt};

            let listener = Server::new("live-websocket", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("modern-only policy is available")
                .http_config(HttpServerConfig::new().mcp_path("/qualified/mcp"))
                .build()
                .bind_websocket(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("WebSocket bind failed: {error}"))?;
            let address = listener
                .local_addr()
                .map_err(|error| format!("WebSocket local address failed: {error}"))?;
            let scope = cx.scope();
            let mut listener_task = cx
                .spawn_in(&scope, move |listener_cx| async move {
                    listener.serve(&listener_cx).await
                })
                .map_err(|error| format!("WebSocket listener task admission failed: {error}"))?;

            let valid = concat!(
                "GET /qualified/mcp?ignored=query HTTP/1.1\r\n",
                "Host: localhost\r\n",
                "Upgrade: websocket\r\n",
                "Connection: Upgrade\r\n",
                "Sec-WebSocket-Version: 13\r\n",
                "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n"
            );
            // The opening frame intentionally shares the Upgrade write. This
            // proves that HTTP header parsing hands pre-read WebSocket bytes
            // to the server-role frame decoder instead of losing them.
            let mut opening = valid.as_bytes().to_vec();
            opening.extend_from_slice(&masked_websocket_message(modern_discovery_request(7_101)));
            let (mut client, accepted) = websocket_upgrade(&cx, address, &opening).await?;
            if !accepted.starts_with(b"HTTP/1.1 101") {
                return Err(format!(
                    "valid WebSocket upgrade was not accepted: {accepted:?}"
                ));
            }
            let deadline = cx.now().saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
            let header_end = accepted
                .windows(4)
                .position(|window| window == b"\r\n\r\n")
                .map_or(accepted.len(), |position| position + 4);
            let mut response = accepted[header_end..].to_vec();
            while !response.windows(10).any(|window| window == b"serverInfo") {
                let mut chunk = [0_u8; 1024];
                let read = asupersync::time::timeout_at(deadline, client.read(&mut chunk))
                    .await
                    .map_err(|_| "modern WebSocket response timed out".to_owned())?
                    .map_err(|error| format!("modern WebSocket response failed: {error}"))?;
                if read == 0 {
                    return Err("modern WebSocket closed before its response".to_owned());
                }
                response.extend_from_slice(&chunk[..read]);
            }
            client
                .write_all(&masked_websocket_frame(0x08, &[]))
                .await
                .map_err(|error| format!("WebSocket close write failed: {error}"))?;
            client
                .flush()
                .await
                .map_err(|error| format!("WebSocket close flush failed: {error}"))?;
            let mut close_reply = [0_u8; 32];
            let close_read = asupersync::time::timeout_at(deadline, client.read(&mut close_reply))
                .await
                .map_err(|_| "WebSocket close reply timed out".to_owned())?
                .map_err(|error| format!("WebSocket close reply failed: {error}"))?;
            if close_read < 2 || close_reply[0] & 0x0f != 0x08 || close_reply[1] & 0x80 != 0 {
                return Err("server did not return an unmasked WebSocket close reply".to_owned());
            }

            let malformed_header = valid.replace("Connection: Upgrade", "Connection: keep-alive");
            let (_bad_client, rejected) =
                websocket_upgrade(&cx, address, malformed_header.as_bytes()).await?;
            if !rejected.starts_with(b"HTTP/1.1 400") {
                return Err(format!("bad Upgrade header was not rejected: {rejected:?}"));
            }

            let (mut era_client, era_accepted) =
                websocket_upgrade(&cx, address, valid.as_bytes()).await?;
            if !era_accepted.starts_with(b"HTTP/1.1 101") {
                return Err("era-negative WebSocket handshake was not accepted".to_owned());
            }
            era_client
                .write_all(&masked_websocket_message(exact_legacy_initialize_request(
                    7_102,
                    serde_json::json!("1.0.0"),
                )))
                .await
                .map_err(|error| format!("legacy-era WebSocket frame write failed: {error}"))?;
            era_client
                .flush()
                .await
                .map_err(|error| format!("legacy-era WebSocket frame flush failed: {error}"))?;
            let mut rejection = [0_u8; 1024];
            let read = asupersync::time::timeout_at(deadline, era_client.read(&mut rejection))
                .await
                .map_err(|_| "legacy-era WebSocket rejection timed out".to_owned())?
                .map_err(|error| format!("legacy-era WebSocket rejection failed: {error}"))?;
            if read == 0
                || !rejection[..read]
                    .windows(5)
                    .any(|window| window == b"error")
            {
                return Err("wrong-era frame did not receive a JSON-RPC refusal".to_owned());
            }

            // RH-5 negative neighbor: a rejected legacy opening must not
            // poison independent modern state or terminate its listener.
            let (mut independent_client, independent_accepted) =
                websocket_upgrade(&cx, address, valid.as_bytes()).await?;
            if !independent_accepted.starts_with(b"HTTP/1.1 101") {
                return Err("wrong-era peer changed listener admission state".to_owned());
            }
            independent_client
                .write_all(&masked_websocket_message(modern_discovery_request(7_103)))
                .await
                .map_err(|error| format!("isolated modern frame write failed: {error}"))?;
            independent_client
                .flush()
                .await
                .map_err(|error| format!("isolated modern frame flush failed: {error}"))?;
            let mut independent_response = Vec::new();
            while !independent_response
                .windows(10)
                .any(|window| window == b"serverInfo")
            {
                let mut chunk = [0_u8; 1024];
                let read =
                    asupersync::time::timeout_at(deadline, independent_client.read(&mut chunk))
                        .await
                        .map_err(|_| "isolated modern WebSocket response timed out".to_owned())?
                        .map_err(|error| {
                            format!("isolated modern WebSocket response failed: {error}")
                        })?;
                if read == 0 {
                    return Err("wrong-era peer closed an independent modern connection".to_owned());
                }
                independent_response.extend_from_slice(&chunk[..read]);
            }
            independent_client
                .write_all(&masked_websocket_frame(0x08, &[]))
                .await
                .map_err(|error| format!("isolated WebSocket close write failed: {error}"))?;
            drop(era_client);

            // TaskHandle::abort requests cooperative cancellation; the
            // serving future still owns child settlement and returns its
            // first-class shutdown result.
            listener_task.abort();
            let join_cx = Cx::for_testing();
            let shutdown = listener_task
                .join(&join_cx)
                .await
                .map_err(|error| format!("WebSocket listener join failed: {error:?}"))?
                .map_err(|error| format!("WebSocket listener failed: {error}"))?;
            if !matches!(shutdown, WebSocketServerShutdown::Quiescent) {
                return Err("cooperative WebSocket shutdown retained a child".to_owned());
            }
            Ok(())
        });
    }

    #[cfg(all(feature = "websocket", feature = "legacy-2024-11-05"))]
    #[test]
    fn live_websocket_auto_accepts_fresh_eras_and_fences_cross_era_traffic() {
        run_live_http_test(|cx| async move {
            use asupersync::io::{AsyncReadExt, AsyncWriteExt};

            fn contains_bytes(haystack: &[u8], needle: &[u8]) -> bool {
                haystack
                    .windows(needle.len())
                    .any(|window| window == needle)
            }

            let handler_calls = Arc::new(AtomicUsize::new(0));
            let listener = Server::new("live-websocket-auto-era-isolation", "1.0.0")
                .protocol_policy(ProtocolPolicy::Auto)
                .expect("Auto policy is available to the public WebSocket listener")
                .tool(ModernHttpAuthCounterTool {
                    calls: Arc::clone(&handler_calls),
                })
                .build()
                .bind_websocket(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("Auto WebSocket bind failed: {error}"))?;
            let address = listener
                .local_addr()
                .map_err(|error| format!("Auto WebSocket address failed: {error}"))?;
            let scope = cx.scope();
            let mut listener_task = cx
                .spawn_in(&scope, move |listener_cx| async move {
                    listener.serve(&listener_cx).await
                })
                .map_err(|error| format!("Auto WebSocket listener admission failed: {error}"))?;
            let opening = concat!(
                "GET /mcp HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\n",
                "Connection: Upgrade\r\nSec-WebSocket-Version: 13\r\n",
                "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n"
            );
            let deadline = cx.now().saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);

            // Positive: a final-era client selects final routing on its own
            // fresh public WebSocket connection.
            let (mut modern, modern_upgrade) =
                websocket_upgrade(&cx, address, opening.as_bytes()).await?;
            if !modern_upgrade.starts_with(b"HTTP/1.1 101") {
                return Err("Auto WebSocket did not accept the final-era client".to_owned());
            }
            modern
                .write_all(&masked_websocket_message(modern_discovery_request(7_201)))
                .await
                .map_err(|error| format!("Auto final-era discovery write failed: {error}"))?;
            modern
                .flush()
                .await
                .map_err(|error| format!("Auto final-era discovery flush failed: {error}"))?;
            let mut modern_response = Vec::new();
            while !contains_bytes(&modern_response, b"serverInfo") {
                let mut chunk = [0_u8; 1024];
                let read = asupersync::time::timeout_at(deadline, modern.read(&mut chunk))
                    .await
                    .map_err(|_| "Auto final-era discovery timed out".to_owned())?
                    .map_err(|error| format!("Auto final-era discovery read failed: {error}"))?;
                if read == 0 {
                    return Err("Auto final-era client closed before discovery response".to_owned());
                }
                modern_response.extend_from_slice(&chunk[..read]);
            }
            modern
                .write_all(&masked_websocket_frame(0x08, &[]))
                .await
                .map_err(|error| format!("Auto final-era close write failed: {error}"))?;
            modern
                .flush()
                .await
                .map_err(|error| format!("Auto final-era close flush failed: {error}"))?;
            drop(modern);

            // Positive: a separate exact-2024 peer may initialize, confirm
            // initialization, and make an ordinary request on the same public
            // listener without sharing the final-era connection namespace.
            let (mut legacy, legacy_upgrade) =
                websocket_upgrade(&cx, address, opening.as_bytes()).await?;
            if !legacy_upgrade.starts_with(b"HTTP/1.1 101") {
                return Err("Auto WebSocket did not accept the exact-2024 client".to_owned());
            }
            let legacy_initialize =
                exact_legacy_initialize_request(7_202, serde_json::json!("1.0.0"));
            let legacy_initialized = JsonRpcMessage::Request(JsonRpcRequest::notification(
                "notifications/initialized",
                None,
            ));
            let legacy_list = JsonRpcMessage::Request(JsonRpcRequest::new(
                "tools/list",
                Some(serde_json::json!({})),
                7_203_i64,
            ));
            let mut legacy_frames = masked_websocket_message(legacy_initialize);
            legacy_frames.extend(masked_websocket_message(legacy_initialized));
            legacy_frames.extend(masked_websocket_message(legacy_list));
            legacy
                .write_all(&legacy_frames)
                .await
                .map_err(|error| format!("Auto exact-2024 transcript write failed: {error}"))?;
            legacy
                .flush()
                .await
                .map_err(|error| format!("Auto exact-2024 transcript flush failed: {error}"))?;
            let mut legacy_response = Vec::new();
            while !(contains_bytes(&legacy_response, b"\"id\":7202")
                && contains_bytes(&legacy_response, b"\"id\":7203")
                && contains_bytes(&legacy_response, b"\"tools\""))
            {
                let mut chunk = [0_u8; 1024];
                let read = asupersync::time::timeout_at(deadline, legacy.read(&mut chunk))
                    .await
                    .map_err(|_| "Auto exact-2024 transcript timed out".to_owned())?
                    .map_err(|error| format!("Auto exact-2024 transcript read failed: {error}"))?;
                if read == 0 {
                    return Err(
                        "Auto exact-2024 client closed before its ordinary response".to_owned()
                    );
                }
                legacy_response.extend_from_slice(&chunk[..read]);
            }
            legacy
                .write_all(&masked_websocket_frame(0x08, &[]))
                .await
                .map_err(|error| format!("Auto exact-2024 close write failed: {error}"))?;
            legacy
                .flush()
                .await
                .map_err(|error| format!("Auto exact-2024 close flush failed: {error}"))?;
            drop(legacy);

            // RH-5 neighbor: the only changed dimension is a legacy opening
            // after this peer already selected final routing. Its refusal is
            // connection-local and cannot poison a later independent final
            // client on the listener.
            let (mut mixed, mixed_upgrade) =
                websocket_upgrade(&cx, address, opening.as_bytes()).await?;
            if !mixed_upgrade.starts_with(b"HTTP/1.1 101") {
                return Err("Auto WebSocket did not admit the cross-era probe peer".to_owned());
            }
            let mut mixed_frames = masked_websocket_message(modern_discovery_request(7_204));
            mixed_frames.extend(masked_websocket_message(exact_legacy_initialize_request(
                7_205,
                serde_json::json!("1.0.0"),
            )));
            mixed
                .write_all(&mixed_frames)
                .await
                .map_err(|error| format!("Auto cross-era frame write failed: {error}"))?;
            mixed
                .flush()
                .await
                .map_err(|error| format!("Auto cross-era frame flush failed: {error}"))?;
            let mut mixed_response = Vec::new();
            while !(contains_bytes(&mixed_response, b"\"id\":7205")
                && contains_bytes(&mixed_response, b"\"error\""))
            {
                let mut chunk = [0_u8; 1024];
                let read = asupersync::time::timeout_at(deadline, mixed.read(&mut chunk))
                    .await
                    .map_err(|_| "Auto cross-era refusal timed out".to_owned())?
                    .map_err(|error| format!("Auto cross-era refusal read failed: {error}"))?;
                if read == 0 {
                    return Err("Auto cross-era peer closed before its refusal".to_owned());
                }
                mixed_response.extend_from_slice(&chunk[..read]);
            }

            if handler_calls.load(Ordering::Acquire) != 0 {
                return Err(
                    "cross-era refusal dispatched a handler before closing the offending peer"
                        .to_owned(),
                );
            }
            loop {
                let mut terminal = [0_u8; 64];
                let read = asupersync::time::timeout_at(deadline, mixed.read(&mut terminal))
                    .await
                    .map_err(|_| "Auto cross-era peer close timed out".to_owned())?
                    .map_err(|error| format!("Auto cross-era peer close failed: {error}"))?;
                if read == 0 {
                    break;
                }
            }
            drop(mixed);

            let (mut isolated, isolated_upgrade) =
                websocket_upgrade(&cx, address, opening.as_bytes()).await?;
            if !isolated_upgrade.starts_with(b"HTTP/1.1 101") {
                return Err("cross-era probe poisoned later listener admission".to_owned());
            }
            isolated
                .write_all(&masked_websocket_message(modern_discovery_request(7_206)))
                .await
                .map_err(|error| format!("isolated final-era discovery write failed: {error}"))?;
            isolated
                .flush()
                .await
                .map_err(|error| format!("isolated final-era discovery flush failed: {error}"))?;
            let mut isolated_response = Vec::new();
            while !contains_bytes(&isolated_response, b"serverInfo") {
                let mut chunk = [0_u8; 1024];
                let read = asupersync::time::timeout_at(deadline, isolated.read(&mut chunk))
                    .await
                    .map_err(|_| "isolated final-era discovery timed out".to_owned())?
                    .map_err(|error| {
                        format!("isolated final-era discovery read failed: {error}")
                    })?;
                if read == 0 {
                    return Err("cross-era probe poisoned later final-era traffic".to_owned());
                }
                isolated_response.extend_from_slice(&chunk[..read]);
            }
            isolated
                .write_all(&masked_websocket_frame(0x08, &[]))
                .await
                .map_err(|error| format!("isolated final-era close write failed: {error}"))?;
            isolated
                .flush()
                .await
                .map_err(|error| format!("isolated final-era close flush failed: {error}"))?;
            drop(isolated);

            listener_task.abort();
            let join_cx = Cx::for_testing();
            let shutdown = listener_task
                .join(&join_cx)
                .await
                .map_err(|error| format!("Auto WebSocket listener join failed: {error:?}"))?
                .map_err(|error| format!("Auto WebSocket listener failed: {error}"))?;
            if !matches!(shutdown, WebSocketServerShutdown::Quiescent) {
                return Err("Auto WebSocket listener retained a child after era proof".to_owned());
            }
            Ok(())
        });
    }

    #[cfg(feature = "websocket")]
    #[test]
    fn live_websocket_connection_limit_rejects_before_child_and_releases_its_permit() {
        run_live_http_test(|cx| async move {
            let listener = Server::new("live-websocket-limit", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("modern-only policy is available")
                .http_config(HttpServerConfig::new().max_connections(1))
                .build()
                .bind_websocket(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("limited WebSocket bind failed: {error}"))?;
            let address = listener
                .local_addr()
                .map_err(|error| format!("limited WebSocket address failed: {error}"))?;
            let scope = cx.scope();
            let mut listener_task = cx
                .spawn_in(&scope, move |listener_cx| async move {
                    listener.serve(&listener_cx).await
                })
                .map_err(|error| format!("limited WebSocket listener admission failed: {error}"))?;
            let opening = concat!(
                "GET /mcp HTTP/1.1\r\n",
                "Host: localhost\r\n",
                "Upgrade: websocket\r\n",
                "Connection: Upgrade\r\n",
                "Sec-WebSocket-Version: 13\r\n",
                "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n"
            );
            let (first, accepted) = websocket_upgrade(&cx, address, opening.as_bytes()).await?;
            if !accepted.starts_with(b"HTTP/1.1 101") {
                return Err("the first limited WebSocket connection was not accepted".to_owned());
            }
            let (_overflow, rejected) = websocket_upgrade(&cx, address, opening.as_bytes()).await?;
            if rejected.starts_with(b"HTTP/1.1 101") {
                return Err(
                    "N+1 WebSocket connection created a child despite the limiter".to_owned(),
                );
            }
            drop(first);
            // The permit belongs to the accepted child's full lifetime.  A
            // later handshake proves it was released when that child ended.
            let deadline = cx.now().saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
            let mut replacement = None;
            while cx.now() < deadline {
                let (stream, response) =
                    websocket_upgrade(&cx, address, opening.as_bytes()).await?;
                if response.starts_with(b"HTTP/1.1 101") {
                    replacement = Some(stream);
                    break;
                }
                asupersync::time::sleep(cx.now(), Duration::from_millis(1)).await;
            }
            drop(replacement.ok_or_else(|| {
                "WebSocket permit did not release with its connection child".to_owned()
            })?);
            listener_task.abort();
            let join_cx = Cx::for_testing();
            let shutdown = listener_task
                .join(&join_cx)
                .await
                .map_err(|error| format!("limited WebSocket listener join failed: {error:?}"))?
                .map_err(|error| format!("limited WebSocket listener failed: {error}"))?;
            if !matches!(shutdown, WebSocketServerShutdown::Quiescent) {
                return Err("limited WebSocket shutdown retained a child".to_owned());
            }
            Ok(())
        });
    }

    #[cfg(feature = "websocket")]
    #[test]
    fn live_websocket_upgrade_authentication_rejects_before_101_and_allows_bearer() {
        run_live_http_test(|cx| async move {
            use asupersync::io::{AsyncReadExt, AsyncWriteExt};

            let provider_calls = Arc::new(AtomicUsize::new(0));
            let handler_calls = Arc::new(AtomicUsize::new(0));
            let middleware_calls = Arc::new(AtomicUsize::new(0));
            let saw_credential = Arc::new(AtomicBool::new(false));
            let listener = Server::new("live-websocket-auth", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("modern-only policy is available")
                .auth_provider(OneShotNativeAuthProvider {
                    calls: Arc::clone(&provider_calls),
                })
                .middleware(ModernHttpAuthMiddleware {
                    calls: Arc::clone(&middleware_calls),
                    saw_credential: Arc::clone(&saw_credential),
                })
                .tool(ModernHttpAuthCounterTool {
                    calls: Arc::clone(&handler_calls),
                })
                .build()
                .bind_websocket(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("WebSocket auth bind failed: {error}"))?;
            let address = listener
                .local_addr()
                .map_err(|error| format!("WebSocket auth address failed: {error}"))?;
            let scope = cx.scope();
            let mut listener_task = cx
                .spawn_in(&scope, move |listener_cx| async move {
                    listener.serve(&listener_cx).await
                })
                .map_err(|error| format!("WebSocket auth listener admission failed: {error}"))?;
            let unsigned = concat!(
                "GET /mcp HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\n",
                "Connection: Upgrade\r\nSec-WebSocket-Version: 13\r\n",
                "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n"
            );
            let (_missing, missing) = websocket_upgrade(&cx, address, unsigned.as_bytes()).await?;
            if !missing.starts_with(b"HTTP/1.1 401")
                || !String::from_utf8_lossy(&missing)
                    .to_ascii_lowercase()
                    .contains("www-authenticate: bearer")
            {
                return Err(
                    "missing WebSocket bearer committed a 101 or omitted challenge".to_owned(),
                );
            }
            let duplicate = unsigned.replace(
                "\r\n\r\n",
                "\r\nAuthorization: Bearer alpha\r\naUtHoRiZaTiOn: Bearer beta\r\n\r\n",
            );
            let (_duplicate, duplicate_response) =
                websocket_upgrade(&cx, address, duplicate.as_bytes()).await?;
            if !duplicate_response.starts_with(b"HTTP/1.1 401")
                || !String::from_utf8_lossy(&duplicate_response)
                    .to_ascii_lowercase()
                    .contains("www-authenticate: bearer")
            {
                return Err(
                    "duplicate WebSocket Authorization did not receive 401 before 101".to_owned(),
                );
            }
            for malformed in [
                unsigned.replace("\r\n\r\n", "\r\nAuthorization Bearer alpha\r\n\r\n"),
                unsigned.replace("\r\n\r\n", "\r\nAuthorization : Bearer alpha\r\n\r\n"),
            ] {
                let (_malformed, response) =
                    websocket_upgrade(&cx, address, malformed.as_bytes()).await?;
                if !response.starts_with(b"HTTP/1.1 401")
                    || !String::from_utf8_lossy(&response)
                        .to_ascii_lowercase()
                        .contains("www-authenticate: bearer")
                {
                    return Err(
                        "malformed Authorization intent did not receive the bounded challenge"
                            .to_owned(),
                    );
                }
            }
            let unrelated_malformed = unsigned.replace("\r\n\r\n", "\r\nX-Test malformed\r\n\r\n");
            let (_unrelated, unrelated_response) =
                websocket_upgrade(&cx, address, unrelated_malformed.as_bytes()).await?;
            if !unrelated_response.starts_with(b"HTTP/1.1 400") {
                return Err("unrelated malformed Upgrade header was not retained as 400".to_owned());
            }
            if provider_calls.load(Ordering::Acquire) != 0
                || handler_calls.load(Ordering::Acquire) != 0
                || middleware_calls.load(Ordering::Acquire) != 0
            {
                return Err(
                    "pre-101 missing, duplicate, or malformed admission evaluated provider or dispatch"
                        .to_owned(),
                );
            }
            let valid = unsigned.replace("\r\n\r\n", "\r\nAuthorization: Bearer alpha\r\n\r\n");
            let (mut accepted, response) =
                websocket_upgrade(&cx, address, valid.as_bytes()).await?;
            if !response.starts_with(b"HTTP/1.1 101") {
                return Err("valid WebSocket bearer did not pass Upgrade admission".to_owned());
            }
            let request = JsonRpcRequest::new(
                "tools/call",
                Some(serde_json::json!({
                    "name": "modern_http_auth_counter",
                    "arguments": {},
                    "_meta": {
                        MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                        FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                    },
                })),
                7_104_i64,
            );
            accepted
                .write_all(&masked_websocket_message(JsonRpcMessage::Request(request)))
                .await
                .map_err(|error| format!("valid WebSocket tool write failed: {error}"))?;
            accepted
                .flush()
                .await
                .map_err(|error| format!("valid WebSocket tool flush failed: {error}"))?;
            let deadline = cx.now().saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
            let mut response = Vec::new();
            while !response
                .windows("authenticated modern HTTP dispatch".len())
                .any(|window| window == b"authenticated modern HTTP dispatch")
            {
                let mut chunk = [0_u8; 1024];
                let read = asupersync::time::timeout_at(deadline, accepted.read(&mut chunk))
                    .await
                    .map_err(|_| "valid WebSocket tool response timed out".to_owned())?
                    .map_err(|error| format!("valid WebSocket tool response failed: {error}"))?;
                if read == 0 {
                    return Err("valid WebSocket bearer closed before handler dispatch".to_owned());
                }
                response.extend_from_slice(&chunk[..read]);
            }
            if handler_calls.load(Ordering::Acquire) != 1
                || provider_calls.load(Ordering::Acquire) != 1
                || middleware_calls.load(Ordering::Acquire) != 1
                || saw_credential.load(Ordering::Acquire)
            {
                return Err(
                    "valid WebSocket bearer did not consume exactly one custody evaluation"
                        .to_owned(),
                );
            }
            // The first provider evaluation above was the accepted bearer.
            // This second evaluation must be counted and denied before 101;
            // it must not produce another custody or dispatch mutation.
            let invalid = unsigned.replace(
                "\r\n\r\n",
                "\r\nAuthorization: Bearer invalid-never-echo\r\n\r\n",
            );
            let (_invalid, invalid_response) =
                websocket_upgrade(&cx, address, invalid.as_bytes()).await?;
            if !invalid_response.starts_with(b"HTTP/1.1 401")
                || String::from_utf8_lossy(&invalid_response).contains("invalid-never-echo")
                || provider_calls.load(Ordering::Acquire) != 2
                || handler_calls.load(Ordering::Acquire) != 1
                || middleware_calls.load(Ordering::Acquire) != 1
            {
                return Err(
                    "second provider evaluation did not reject invalid WebSocket bearer before 101"
                        .to_owned(),
                );
            }
            let mixed = JsonRpcRequest::new(
                "tools/call",
                Some(serde_json::json!({
                    "authorization": "Bearer never-log-or-handle",
                    "name": "modern_http_auth_counter",
                    "arguments": {},
                    "_meta": {
                        MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                        FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                    },
                })),
                7_105_i64,
            );
            accepted
                .write_all(&masked_websocket_message(JsonRpcMessage::Request(mixed)))
                .await
                .map_err(|error| format!("mixed WebSocket credential write failed: {error}"))?;
            accepted
                .flush()
                .await
                .map_err(|error| format!("mixed WebSocket credential flush failed: {error}"))?;
            let mut rejection = [0_u8; 1024];
            let rejected = asupersync::time::timeout_at(deadline, accepted.read(&mut rejection))
                .await
                .map_err(|_| "mixed WebSocket credential response timed out".to_owned())?
                .map_err(|error| format!("mixed WebSocket credential response failed: {error}"))?;
            if rejected == 0
                || !rejection[..rejected]
                    .windows(5)
                    .any(|window| window == b"error")
                || String::from_utf8_lossy(&rejection[..rejected]).contains("never-log-or-handle")
                || handler_calls.load(Ordering::Acquire) != 1
                || provider_calls.load(Ordering::Acquire) != 2
                || middleware_calls.load(Ordering::Acquire) != 1
                || saw_credential.load(Ordering::Acquire)
            {
                return Err(
                    "mixed WebSocket credential escaped custody or reached dispatch".to_owned(),
                );
            }
            drop(accepted);
            listener_task.abort();
            let join_cx = Cx::for_testing();
            let shutdown = listener_task
                .join(&join_cx)
                .await
                .map_err(|error| format!("WebSocket auth listener join failed: {error:?}"))?
                .map_err(|error| format!("WebSocket auth listener failed: {error}"))?;
            if !matches!(shutdown, WebSocketServerShutdown::Quiescent) {
                return Err("WebSocket authentication shutdown retained a child".to_owned());
            }
            Ok(())
        });
    }

    #[cfg(feature = "websocket")]
    #[test]
    fn websocket_nonquiescent_settle_for_drains_successful_retained_child_once() {
        run_live_http_test(|cx| async move {
            let shutdown_calls = Arc::new(AtomicUsize::new(0));
            let shutdown_observer = Arc::clone(&shutdown_calls);
            let server = Arc::new(
                Server::new("websocket-settlement-success", "1.0.0")
                    .on_shutdown(move || {
                        shutdown_observer.fetch_add(1, Ordering::AcqRel);
                    })
                    .build(),
            );
            let release_child = Arc::new(AtomicBool::new(false));
            let child_release = Arc::clone(&release_child);
            let child_started = Arc::new(AtomicBool::new(false));
            let child_started_observer = Arc::clone(&child_started);
            let scope = cx.scope();
            let child = cx
                .spawn_in(&scope, move |_child_cx| async move {
                    child_started_observer.store(true, Ordering::Release);
                    while !child_release.load(Ordering::Acquire) {
                        asupersync::runtime::yield_now().await;
                    }
                    Ok(())
                })
                .map_err(|error| format!("successful retained child admission failed: {error}"))?;
            let deadline = Instant::now() + Duration::from_secs(1);
            while !child_started.load(Ordering::Acquire) && Instant::now() < deadline {
                asupersync::runtime::yield_now().await;
            }
            if !child_started.load(Ordering::Acquire) {
                return Err("successful retained child did not begin".to_owned());
            }
            let mut retained = WebSocketNonquiescentShutdown {
                children: WebSocketConnectionChildren {
                    tasks: vec![child],
                    terminal_failure: Arc::default(),
                },
                server,
                listener_error: None,
                shutdown_complete: false,
            };
            if retained.remaining_connections() != 1 {
                return Err("successful retained child was not caller-owned".to_owned());
            }
            release_child.store(true, Ordering::Release);
            if !retained
                .settle_for(Duration::from_secs(1))
                .await
                .map_err(|error| format!("successful retained child settlement failed: {error}"))?
                || retained.remaining_connections() != 0
                || shutdown_calls.load(Ordering::Acquire) != 1
            {
                return Err(
                    "successful retained child did not drain to one cleanup-backed settlement"
                        .to_owned(),
                );
            }
            Ok(())
        });
    }

    #[cfg(feature = "websocket")]
    #[test]
    fn websocket_nonquiescent_settle_for_retains_abort_race_and_reaped_panic() {
        run_live_http_test(|cx| async move {
            let shutdown_calls = Arc::new(AtomicUsize::new(0));
            let shutdown_observer = Arc::clone(&shutdown_calls);
            let server = Arc::new(
                Server::new("websocket-settlement-drain", "1.0.0")
                    .on_shutdown(move || {
                        shutdown_observer.fetch_add(1, Ordering::AcqRel);
                    })
                    .build(),
            );
            let scope = cx.scope();
            let release_live_child = Arc::new(AtomicBool::new(false));
            let live_child_release = Arc::clone(&release_live_child);
            let live_child_started = Arc::new(AtomicBool::new(false));
            let live_child_started_observer = Arc::clone(&live_child_started);
            let retained_live = cx
                .spawn_in(&scope, move |_child_cx| async move {
                    live_child_started_observer.store(true, Ordering::Release);
                    while !live_child_release.load(Ordering::Acquire) {
                        // Deliberately ignore the child Cx cancellation. This
                        // is the shutdown-debt shape that must remain caller
                        // owned after the listener aborts its child.
                        asupersync::runtime::yield_now().await;
                    }
                    Ok(())
                })
                .map_err(|error| format!("retained WebSocket child admission failed: {error}"))?;
            let started_deadline = Instant::now() + Duration::from_secs(1);
            while !live_child_started.load(Ordering::Acquire) && Instant::now() < started_deadline {
                asupersync::runtime::yield_now().await;
            }
            if !live_child_started.load(Ordering::Acquire) {
                return Err("WebSocket retained child did not begin before abort".to_owned());
            }
            let failed = cx
                .spawn_in(&scope, move |_child_cx| async move {
                    panic!("forced WebSocket child failure")
                })
                .map_err(|error| format!("failed WebSocket child admission failed: {error}"))?;
            retained_live.abort();
            let mut children = WebSocketConnectionChildren {
                tasks: vec![retained_live, failed],
                terminal_failure: Arc::default(),
            };
            let deadline = Instant::now() + Duration::from_secs(1);
            while !children.has_terminal_failure() && Instant::now() < deadline {
                children.reap_finished();
                if !children.has_terminal_failure() {
                    asupersync::runtime::yield_now().await;
                }
            }
            if !children.has_terminal_failure() {
                return Err("WebSocket child reaper did not retain the forced panic".to_owned());
            }
            let retained = WebSocketServerShutdown::Nonquiescent(WebSocketNonquiescentShutdown {
                children,
                server,
                listener_error: None,
                shutdown_complete: false,
            });
            let WebSocketServerShutdown::Nonquiescent(retained) = retained else {
                return Err("forced WebSocket retained work did not report Nonquiescent".to_owned());
            };
            if retained.remaining_connections() != 1 {
                return Err(
                    "WebSocket abort race did not retain exactly one live caller-owned child"
                        .to_owned(),
                );
            }
            let mut retained = retained;
            if retained
                .settle_for(Duration::ZERO)
                .await
                .map_err(|error| format!("WebSocket retained-child probe failed: {error}"))?
            {
                return Err(
                    "WebSocket settle_for falsely reported an abort-race child as settled"
                        .to_owned(),
                );
            }
            if retained.remaining_connections() != 1 {
                return Err("WebSocket settle_for detached or lost the abort-race child".to_owned());
            }
            release_live_child.store(true, Ordering::Release);
            let error = retained
                .settle_for(Duration::from_secs(1))
                .await
                .expect_err("a real child failure must be returned after all children drain");
            if !error
                .message
                .contains("WebSocket connection child settlement failure")
                || shutdown_calls.load(Ordering::Acquire) != 1
            {
                return Err(
                    "WebSocket settlement skipped cleanup or hid its recorded child failure"
                        .to_owned(),
                );
            }
            Ok(())
        });
    }

    #[cfg(feature = "websocket")]
    #[test]
    fn websocket_settle_for_returns_listener_failure_after_cleanup() {
        run_live_http_test(|_cx| async move {
            let shutdown_calls = Arc::new(AtomicUsize::new(0));
            let shutdown_observer = Arc::clone(&shutdown_calls);
            let server = Arc::new(
                Server::new("websocket-settle-for-listener-error", "1.0.0")
                    .on_shutdown(move || {
                        shutdown_observer.fetch_add(1, Ordering::AcqRel);
                    })
                    .build(),
            );
            let mut retained = WebSocketNonquiescentShutdown {
                children: WebSocketConnectionChildren::default(),
                server,
                listener_error: Some(McpError::internal_error("forced accept-loop failure")),
                shutdown_complete: false,
            };
            let error = retained
                .settle_for(Duration::ZERO)
                .await
                .expect_err("settle_for must not hide a recorded listener failure");
            if !error.message.contains("forced accept-loop failure")
                || shutdown_calls.load(Ordering::Acquire) != 1
            {
                return Err(
                    "WebSocket settle_for did not preserve listener error after cleanup".to_owned(),
                );
            }
            Ok(())
        });
    }

    fn live_http_test_timeout(operation: &str) -> String {
        format!("Timeout while waiting for {operation}")
    }

    #[test]
    fn boxed_extension_settings_resolver_preserves_inactive_disposition() {
        struct InactiveResolver;

        impl ExtensionSettingsCompatibilityResolver for InactiveResolver {
            fn resolve(
                &mut self,
                descriptor: &ExtensionDescriptor,
                _client: &ExtensionSettings,
                _server: &ExtensionSettings,
            ) -> Result<ExtensionSettings, ExtensionNegotiationError> {
                Err(ExtensionNegotiationError::SettingsCompatibilityRejected(
                    descriptor.id.to_string(),
                ))
            }

            fn resolve_with_disposition(
                &mut self,
                _descriptor: &ExtensionDescriptor,
                _client: &ExtensionSettings,
                _server: &ExtensionSettings,
            ) -> Result<ExtensionSettingsResolution, ExtensionNegotiationError> {
                Ok(ExtensionSettingsResolution::Inactive)
            }
        }

        let settings = ExtensionSettings::new(serde_json::json!({}))
            .expect("empty extension settings must be valid");
        let mut resolver = BoxedExtensionSettingsResolver(Box::new(InactiveResolver));
        let disposition = resolver
            .resolve_with_disposition(
                &fastmcp_protocol::extensions::official_mcp_apps_descriptor(),
                &settings,
                &settings,
            )
            .expect("boxed resolver must retain an inactive disposition");

        assert_eq!(disposition, ExtensionSettingsResolution::Inactive);
    }

    #[cfg(all(feature = "apps", feature = "tasks"))]
    #[test]
    fn builder_mcp_apps_composes_with_final_tasks_and_preserves_inactive_apps() {
        let delivered = Arc::new(Mutex::new(Vec::new()));
        let server = Server::new("apps-and-tasks-server", "1.0.0")
            .mcp_apps()
            .expect("official Apps installs before final Tasks")
            .final_tasks(final_tasks_test_runtime(Arc::clone(&delivered)))
            .expect("final Tasks composes with official Apps")
            .build();
        let apps_id = fastmcp_protocol::official_mcp_apps_extension_id();
        let tasks_id = fastmcp_protocol::official_tasks_extension_id();

        assert_eq!(
            server
                .extension_registry_receipt()
                .expect("Apps and Tasks registry is frozen")
                .descriptor_count(),
            2
        );
        let discovery = serde_json::to_value(
            server
                .server_discovery()
                .expect("Apps and Tasks discovery is available"),
        )
        .expect("Apps and Tasks discovery serializes");
        assert_eq!(
            discovery.pointer("/capabilities/extensions/io.modelcontextprotocol~1ui"),
            Some(&serde_json::json!({}))
        );
        assert_eq!(
            discovery.pointer("/capabilities/extensions/io.modelcontextprotocol~1tasks"),
            Some(&serde_json::json!({}))
        );

        let client = ClientExtensionDiscovery {
            extensions: BTreeMap::from([
                (
                    apps_id.clone(),
                    McpAppsClientSettings::new(vec!["text/plain".to_owned()])
                        .expect("another bounded MIME type is valid Apps settings")
                        .to_extension_settings(),
                ),
                (tasks_id.clone(), official_tasks_empty_settings()),
            ]),
        };
        let negotiated = server
            .negotiate_extensions(&client)
            .expect("valid inactive Apps settings do not reject Tasks negotiation");
        assert_eq!(
            negotiated.inactive_reason(&apps_id),
            Some(ExtensionInactiveReason::SettingsInactiveFallback)
        );
        assert!(negotiated.active(&tasks_id).is_some());
    }

    #[cfg(feature = "apps")]
    #[test]
    fn builder_mcp_apps_ui_resource_binds_a_final_only_ui_catalog_entry() {
        let resource = crate::providers::McpAppsUiResource::try_new(
            fastmcp_protocol::common_types::AbsoluteUri::parse("ui://weather/dashboard")
                .expect("valid ui URI"),
            "weather-dashboard",
            "<main>weather</main>",
        )
        .expect("valid Apps UI resource");
        let server = Server::new("apps-ui-resource", "1.0")
            .mcp_apps()
            .expect("Apps capability installs")
            .mcp_apps_ui_resource(resource)
            .expect("Apps UI resource binds after Apps opt-in")
            .build();

        let inbound =
            InboundRequestContext::new(Cx::for_testing(), 901, InboundRequestTransport::Memory);
        let response = block_on(server.dispatch_stateless(
            &inbound,
            &JsonRpcRequest::new(
                "resources/list",
                Some(serde_json::json!({
                    "_meta": {
                        "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                        "io.modelcontextprotocol/clientCapabilities": {},
                    },
                })),
                901_i64,
            ),
        ))
        .expect("modern resource catalog dispatch succeeds");
        let resources = response.result.expect("modern resource list has a result");
        assert_eq!(resources["resources"][0]["uri"], "ui://weather/dashboard");
        assert_eq!(
            resources["resources"][0]["mimeType"],
            fastmcp_protocol::MCP_APPS_HTML_MIME_TYPE
        );
        let read_inbound =
            InboundRequestContext::new(Cx::for_testing(), 902, InboundRequestTransport::Memory);
        let read_request = JsonRpcRequest::new(
            "resources/read",
            Some(serde_json::json!({
                "uri": "ui://weather/dashboard",
                "_meta": {
                    "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                    "io.modelcontextprotocol/clientCapabilities": {},
                },
            })),
            902_i64,
        );
        let read = block_on(server.dispatch_stateless(&read_inbound, &read_request))
            .expect("modern Apps UI read reaches its final-only resource");
        assert!(
            read.error.is_none(),
            "modern Apps UI read must succeed: {:?}",
            read.error
        );
        let contents = read.result.expect("modern UI read has a result");
        assert_eq!(contents["contents"][0]["text"], "<main>weather</main>");
        assert_eq!(
            contents["contents"][0]["mimeType"],
            fastmcp_protocol::MCP_APPS_HTML_MIME_TYPE
        );
        assert!(
            server.resources().is_empty(),
            "the Apps UI document must remain absent from the exact-2024 catalog"
        );
    }

    #[cfg(feature = "apps")]
    #[test]
    fn builder_mcp_apps_ui_resource_rejects_only_missing_apps_opt_in_without_mutation() {
        let resource = crate::providers::McpAppsUiResource::try_new(
            fastmcp_protocol::common_types::AbsoluteUri::parse("ui://weather/dashboard")
                .expect("valid ui URI"),
            "weather-dashboard",
            "<main>weather</main>",
        )
        .expect("valid Apps UI resource");
        let error = match Server::new("apps-ui-resource", "1.0").mcp_apps_ui_resource(resource) {
            Ok(_) => panic!("changing only the missing Apps opt-in must reject the UI resource"),
            Err(error) => error,
        };
        assert_eq!(error.code, McpErrorCode::InvalidRequest);
    }

    #[cfg(all(feature = "apps", feature = "tasks"))]
    #[test]
    fn builder_final_tasks_then_mcp_apps_preserves_both_discovery_markers() {
        let server = Server::new("tasks-then-apps-server", "1.0.0")
            .final_tasks(final_tasks_test_runtime(Arc::new(Mutex::new(Vec::new()))))
            .expect("final Tasks configures before official Apps")
            .mcp_apps()
            .expect("official Apps composes after final Tasks")
            .build();
        let discovery = serde_json::to_value(
            server
                .server_discovery()
                .expect("Apps and Tasks discovery is available"),
        )
        .expect("Apps and Tasks discovery serializes");

        assert_eq!(
            discovery.pointer("/capabilities/extensions/io.modelcontextprotocol~1ui"),
            Some(&serde_json::json!({}))
        );
        assert_eq!(
            discovery.pointer("/capabilities/extensions/io.modelcontextprotocol~1tasks"),
            Some(&serde_json::json!({}))
        );
    }

    #[derive(Debug, Default)]
    struct HttpOverlapControlState {
        enabled: bool,
        entries: usize,
        permits: usize,
    }

    #[derive(Debug, Default)]
    struct HttpOverlapControl {
        state: Mutex<HttpOverlapControlState>,
        changed: Condvar,
    }

    impl HttpOverlapControl {
        fn begin(&self) -> HttpOverlapControlGuard<'_> {
            let mut state = self.state.lock().expect("HTTP overlap control poisoned");
            state.enabled = true;
            state.entries = 0;
            state.permits = 0;
            HttpOverlapControlGuard { control: self }
        }

        fn enter_and_wait(&self) {
            let mut state = self.state.lock().expect("HTTP overlap control poisoned");
            if !state.enabled {
                return;
            }
            state.entries += 1;
            self.changed.notify_all();
            while state.enabled && state.permits == 0 {
                state = self
                    .changed
                    .wait(state)
                    .expect("HTTP overlap control poisoned while waiting");
            }
            state.permits = state.permits.saturating_sub(1);
        }

        fn wait_for_entries(&self, target: usize, timeout: Duration) -> bool {
            let state = self.state.lock().expect("HTTP overlap control poisoned");
            let (state, _) = self
                .changed
                .wait_timeout_while(state, timeout, |state| state.entries < target)
                .expect("HTTP overlap control poisoned while observing entries");
            state.entries >= target
        }

        fn release_one(&self) {
            let mut state = self.state.lock().expect("HTTP overlap control poisoned");
            state.permits = state.permits.saturating_add(1);
            self.changed.notify_all();
        }

        fn disable(&self) {
            let mut state = self.state.lock().expect("HTTP overlap control poisoned");
            state.enabled = false;
            state.permits = 0;
            self.changed.notify_all();
        }
    }

    struct HttpOverlapControlGuard<'a> {
        control: &'a HttpOverlapControl,
    }

    impl Drop for HttpOverlapControlGuard<'_> {
        fn drop(&mut self) {
            self.control.disable();
        }
    }

    fn http_overlap_metrics() -> &'static HttpOverlapMetrics {
        HTTP_OVERLAP_METRICS.get_or_init(HttpOverlapMetrics::default)
    }

    fn http_overlap_lock() -> &'static Mutex<()> {
        HTTP_OVERLAP_LOCK.get_or_init(|| Mutex::new(()))
    }

    fn http_overlap_control() -> &'static HttpOverlapControl {
        HTTP_OVERLAP_CONTROL.get_or_init(HttpOverlapControl::default)
    }

    pub(super) fn record_live_http_listener_wait() {
        LIVE_HTTP_LISTENER_WAITS.fetch_add(1, Ordering::AcqRel);
    }

    pub(super) fn record_live_http_connection_read_wait() {
        LIVE_HTTP_CONNECTION_READ_WAITS.fetch_add(1, Ordering::AcqRel);
    }

    fn live_http_listener_wait_count() -> usize {
        LIVE_HTTP_LISTENER_WAITS.load(Ordering::Acquire)
    }

    fn live_http_connection_read_wait_count() -> usize {
        LIVE_HTTP_CONNECTION_READ_WAITS.load(Ordering::Acquire)
    }

    async fn wait_for_live_http_probe(
        cx: &Cx,
        before: usize,
        probe: fn() -> usize,
    ) -> Result<(), String> {
        let deadline = cx.now().saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
        while probe() <= before {
            cx.checkpoint()
                .map_err(|error| format!("live HTTP probe caller stopped: {error}"))?;
            asupersync::time::timeout_at(
                deadline,
                asupersync::time::sleep(cx.now(), Duration::from_millis(1)),
            )
            .await
            .map_err(|_| live_http_test_timeout("live HTTP probe"))?;
        }
        Ok(())
    }

    async fn wait_for_live_http_flag(
        cx: &Cx,
        flag: &AtomicBool,
        operation: &str,
    ) -> Result<(), String> {
        let deadline = cx.now().saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
        while !flag.load(Ordering::Acquire) {
            cx.checkpoint()
                .map_err(|error| format!("{operation} caller stopped: {error}"))?;
            asupersync::time::timeout_at(
                deadline,
                asupersync::time::sleep(cx.now(), Duration::from_millis(1)),
            )
            .await
            .map_err(|_| live_http_test_timeout(operation))?;
        }
        Ok(())
    }

    async fn wait_for_live_http_test_result<T>(receiver: Receiver<T>) -> Result<T, String> {
        let cx = Cx::current().expect("the test runtime must install an ambient Cx while polling");
        let deadline = cx.now().saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
        loop {
            match receiver.try_recv() {
                Ok(result) => return Ok(result),
                Err(TryRecvError::Disconnected) => {
                    panic!("live HTTP test task exited without reporting its result");
                }
                Err(TryRecvError::Empty) => {
                    asupersync::time::timeout_at(
                        deadline,
                        asupersync::time::sleep(cx.now(), Duration::from_millis(1)),
                    )
                    .await
                    .map_err(|_| live_http_test_timeout("live HTTP test result"))?;
                }
            }
        }
    }

    /// Runnable time one whole live HTTP test may take.
    ///
    /// Each client step has its own [`LIVE_HTTP_TEST_TIMEOUT_NANOS`] bound,
    /// but `serve` returns only once its caller `Cx` is cancelled, and most
    /// tests cancel it only on their client's success path. A client that
    /// failed first therefore left `serve` waiting forever. In a no-legacy test
    /// build that forced the legacy loop, four tests hung the process this way
    /// until the runner killed it:
    /// `live_http_legacy_initialize_is_peer_cancellation_protected`,
    /// `live_http_legacy_sse_advertises_the_request_host_on_wildcard_bind`,
    /// `live_http_legacy_sse_peer_close_cancels_its_busy_request` and
    /// `live_http_legacy_sse_peer_close_does_not_cancel_another_session`.
    const LIVE_HTTP_WHOLE_TEST_BOUND: Duration = Duration::from_secs(60);

    fn run_live_http_test<F, Fut>(operation: F)
    where
        F: FnOnce(Cx) -> Fut + Send + 'static,
        Fut: Future<Output = Result<(), String>> + Send + 'static,
    {
        let runtime = RuntimeBuilder::current_thread()
            .with_reactor(create_reactor().expect("live HTTP test reactor must initialize"))
            .blocking_threads(4, MAX_DISPATCH_QUEUE_DEPTH)
            .build()
            .expect("live HTTP test runtime must initialize");
        let host = RunnableClock::start();
        let (result, expired) = runtime.block_on(async move {
            let cx = Cx::current().expect("the live HTTP test runtime must install an ambient Cx");
            // On expiry the watchdog cancels the caller `Cx`, which is what
            // lets a `serve` with no remaining canceller return, so the test
            // fails with this bound's message instead of hanging.
            let (finished, finished_signal) = sync_channel::<()>(0);
            let watchdog_cx = cx.clone();
            let watchdog = thread::spawn(move || {
                let started = host.mark();
                while !host.expired(started, LIVE_HTTP_WHOLE_TEST_BOUND) {
                    if !matches!(
                        finished_signal.recv_timeout(Duration::from_millis(50)),
                        Err(std::sync::mpsc::RecvTimeoutError::Timeout)
                    ) {
                        return None;
                    }
                }
                watchdog_cx.cancel_with(
                    CancelKind::Deadline,
                    Some("live HTTP test exceeded its whole-test bound"),
                );
                Some(host.describe(started))
            });
            let result = operation(cx).await;
            drop(finished);
            let expired = watchdog
                .join()
                .expect("the live HTTP test watchdog must not panic");
            (result, expired)
        });
        if let Some(elapsed) = expired {
            panic!(
                "live HTTP test exceeded its {LIVE_HTTP_WHOLE_TEST_BOUND:?} whole-test bound after {elapsed}; the watchdog cancelled its caller Cx so a serve left without a canceller could return. Test result: {result:?}"
            );
        }
        result.unwrap();
    }

    async fn require_quiescent_http_shutdown(
        shutdown: HttpServerShutdown,
        probe: &str,
    ) -> Result<(), String> {
        match shutdown {
            HttpServerShutdown::Quiescent => Ok(()),
            HttpServerShutdown::Nonquiescent(mut shutdown) => {
                let initial = shutdown.poll_settlement();
                let settled = shutdown.settle_for(Duration::from_secs(1)).await;
                Err(format!(
                    "{probe} unexpectedly retained caller-owned HTTP children; initial={initial:?}, after bounded settlement={settled:?}"
                ))
            }
        }
    }

    fn run_live_modern_pump<R>(server: Server, recv: R, responses: Arc<LiveModernResponses>) -> i32
    where
        R: FnMut(&Cx, &AtomicBool) -> Result<JsonRpcMessage, TransportError> + Send + 'static,
    {
        let runtime = RuntimeBuilder::current_thread()
            .with_reactor(create_reactor().expect("live modern test reactor must initialize"))
            .blocking_threads(4, MAX_DISPATCH_QUEUE_DEPTH)
            .build()
            .expect("live modern test runtime must initialize");
        let (sender, receiver) = sync_channel(1);
        runtime
            .block_on(async move {
                let cx =
                    Cx::current().expect("the live modern test runtime must install an ambient Cx");
                let dispatch_cx = cx.clone();
                match cx.spawn_blocking(move |pump_cx| {
                    let result = Arc::new(server).run_loop_pump_with_policy(
                        &pump_cx,
                        &dispatch_cx,
                        recv,
                        move |_send_cx, message| {
                            responses.record(message.clone());
                            Ok(())
                        },
                        Arc::new(|_| {}),
                        "live-modern-test",
                        false,
                        None,
                        true,
                        true,
                        None,
                        None,
                        None,
                        PumpIoMode::Split,
                    );
                    let _ = sender.send(result);
                }) {
                    // The blocking closure owns the product return value.
                    // Joining its cancellation-dominant wrapper can instead
                    // report shutdown when the pump closes the server region
                    // immediately after producing that value.
                    Ok(_pump) => wait_for_live_http_test_result(receiver).await,
                    Err(error) => Err(format!("live modern pump admission failed: {error}")),
                }
            })
            .expect("live modern pump must complete")
    }

    fn run_live_split_transport<R, S>(
        completion_timeout: Duration,
        server: Server,
        recv: R,
        send: S,
    ) -> Result<(), String>
    where
        R: TransportRecvHalf + Send + 'static,
        S: TransportSendHalf + 'static,
    {
        let runtime = RuntimeBuilder::current_thread()
            .with_reactor(create_reactor().expect("live split transport reactor must initialize"))
            .blocking_threads(4, MAX_DISPATCH_QUEUE_DEPTH)
            .build()
            .expect("live split transport runtime must initialize");
        let (sender, receiver) = sync_channel(1);
        runtime.block_on(async move {
            let cx =
                Cx::current().expect("the live split transport runtime must install an ambient Cx");
            let dispatch_cx = cx.clone();
            match cx.spawn_blocking(move |pump_cx| {
                let result = server.run_split_transport_returning_with_dispatch_cx(
                    &pump_cx,
                    &dispatch_cx,
                    recv,
                    send,
                );
                let _ = sender.send(result);
            }) {
                // Read the value from the completed blocking closure itself;
                // the wrapper join is cancellation-dominant during shutdown.
                Ok(_pump) => {
                    // Counted in runnable time, so a loaded full suite cannot
                    // expire the bound while a stalled transport still does.
                    let host = RunnableClock::start();
                    let started = host.mark();
                    loop {
                        match receiver.try_recv() {
                            Ok(result) => break result.map_err(|error| error.to_string()),
                            Err(TryRecvError::Disconnected) => {
                                panic!(
                                    "live split transport task exited without reporting its result"
                                );
                            }
                            Err(TryRecvError::Empty) => {
                                if host.expired(started, completion_timeout) {
                                    return Err(format!(
                                        "{} after {}",
                                        live_http_test_timeout("live split transport result"),
                                        host.describe(started)
                                    ));
                                }
                                asupersync::time::sleep(cx.now(), Duration::from_millis(1)).await;
                            }
                        }
                    }
                }
                Err(error) => Err(format!("live split transport admission failed: {error}")),
            }
        })
    }

    async fn live_http_exchange(address: SocketAddr, request: Vec<u8>) -> Result<Vec<u8>, String> {
        let cx = Cx::current()
            .expect("the test runtime must install an ambient Cx for live HTTP exchange");
        let deadline = cx.now().saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
        let mut stream = asupersync::time::timeout_at(deadline, AsyncTcpStream::connect(address))
            .await
            .map_err(|_| live_http_test_timeout("live HTTP client connection"))?
            .map_err(|error| format!("live HTTP client connect failed: {error}"))?;
        asupersync::time::timeout_at(deadline, stream.write_all(&request))
            .await
            .map_err(|_| live_http_test_timeout("live HTTP client request write"))?
            .map_err(|error| format!("live HTTP client write failed: {error}"))?;
        asupersync::time::timeout_at(deadline, stream.flush())
            .await
            .map_err(|_| live_http_test_timeout("live HTTP client request flush"))?
            .map_err(|error| format!("live HTTP client flush failed: {error}"))?;
        let mut response = Vec::new();
        read_live_http_to_end(&mut stream, &mut response, "live HTTP client response EOF").await?;
        Ok(response)
    }

    fn live_http_post(
        path_and_query: &str,
        body: &[u8],
        extra_headers: &[(&str, &str)],
    ) -> Vec<u8> {
        let mut request = format!(
            "POST {path_and_query} HTTP/1.1\r\nHost: loopback\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n",
            body.len()
        );
        for (name, value) in extra_headers {
            request.push_str(name);
            request.push_str(": ");
            request.push_str(value);
            request.push_str("\r\n");
        }
        request.push_str("\r\n");
        let mut request = request.into_bytes();
        request.extend_from_slice(body);
        request
    }

    async fn live_http_strict_admission_exchange(
        cx: &Cx,
        mirrored_method_header: &'static str,
    ) -> Result<Vec<u8>, String> {
        live_http_admission_exchange(
            cx,
            vec![
                ("Accept", "application/json"),
                ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                ("Mcp-Method", mirrored_method_header),
            ],
        )
        .await
    }

    async fn live_http_admission_exchange(
        cx: &Cx,
        headers: Vec<(&'static str, &'static str)>,
    ) -> Result<Vec<u8>, String> {
        let bound = Server::new("live-http-strict-admission", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .build()
            .bind_http(cx, "127.0.0.1:0")
            .await
            .map_err(|error| format!("strict admission HTTP bind failed: {error}"))?;
        let address = bound
            .local_addr()
            .map_err(|error| format!("strict admission HTTP address failed: {error}"))?;
        let caller_cx = cx.clone();
        let mut client = cx
            .spawn(move |_client_cx| async move {
                let request = JsonRpcRequest::new(
                    SERVER_DISCOVER_METHOD,
                    Some(serde_json::json!({
                        "_meta": {
                            MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                            FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                        },
                    })),
                    803_i64,
                );
                let body = serde_json::to_vec(&request).map_err(|error| {
                    format!("strict admission request did not serialize: {error}")
                })?;
                let response =
                    live_http_exchange(address, live_http_post("/mcp", &body, &headers)).await;
                caller_cx.cancel_with(CancelKind::User, Some("strict admission exchange complete"));
                response
            })
            .map_err(|error| format!("strict admission client admission failed: {error}"))?;

        let serve = bound.serve(cx).await;
        let response = client
            .join(cx)
            .await
            .map_err(|error| format!("strict admission client failed: {error:?}"))??;
        let shutdown = serve.map_err(|error| format!("strict admission server failed: {error}"))?;
        require_quiescent_http_shutdown(shutdown, "strict admission").await?;
        Ok(response)
    }

    fn live_http_response_body(response: &[u8]) -> Result<&[u8], String> {
        response
            .windows(4)
            .position(|window| window == b"\r\n\r\n")
            .map(|offset| &response[offset + 4..])
            .ok_or_else(|| "live HTTP response omitted its header terminator".to_string())
    }

    fn live_http_sse_jsonrpc_response(response: &[u8]) -> Result<JsonRpcResponse, String> {
        let body = std::str::from_utf8(live_http_response_body(response)?)
            .map_err(|error| format!("live SSE body was not UTF-8: {error}"))?;
        let data = body
            .rsplit_once("data: ")
            .map(|(_, data)| data)
            .and_then(|data| data.split_once("\n\n").map(|(data, _)| data))
            .ok_or_else(|| "live SSE body omitted a JSON-RPC event".to_owned())?;
        serde_json::from_str(data)
            .map_err(|error| format!("live SSE JSON-RPC event was invalid: {error}"))
    }

    /// Parses the full chunked H1 body rather than searching its text. This
    /// keeps live SSE assertions honest about frame boundaries, ordering, and
    /// terminal EOF: an extra notification after the response is a fourth
    /// parsed frame, not an overlooked substring.
    fn live_http_chunked_sse_messages(response: &[u8]) -> Result<Vec<JsonRpcMessage>, String> {
        let mut remaining = live_http_response_body(response)?;
        let mut messages = Vec::new();
        loop {
            let Some(line_end) = remaining.windows(2).position(|window| window == b"\r\n") else {
                return Err("live SSE chunk omitted its size terminator".to_owned());
            };
            let chunk_size = std::str::from_utf8(&remaining[..line_end])
                .map_err(|error| format!("live SSE chunk size was not UTF-8: {error}"))?;
            let chunk_size = usize::from_str_radix(chunk_size, 16)
                .map_err(|error| format!("live SSE chunk size was invalid: {error}"))?;
            remaining = &remaining[line_end + 2..];
            if chunk_size == 0 {
                if remaining != b"\r\n" {
                    return Err("live SSE terminal chunk had trailing bytes".to_owned());
                }
                return Ok(messages);
            }
            if remaining.len() < chunk_size + 2 {
                return Err("live SSE chunk was truncated".to_owned());
            }
            let (chunk, suffix) = remaining.split_at(chunk_size);
            if &suffix[..2] != b"\r\n" {
                return Err("live SSE chunk omitted its data terminator".to_owned());
            }
            remaining = &suffix[2..];
            let event = std::str::from_utf8(chunk)
                .map_err(|error| format!("live SSE event was not UTF-8: {error}"))?;
            if !event.starts_with("event: message\n") || !event.ends_with("\n\n") {
                return Err(format!(
                    "live SSE chunk was not one message event: {event:?}"
                ));
            }
            let data = event
                .lines()
                .filter_map(|line| line.strip_prefix("data: "))
                .collect::<Vec<_>>();
            if data.len() != 1 {
                return Err(
                    "live SSE message event did not carry one JSON-RPC data line".to_owned(),
                );
            }
            messages.push(
                Codec::new()
                    .decode_complete_message(data[0].as_bytes())
                    .map_err(|error| format!("live SSE JSON-RPC event was invalid: {error}"))?,
            );
        }
    }

    fn live_http_response_header(response: &[u8], name: &str) -> Result<String, String> {
        let headers = std::str::from_utf8(
            response
                .windows(4)
                .position(|window| window == b"\r\n\r\n")
                .map(|offset| &response[..offset])
                .ok_or_else(|| "live HTTP response omitted its header terminator".to_string())?,
        )
        .map_err(|error| format!("live HTTP response headers were not UTF-8: {error}"))?;
        headers
            .split("\r\n")
            .skip(1)
            .find_map(|header| {
                let (header_name, value) = header.split_once(':')?;
                header_name
                    .eq_ignore_ascii_case(name)
                    .then(|| value.trim().to_owned())
            })
            .ok_or_else(|| format!("live HTTP response omitted {name} header"))
    }

    fn live_http_response_has_header(response: &[u8], name: &str) -> Result<bool, String> {
        let headers = std::str::from_utf8(
            response
                .windows(4)
                .position(|window| window == b"\r\n\r\n")
                .map(|offset| &response[..offset])
                .ok_or_else(|| "live HTTP response omitted its header terminator".to_string())?,
        )
        .map_err(|error| format!("live HTTP response headers were not UTF-8: {error}"))?;
        Ok(headers.split("\r\n").skip(1).any(|header| {
            header
                .split_once(':')
                .is_some_and(|(header_name, _)| header_name.eq_ignore_ascii_case(name))
        }))
    }

    async fn read_live_http_until(
        stream: &mut AsyncTcpStream,
        received: &mut Vec<u8>,
        needle: &[u8],
    ) -> Result<(), String> {
        let cx = Cx::current()
            .expect("the test runtime must install an ambient Cx for live HTTP SSE reads");
        let deadline = cx.now().saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
        while !received
            .windows(needle.len())
            .any(|window| window == needle)
        {
            if received.len() > 64 * 1024 {
                return Err("live HTTP SSE response exceeded the test bound".to_string());
            }
            let mut chunk = [0_u8; 2048];
            let read = asupersync::time::timeout_at(deadline, stream.read(&mut chunk))
                .await
                .map_err(|_| live_http_test_timeout("live HTTP SSE response"))?
                .map_err(|error| format!("live HTTP SSE read failed: {error}"))?;
            if read == 0 {
                return Err("live HTTP SSE connection closed before expected event".to_string());
            }
            received.extend_from_slice(&chunk[..read]);
        }
        Ok(())
    }

    async fn read_live_http_to_end(
        stream: &mut AsyncTcpStream,
        received: &mut Vec<u8>,
        operation: &str,
    ) -> Result<(), String> {
        let cx = Cx::current()
            .expect("the test runtime must install an ambient Cx for live HTTP EOF reads");
        let deadline = cx.now().saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
        asupersync::time::timeout_at(deadline, stream.read_to_end(received))
            .await
            .map_err(|_| live_http_test_timeout(operation))?
            .map_err(|error| format!("{operation} failed: {error}"))?;
        Ok(())
    }

    // Exact-2024 era: opens a legacy HTTP SSE session.
    #[cfg(feature = "legacy-2024-11-05")]
    async fn open_live_legacy_http_session(
        address: SocketAddr,
        headers: &[(&str, &str)],
    ) -> Result<(AsyncTcpStream, String, Vec<u8>), String> {
        let cx = Cx::current()
            .expect("the test runtime must install an ambient Cx for legacy HTTP SSE setup");
        let deadline = cx.now().saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
        let mut stream = asupersync::time::timeout_at(deadline, AsyncTcpStream::connect(address))
            .await
            .map_err(|_| live_http_test_timeout("legacy HTTP SSE connection"))?
            .map_err(|error| format!("legacy HTTP SSE connect failed: {error}"))?;
        let mut extra_headers = String::new();
        for (name, value) in headers {
            extra_headers.push_str(name);
            extra_headers.push_str(": ");
            extra_headers.push_str(value);
            extra_headers.push_str("\r\n");
        }
        let request = format!(
            "GET /sse HTTP/1.1\r\nHost: {address}\r\nAccept: text/event-stream\r\nConnection: keep-alive\r\n{extra_headers}\r\n"
        );
        asupersync::time::timeout_at(deadline, stream.write_all(request.as_bytes()))
            .await
            .map_err(|_| live_http_test_timeout("legacy HTTP SSE request write"))?
            .map_err(|error| format!("legacy HTTP SSE write failed: {error}"))?;
        asupersync::time::timeout_at(deadline, stream.flush())
            .await
            .map_err(|_| live_http_test_timeout("legacy HTTP SSE request flush"))?
            .map_err(|error| format!("legacy HTTP SSE flush failed: {error}"))?;

        let mut received = Vec::new();
        let endpoint_prefix = format!("data: http://{address}/messages?session_id=");
        read_live_http_until(&mut stream, &mut received, endpoint_prefix.as_bytes()).await?;
        let received_text = std::str::from_utf8(&received)
            .map_err(|error| format!("legacy HTTP SSE endpoint was not UTF-8: {error}"))?;
        let session_id = received_text
            .split_once(&endpoint_prefix)
            .and_then(|(_, remainder)| remainder.split_whitespace().next())
            .ok_or_else(|| "legacy HTTP SSE endpoint omitted its session identifier".to_string())?
            .to_owned();
        Ok((stream, session_id, received))
    }

    // Exact-2024 era: waits on a legacy HTTP session's admissions.
    #[cfg(feature = "legacy-2024-11-05")]
    async fn wait_for_live_http_legacy_admission(
        cx: &Cx,
        session: &LiveHttpSession,
        request_id: &RequestId,
    ) -> Result<(), String> {
        let deadline = cx.now().saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
        while !session.cancellation.admissions.contains(request_id) {
            cx.checkpoint()
                .map_err(|error| format!("legacy HTTP admission wait stopped: {error}"))?;
            asupersync::time::timeout_at(
                deadline,
                asupersync::time::sleep(cx.now(), Duration::from_millis(1)),
            )
            .await
            .map_err(|_| live_http_test_timeout("legacy HTTP request admission"))?;
        }
        Ok(())
    }

    fn reset_http_overlap_metrics() {
        let metrics = http_overlap_metrics();
        metrics.current.store(0, Ordering::SeqCst);
        metrics.max.store(0, Ordering::SeqCst);
    }

    fn test_request_sender() -> RequestSender {
        let pending = Arc::new(PendingRequests::new());
        let send_fn: bidirectional::TransportSendFn =
            Arc::new(|message| Err(format!("unexpected outbound message in test: {message:?}")));
        RequestSender::new(pending, send_fn)
    }

    fn fixed_test_subject_for_credential(token: &str) -> McpResult<&'static str> {
        match token {
            "alpha" => Ok("principal-alpha"),
            "beta" => Ok("principal-beta"),
            _ => Err(McpError::invalid_request("unrecognized auth token")),
        }
    }

    fn initialized_test_session(server: &Server) -> Session {
        let mut session = Session::new(server.info.clone(), server.capabilities.clone());
        session.initialize(
            fastmcp_protocol::ClientInfo {
                name: "panic-containment-test-client".to_string(),
                version: "1.0.0".to_string(),
            },
            fastmcp_protocol::ClientCapabilities::default(),
            "2024-11-05".to_string(),
        );
        session
    }

    fn initialize_test_request(
        id: i64,
        client_name: &str,
        capabilities: fastmcp_protocol::ClientCapabilities,
    ) -> JsonRpcRequest {
        JsonRpcRequest::new(
            "initialize",
            Some(
                serde_json::to_value(InitializeParams {
                    protocol_version: "2024-11-05".to_string(),
                    capabilities,
                    client_info: fastmcp_protocol::ClientInfo {
                        name: client_name.to_string(),
                        version: "1.0.0".to_string(),
                    },
                })
                .expect("serialize initialize request"),
            ),
            id,
        )
    }

    #[test]
    fn resource_exhausted_masking_preserves_only_the_fixed_server_contract() {
        let fixed = mask_peer_error(resource_subscription_capacity_error(), true);
        assert_eq!(
            fixed.code,
            McpErrorCode::Custom(RESOURCE_EXHAUSTED_ERROR_CODE)
        );
        assert_eq!(fixed.message, RESOURCE_SUBSCRIPTION_CAPACITY_MESSAGE);
        assert!(fixed.data.is_none());

        let forged = mask_peer_error(
            McpError::with_data(
                McpErrorCode::Custom(RESOURCE_EXHAUSTED_ERROR_CODE),
                "credential-canary-must-be-masked",
                serde_json::json!({"token": "secret-canary"}),
            ),
            true,
        );
        assert_eq!(forged.message, "Internal server error");
        assert!(forged.data.is_none());
    }

    fn dispatch_test_request(
        server: &Server,
        session: &mut Session,
        method: &str,
    ) -> JsonRpcResponse {
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();
        block_on(server.dispatch_request(
            &Cx::for_testing(),
            session,
            JsonRpcRequest::new(method, Some(serde_json::json!({})), 1_i64),
            &notification_sender,
            &request_sender,
        ))
        .expect("test request should produce a JSON-RPC response")
    }

    #[cfg(feature = "tasks")]
    fn extension_registry_test_server(calls: Arc<AtomicUsize>) -> Server {
        let mut descriptors = ExtensionDescriptorRegistry::new();
        let tasks_id = register_official_tasks_extension(&mut descriptors)
            .expect("official Tasks descriptor must register");
        let mut handlers = ExtensionHandlerRegistry::new(descriptors);
        let handler_calls = Arc::clone(&calls);
        handlers
            .register(
                tasks_id.clone(),
                "tasks/get",
                move |context: &McpContext, request: serde_json::Value| {
                    assert_eq!(context.request_id(), 71);
                    assert!(
                        request
                            .pointer("/_meta/io.modelcontextprotocol~1protocolVersion")
                            .is_none(),
                        "extension handlers must not receive transport protocol metadata"
                    );
                    handler_calls.fetch_add(1, Ordering::SeqCst);
                    let value = request
                        .get("value")
                        .and_then(serde_json::Value::as_u64)
                        .ok_or_else(|| McpError::invalid_params("missing value"))?;
                    Ok(serde_json::json!({ "next": value + 1 }))
                },
            )
            .expect("official Tasks handler must register");

        Server::new("extension-registry-test", "1.0.0")
            .extension_registry(
                handlers,
                ServerExtensionDiscovery {
                    extensions: std::collections::BTreeMap::from([(
                        tasks_id,
                        official_tasks_empty_settings(),
                    )]),
                },
                |_descriptor: &fastmcp_protocol::ExtensionDescriptor,
                 _client: &fastmcp_protocol::ExtensionSettings,
                 _server: &fastmcp_protocol::ExtensionSettings|
                 -> Result<fastmcp_protocol::ExtensionSettings, ExtensionNegotiationError> {
                    Ok(official_tasks_empty_settings())
                },
            )
            .expect("extension registry must install")
            .build()
    }

    #[cfg(feature = "tasks")]
    fn extension_tasks_get_request(settings: serde_json::Value) -> JsonRpcRequest {
        JsonRpcRequest::new(
            "tasks/get",
            Some(serde_json::json!({
                "taskId": "task-extension-71",
                "value": 41,
                "_meta": {
                    "io.modelcontextprotocol/protocolVersion": MODERN_PROTOCOL_VERSION,
                    "io.modelcontextprotocol/clientCapabilities": {
                        "extensions": {
                            "io.modelcontextprotocol/tasks": settings,
                        },
                    },
                },
            })),
            71_i64,
        )
    }

    #[cfg(feature = "tasks")]
    fn extension_tasks_get_http_request(protocol_version: &str) -> HttpRequest {
        let mut request = extension_tasks_get_request(serde_json::json!({}));
        *request
            .params
            .as_mut()
            .and_then(|value| value.pointer_mut("/_meta/io.modelcontextprotocol~1protocolVersion"))
            .expect("extension request has modern protocol metadata") =
            serde_json::json!(protocol_version);
        HttpRequest::new(HttpMethod::Post, "/mcp")
            .with_header("content-type", "application/json")
            .with_header("accept", "application/json")
            .with_header("mcp-protocol-version", protocol_version)
            .with_header("mcp-method", "tasks/get")
            .with_header("mcp-name", "task-extension-71")
            .with_body(
                serde_json::to_vec(&request).expect("modern extension request must serialize"),
            )
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn server_extension_registry_freezes_and_advertises_installed_extension() {
        let server = extension_registry_test_server(Arc::new(AtomicUsize::new(0)));

        assert!(
            server
                .extension_handler_registry()
                .expect("installed registry must be retained")
                .is_frozen()
        );
        let receipt = server
            .extension_registry_receipt()
            .expect("installed registry must expose its canonical receipt");
        assert_eq!(receipt.descriptor_count(), 1);

        let discovery = serde_json::to_value(
            server
                .server_discovery()
                .expect("installed extension must be discoverable"),
        )
        .expect("server discovery must serialize");
        assert_eq!(
            discovery["capabilities"]["extensions"]["io.modelcontextprotocol/tasks"],
            serde_json::json!({})
        );
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn modern_extension_fallback_rejects_one_variable_incompatible_settings() {
        let calls = Arc::new(AtomicUsize::new(0));
        let server = extension_registry_test_server(Arc::clone(&calls));
        let inbound =
            InboundRequestContext::new(Cx::for_testing(), 71, InboundRequestTransport::Memory);

        let admitted = block_on(server.dispatch_stateless(
            &inbound,
            &extension_tasks_get_request(serde_json::json!({})),
        ))
        .expect("modern extension request must have a response");
        assert_eq!(admitted.result, Some(serde_json::json!({ "next": 42 })));
        assert!(admitted.error.is_none());

        let negotiated = server
            .negotiate_extensions(
                &final_client_extension_discovery(&extension_tasks_get_request(serde_json::json!(
                    {}
                )))
                .expect("extension settings must decode"),
            )
            .expect("extension settings must negotiate");
        assert_eq!(
            server
                .dispatch_negotiated_extension(
                    &inbound.request_context(),
                    &negotiated,
                    &extension_tasks_get_request(serde_json::json!({})),
                )
                .expect("public negotiated extension dispatch must admit exact modern metadata"),
            serde_json::json!({ "next": 42 })
        );

        let mut rejected = extension_tasks_get_request(serde_json::json!({}));
        *rejected
            .params
            .as_mut()
            .and_then(|value| {
                value.pointer_mut(
                    "/_meta/io.modelcontextprotocol~1clientCapabilities/extensions/io.modelcontextprotocol~1tasks",
                )
            })
            .expect("test request must contain its extension settings") =
            serde_json::json!({ "unexpected": true });
        let rejected = block_on(server.dispatch_stateless(&inbound, &rejected))
            .expect("rejected extension request must have an error response");
        let error = rejected
            .error
            .expect("incompatible extension settings must fail closed");
        assert_eq!(error.code, i32::from(McpErrorCode::InvalidParams).into());
        assert_eq!(calls.load(Ordering::SeqCst), 2);
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn modern_extension_fallback_rejects_wrong_protocol_metadata_before_invocation() {
        let calls = Arc::new(AtomicUsize::new(0));
        let server = extension_registry_test_server(Arc::clone(&calls));
        let inbound =
            InboundRequestContext::new(Cx::for_testing(), 71, InboundRequestTransport::Memory);

        let admitted = block_on(server.dispatch_stateless(
            &inbound,
            &extension_tasks_get_request(serde_json::json!({})),
        ))
        .expect("modern extension request must have a response");
        assert!(admitted.error.is_none());

        let negotiated = server
            .negotiate_extensions(
                &final_client_extension_discovery(&extension_tasks_get_request(serde_json::json!(
                    {}
                )))
                .expect("extension settings must decode"),
            )
            .expect("extension settings must negotiate");

        let mut rejected = extension_tasks_get_request(serde_json::json!({}));
        *rejected
            .params
            .as_mut()
            .and_then(|value| value.pointer_mut("/_meta/io.modelcontextprotocol~1protocolVersion"))
            .expect("test request must contain its protocol version") =
            serde_json::json!(LEGACY_PROTOCOL_VERSION);
        let rejected = block_on(server.dispatch_stateless(&inbound, &rejected))
            .expect("wrong-era extension request must have an error response");
        assert_eq!(
            rejected.error.map(|error| error.code),
            Some(i32::from(McpErrorCode::InvalidRequest).into())
        );
        let mut public_rejected = extension_tasks_get_request(serde_json::json!({}));
        *public_rejected
            .params
            .as_mut()
            .and_then(|value| value.pointer_mut("/_meta/io.modelcontextprotocol~1protocolVersion"))
            .expect("test request must contain its protocol version") =
            serde_json::json!(LEGACY_PROTOCOL_VERSION);
        assert_eq!(
            server
                .dispatch_negotiated_extension(
                    &inbound.request_context(),
                    &negotiated,
                    &public_rejected,
                )
                .expect_err("public extension dispatch must reject the changed era metadata")
                .code,
            McpErrorCode::InvalidRequest
        );
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn final_core_middleware_short_circuit_cannot_bypass_request_admission() {
        struct ShortCircuitMiddleware;

        impl Middleware for ShortCircuitMiddleware {
            fn on_request(
                &self,
                _ctx: &McpContext,
                _request: &JsonRpcRequest,
            ) -> McpResult<MiddlewareDecision> {
                Ok(MiddlewareDecision::Respond(serde_json::json!({})))
            }
        }

        let server = Server::new("final-core-short-circuit", "1.0.0")
            .middleware(ShortCircuitMiddleware)
            .build();
        let inbound =
            InboundRequestContext::new(Cx::for_testing(), 72, InboundRequestTransport::Memory);
        let request = JsonRpcRequest::new("tools/list", Some(serde_json::json!({})), 72_i64);

        let response = block_on(server.dispatch_stateless(&inbound, &request))
            .expect("a malformed final request with an id receives an error response");
        assert_eq!(
            response.error.map(|error| error.code),
            Some(i32::from(McpErrorCode::InvalidParams).into())
        );
        assert!(response.result.is_none());
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn final_core_middleware_short_circuit_cannot_author_metadata() {
        struct ShortCircuitMiddleware;

        impl Middleware for ShortCircuitMiddleware {
            fn on_request(
                &self,
                _ctx: &McpContext,
                _request: &JsonRpcRequest,
            ) -> McpResult<MiddlewareDecision> {
                Ok(MiddlewareDecision::Respond(serde_json::json!({
                    "resultType": "complete",
                    "tools": [],
                    "ttlMs": 0,
                    "cacheScope": "private",
                    "_meta": {
                        "io.modelcontextprotocol/serverInfo": {
                            "name": "middleware",
                            "version": "1.0.0",
                        },
                    },
                })))
            }
        }

        let server = Server::new("final-core-short-circuit", "1.0.0")
            .middleware(ShortCircuitMiddleware)
            .build();
        let inbound =
            InboundRequestContext::new(Cx::for_testing(), 721, InboundRequestTransport::Memory);
        let request = JsonRpcRequest::new(
            "tools/list",
            Some(serde_json::json!({
                "_meta": {
                    "io.modelcontextprotocol/protocolVersion": MODERN_PROTOCOL_VERSION,
                    "io.modelcontextprotocol/clientCapabilities": {},
                },
            })),
            721_i64,
        );

        let response = block_on(server.dispatch_stateless(&inbound, &request))
            .expect("short-circuited final request receives an error response");
        assert_eq!(
            response.error.map(|error| error.code),
            Some(i32::from(McpErrorCode::InternalError).into())
        );
        assert!(response.result.is_none());
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn final_core_middleware_rejects_one_field_result_type_mutation() {
        struct ResultTypeMutationMiddleware;

        impl Middleware for ResultTypeMutationMiddleware {
            fn on_response(
                &self,
                _ctx: &McpContext,
                _request: &JsonRpcRequest,
                mut response: serde_json::Value,
            ) -> McpResult<serde_json::Value> {
                assert_eq!(response["resultType"], "complete");
                response["resultType"] = serde_json::json!("input_required");
                Ok(response)
            }
        }

        let server = Server::new("final-core-result-type", "1.0.0")
            .middleware(ResultTypeMutationMiddleware)
            .build();
        let inbound =
            InboundRequestContext::new(Cx::for_testing(), 73, InboundRequestTransport::Memory);
        let request = JsonRpcRequest::new(
            "tools/list",
            Some(serde_json::json!({
                "_meta": {
                    "io.modelcontextprotocol/protocolVersion": MODERN_PROTOCOL_VERSION,
                    "io.modelcontextprotocol/clientCapabilities": {},
                },
            })),
            73_i64,
        );

        let response = block_on(server.dispatch_stateless(&inbound, &request))
            .expect("a malformed middleware result with an id receives an error response");
        assert_eq!(
            response.error.map(|error| error.code),
            Some(i32::from(McpErrorCode::InternalError).into())
        );
        assert!(response.result.is_none());
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn final_core_middleware_preserves_open_response_metadata() {
        struct OpenMetadataMiddleware;

        impl Middleware for OpenMetadataMiddleware {
            fn on_response(
                &self,
                _ctx: &McpContext,
                _request: &JsonRpcRequest,
                mut response: serde_json::Value,
            ) -> McpResult<serde_json::Value> {
                response["_meta"]["com.example/trace"] = serde_json::json!("retained");
                Ok(response)
            }
        }

        let server = Server::new("final-core-open-metadata", "1.0.0")
            .middleware(OpenMetadataMiddleware)
            .build();
        let inbound =
            InboundRequestContext::new(Cx::for_testing(), 74, InboundRequestTransport::Memory);
        let request = JsonRpcRequest::new(
            "tools/list",
            Some(serde_json::json!({
                "_meta": {
                    "io.modelcontextprotocol/protocolVersion": MODERN_PROTOCOL_VERSION,
                    "io.modelcontextprotocol/clientCapabilities": {},
                },
            })),
            74_i64,
        );

        let response = block_on(server.dispatch_stateless(&inbound, &request))
            .expect("final request has a response");
        assert!(response.error.is_none());
        assert_eq!(
            response
                .result
                .as_ref()
                .and_then(|result| result.pointer("/_meta/com.example~1trace")),
            Some(&serde_json::json!("retained")),
            "middleware may still add open metadata"
        );
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn final_core_middleware_rejects_one_field_server_info_injection() {
        struct ServerInfoInjectionMiddleware;

        impl Middleware for ServerInfoInjectionMiddleware {
            fn on_response(
                &self,
                _ctx: &McpContext,
                _request: &JsonRpcRequest,
                mut response: serde_json::Value,
            ) -> McpResult<serde_json::Value> {
                response["_meta"][FINAL_SERVER_INFO_META_KEY] = serde_json::json!({
                    "name": "middleware",
                    "version": "1.0.0",
                });
                Ok(response)
            }
        }

        let server = Server::new("final-core-server-info", "1.0.0")
            .middleware(ServerInfoInjectionMiddleware)
            .build();
        let inbound =
            InboundRequestContext::new(Cx::for_testing(), 75, InboundRequestTransport::Memory);
        let request = JsonRpcRequest::new(
            "tools/list",
            Some(serde_json::json!({
                "_meta": {
                    "io.modelcontextprotocol/protocolVersion": MODERN_PROTOCOL_VERSION,
                    "io.modelcontextprotocol/clientCapabilities": {},
                },
            })),
            75_i64,
        );

        let response = block_on(server.dispatch_stateless(&inbound, &request))
            .expect("sealed metadata mutation receives an error response");
        assert_eq!(
            response.error.map(|error| error.code),
            Some(i32::from(McpErrorCode::InternalError).into())
        );
        assert!(response.result.is_none());
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn final_discovery_middleware_rejects_one_field_server_info_mutation() {
        struct DiscoveryServerInfoMutationMiddleware;

        impl Middleware for DiscoveryServerInfoMutationMiddleware {
            fn on_response(
                &self,
                _ctx: &McpContext,
                _request: &JsonRpcRequest,
                mut response: serde_json::Value,
            ) -> McpResult<serde_json::Value> {
                response["_meta"][FINAL_SERVER_INFO_META_KEY]["name"] =
                    serde_json::json!("middleware");
                Ok(response)
            }
        }

        let server = Server::new("final-discovery-server-info", "1.0.0")
            .middleware(DiscoveryServerInfoMutationMiddleware)
            .build();
        let inbound =
            InboundRequestContext::new(Cx::for_testing(), 76, InboundRequestTransport::Memory);
        let request = JsonRpcRequest::new(
            SERVER_DISCOVER_METHOD,
            Some(serde_json::json!({
                "_meta": {
                    "io.modelcontextprotocol/protocolVersion": MODERN_PROTOCOL_VERSION,
                    "io.modelcontextprotocol/clientCapabilities": {},
                },
            })),
            76_i64,
        );

        let response = block_on(server.dispatch_stateless(&inbound, &request))
            .expect("sealed discovery mutation receives an error response");
        assert_eq!(
            response.error.map(|error| error.code),
            Some(i32::from(McpErrorCode::InternalError).into())
        );
        assert!(response.result.is_none());
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn legacy_middleware_retains_open_result_metadata() {
        struct LegacyMetadataMiddleware;

        impl Middleware for LegacyMetadataMiddleware {
            fn on_response(
                &self,
                _ctx: &McpContext,
                _request: &JsonRpcRequest,
                mut response: serde_json::Value,
            ) -> McpResult<serde_json::Value> {
                response["_meta"][FINAL_SERVER_INFO_META_KEY] = serde_json::json!({
                    "name": "middleware",
                    "version": "1.0.0",
                });
                Ok(response)
            }
        }

        let server = Server::new("legacy-open-result-metadata", "1.0.0")
            .middleware(LegacyMetadataMiddleware)
            .build();
        let mut session = initialized_test_session(&server);

        let response = dispatch_test_request(&server, &mut session, "tools/list");
        assert!(response.error.is_none());
        assert_eq!(
            response
                .result
                .as_ref()
                .and_then(|result| result.pointer("/_meta/io.modelcontextprotocol~1serverInfo")),
            Some(&serde_json::json!({
                "name": "middleware",
                "version": "1.0.0",
            })),
            "the exact legacy result metadata surface remains open to middleware"
        );
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn legacy_dispatch_does_not_fall_through_to_extension_registry() {
        let calls = Arc::new(AtomicUsize::new(0));
        let server = extension_registry_test_server(Arc::clone(&calls));
        let mut session = initialized_test_session(&server);
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();

        let response = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            JsonRpcRequest::new(
                "tasks/get",
                Some(serde_json::json!({ "value": 41 })),
                71_i64,
            ),
            &notification_sender,
            &request_sender,
        ))
        .expect("legacy request must have a response");
        let error = response
            .error
            .expect("legacy request must not reach the extension handler");
        assert_eq!(error.code, i32::from(McpErrorCode::MethodNotFound).into());
        assert_eq!(calls.load(Ordering::SeqCst), 0);
    }

    #[cfg(feature = "tasks")]
    #[derive(Default)]
    struct ServerFinalTaskState {
        tasks: std::collections::BTreeMap<fastmcp_protocol::FinalTaskId, fastmcp_protocol::Task>,
        generations: std::collections::BTreeMap<fastmcp_protocol::FinalTaskId, u64>,
        next_generation: u64,
        next_dispatch_fence: u64,
        work_descriptors:
            std::collections::BTreeMap<fastmcp_protocol::FinalTaskId, FinalTaskWorkDescriptor>,
        initial_work:
            std::collections::BTreeMap<fastmcp_protocol::FinalTaskId, FinalTaskWorkDescriptor>,
        accepted_inputs: std::collections::BTreeMap<
            fastmcp_protocol::FinalTaskId,
            fastmcp_protocol::TaskInputResponses,
        >,
        handoff_leases:
            std::collections::BTreeMap<fastmcp_protocol::FinalTaskId, ServerFinalTaskHandoffLease>,
        cancellation_requests: std::collections::BTreeSet<fastmcp_protocol::FinalTaskId>,
        notifications: Vec<fastmcp_protocol::TaskStatusNotification>,
        expires_at: std::collections::BTreeMap<fastmcp_protocol::FinalTaskId, Instant>,
        execution_budgets: std::collections::BTreeMap<
            fastmcp_protocol::FinalTaskId,
            crate::tasks::FinalTaskExecutionBudget,
        >,
    }

    #[cfg(feature = "tasks")]
    #[derive(Clone, Copy, PartialEq, Eq)]
    enum ServerFinalTaskHandoffKind {
        Initial,
        Resumed,
    }

    #[cfg(feature = "tasks")]
    struct ServerFinalTaskHandoffLease {
        generation: u64,
        kind: ServerFinalTaskHandoffKind,
        owner_id: String,
        dispatch_fence: Option<u64>,
        expires_at: Instant,
    }

    #[cfg(feature = "tasks")]
    const SERVER_FINAL_TASK_HANDOFF_LEASE: Duration = Duration::from_secs(30);
    #[cfg(feature = "tasks")]
    const SERVER_FINAL_TASK_HANDOFF_HEARTBEAT: Duration = Duration::from_secs(10);

    #[cfg(feature = "tasks")]
    struct ServerFinalTaskStore {
        clock: Arc<dyn Fn() -> Instant + Send + Sync>,
        execution_limits: crate::tasks::FinalTaskExecutionLimits,
        state: Mutex<ServerFinalTaskState>,
    }

    #[cfg(feature = "tasks")]
    impl Default for ServerFinalTaskStore {
        fn default() -> Self {
            Self::with_clock(Arc::new(Instant::now))
        }
    }

    #[cfg(feature = "tasks")]
    impl ServerFinalTaskStore {
        fn with_clock(clock: Arc<dyn Fn() -> Instant + Send + Sync>) -> Self {
            Self {
                clock,
                execution_limits: crate::tasks::FinalTaskExecutionLimits::default(),
                state: Mutex::new(ServerFinalTaskState::default()),
            }
        }

        fn now(&self) -> Instant {
            (self.clock)()
        }
    }

    #[cfg(feature = "tasks")]
    fn next_server_final_task_generation(state: &mut ServerFinalTaskState) -> McpResult<u64> {
        let generation = state.next_generation.checked_add(1).ok_or_else(|| {
            McpError::internal_error("Server final task test-store generation space is exhausted")
        })?;
        state.next_generation = generation;
        Ok(generation)
    }

    #[cfg(feature = "tasks")]
    fn next_server_final_task_dispatch_fence(state: &mut ServerFinalTaskState) -> McpResult<u64> {
        let fence = state.next_dispatch_fence.checked_add(1).ok_or_else(|| {
            McpError::internal_error(
                "Server final task test-store dispatch fence space is exhausted",
            )
        })?;
        state.next_dispatch_fence = fence;
        Ok(fence)
    }

    #[cfg(feature = "tasks")]
    fn server_final_task_handoff_expiry(now: Instant) -> McpResult<Instant> {
        now.checked_add(SERVER_FINAL_TASK_HANDOFF_LEASE)
            .ok_or_else(|| {
                McpError::internal_error(
                    "Server final task test-store handoff lease exceeds clock range",
                )
            })
    }

    /// Validates every unbounded wire duration before a store operation may
    /// reclaim, replace, or otherwise mutate retained state. The returned TTL
    /// is the one bounded duration that the store needs for its expiry index.
    #[cfg(feature = "tasks")]
    fn validate_server_final_task_durations(
        task: &fastmcp_protocol::Task,
    ) -> McpResult<Option<u64>> {
        let ttl_ms = task
            .base()
            .ttl_ms
            .as_ref()
            .map(fastmcp_protocol::TaskDuration::try_as_millis)
            .transpose()
            .map_err(|_| {
                McpError::invalid_params(
                    "Server final task test-store ttlMs is outside milliseconds",
                )
            })?;
        task.base()
            .poll_interval_ms
            .as_ref()
            .map(fastmcp_protocol::TaskDuration::try_as_millis)
            .transpose()
            .map_err(|_| {
                McpError::invalid_params(
                    "Server final task test-store pollIntervalMs is outside milliseconds",
                )
            })?;
        Ok(ttl_ms)
    }

    #[cfg(feature = "tasks")]
    fn server_final_task_expiry(ttl_ms: Option<u64>, now: Instant) -> McpResult<Option<Instant>> {
        let Some(ttl_ms) = ttl_ms else {
            return Ok(None);
        };
        now.checked_add(Duration::from_millis(ttl_ms))
            .map(Some)
            .ok_or_else(|| {
                McpError::internal_error("Server final task test-store TTL exceeds clock range")
            })
    }

    #[cfg(feature = "tasks")]
    fn new_server_final_task_execution_budget(
        limits: crate::tasks::FinalTaskExecutionLimits,
        now: Instant,
    ) -> McpResult<crate::tasks::FinalTaskExecutionBudget> {
        let total_deadline = now.checked_add(limits.total_runtime()).ok_or_else(|| {
            McpError::internal_error("Server final task execution exceeds clock range")
        })?;
        crate::tasks::FinalTaskExecutionBudget::new(total_deadline, None, 0, limits)
    }

    #[cfg(feature = "tasks")]
    fn server_final_task_execution_exhaustion(
        state: &ServerFinalTaskState,
        task_id: &fastmcp_protocol::FinalTaskId,
        now: Instant,
    ) -> McpResult<Option<&'static str>> {
        let Some(task) = state.tasks.get(task_id) else {
            return Ok(None);
        };
        if !matches!(
            task,
            fastmcp_protocol::Task::Working(_) | fastmcp_protocol::Task::InputRequired { .. }
        ) {
            return Ok(None);
        }
        let budget = state.execution_budgets.get(task_id).ok_or_else(|| {
            McpError::internal_error("Server final task is missing execution accounting")
        })?;
        if now >= budget.total_deadline() {
            return Ok(Some("Task total execution deadline exceeded"));
        }
        if budget
            .attempt_deadline()
            .is_some_and(|deadline| now >= deadline)
        {
            return Ok(Some("Task attempt execution deadline exceeded"));
        }
        if budget.attempts() == budget.limits().max_attempts()
            && !state.handoff_leases.contains_key(task_id)
            && matches!(task, fastmcp_protocol::Task::Working(_))
            && (state.initial_work.contains_key(task_id)
                || state.accepted_inputs.contains_key(task_id))
        {
            return Ok(Some("Task execution attempt limit exceeded"));
        }
        Ok(None)
    }

    #[cfg(feature = "tasks")]
    fn released_server_final_task_execution_budget(
        state: &ServerFinalTaskState,
        task_id: &fastmcp_protocol::FinalTaskId,
    ) -> McpResult<crate::tasks::FinalTaskExecutionBudget> {
        let budget = state.execution_budgets.get(task_id).ok_or_else(|| {
            McpError::internal_error("Server final task is missing execution accounting")
        })?;
        crate::tasks::FinalTaskExecutionBudget::new(
            budget.total_deadline(),
            None,
            budget.attempts(),
            budget.limits(),
        )
    }

    #[cfg(feature = "tasks")]
    fn prepare_server_final_task_execution_release(
        state: &ServerFinalTaskState,
        task_id: &fastmcp_protocol::FinalTaskId,
        now: Instant,
    ) -> McpResult<crate::tasks::FinalTaskExecutionBudget> {
        if let Some(reason) = server_final_task_execution_exhaustion(state, task_id, now)? {
            return Err(McpError::invalid_params(reason));
        }
        released_server_final_task_execution_budget(state, task_id)
    }

    #[cfg(feature = "tasks")]
    fn server_final_task_is_working(
        state: &ServerFinalTaskState,
        task_id: &fastmcp_protocol::FinalTaskId,
        generation: u64,
    ) -> bool {
        state.generations.get(task_id) == Some(&generation)
            && state
                .tasks
                .get(task_id)
                .is_some_and(|task| matches!(task, fastmcp_protocol::Task::Working(_)))
            && !state.cancellation_requests.contains(task_id)
    }

    /// Retires durable cancellation intent after its elected service lease
    /// expires. This test-store transition mirrors the production in-memory
    /// store: it must not drop the only retirement fence and leave a working
    /// task with cancellation intent.
    #[cfg(feature = "tasks")]
    fn terminalize_expired_server_final_task_cancellation(
        state: &mut ServerFinalTaskState,
        task_id: &fastmcp_protocol::FinalTaskId,
    ) -> McpResult<()> {
        let Some(fastmcp_protocol::Task::Working(base)) = state.tasks.get(task_id).cloned() else {
            return Err(McpError::internal_error(
                "Expired cancellation lease no longer owns a working server final task",
            ));
        };
        let task =
            fastmcp_protocol::Task::Cancelled(crate::tasks::transition_terminal_final_task_base(
                base,
                fastmcp_protocol::FinalTaskStatus::Cancelled,
                None,
            )?);
        let notification = crate::tasks::final_task_notification(&task);
        let execution_budget = released_server_final_task_execution_budget(state, task_id)?;
        let generation = next_server_final_task_generation(state)?;
        state.tasks.insert(task_id.clone(), task);
        state.generations.insert(task_id.clone(), generation);
        state
            .execution_budgets
            .insert(task_id.clone(), execution_budget);
        state.accepted_inputs.remove(task_id);
        state.initial_work.remove(task_id);
        state.handoff_leases.remove(task_id);
        state.cancellation_requests.remove(task_id);
        state.notifications.push(notification);
        Ok(())
    }

    #[cfg(feature = "tasks")]
    fn reclaim_expired_server_final_task_handoffs(state: &mut ServerFinalTaskState, now: Instant) {
        let expired = state
            .handoff_leases
            .iter()
            .filter(|(_, lease)| lease.expires_at <= now)
            .map(|(task_id, _)| task_id.clone())
            .collect::<Vec<_>>();
        for task_id in expired {
            // Expired execution retains its exact fence until the explicit
            // expiry operation commits a failure and matching notification.
            if !matches!(
                server_final_task_execution_exhaustion(state, &task_id, now),
                Ok(None)
            ) {
                continue;
            }
            let Some(lease_generation) = state
                .handoff_leases
                .get(&task_id)
                .map(|lease| lease.generation)
            else {
                continue;
            };
            let cancellation_requires_retirement = state.cancellation_requests.contains(&task_id)
                && state
                    .tasks
                    .get(&task_id)
                    .is_some_and(|task| matches!(task, fastmcp_protocol::Task::Working(_)));
            if cancellation_requires_retirement {
                // If checked terminalization cannot allocate a generation,
                // retain this exact lease as the cancellation-retirement
                // fence. Releasing it would strand working+cancellation.
                let _ = terminalize_expired_server_final_task_cancellation(state, &task_id);
                continue;
            }
            let recoverable = server_final_task_is_working(state, &task_id, lease_generation);
            if recoverable {
                let Ok(execution_budget) =
                    released_server_final_task_execution_budget(state, &task_id)
                else {
                    continue;
                };
                if let Ok(generation) = next_server_final_task_generation(state) {
                    state.handoff_leases.remove(&task_id);
                    state
                        .execution_budgets
                        .insert(task_id.clone(), execution_budget);
                    state.generations.insert(task_id, generation);
                }
            } else {
                state.handoff_leases.remove(&task_id);
            }
        }

        let expired_task_ids = state
            .expires_at
            .iter()
            .filter(|(_, expires_at)| **expires_at <= now)
            .map(|(task_id, _)| task_id.clone())
            .collect::<Vec<_>>();
        for task_id in expired_task_ids {
            state.expires_at.remove(&task_id);
            state.execution_budgets.remove(&task_id);
            state.tasks.remove(&task_id);
            state.generations.remove(&task_id);
            state.work_descriptors.remove(&task_id);
            state.initial_work.remove(&task_id);
            state.accepted_inputs.remove(&task_id);
            state.handoff_leases.remove(&task_id);
            state.cancellation_requests.remove(&task_id);
            state
                .notifications
                .retain(|notification| notification.params.task.base().task_id != task_id);
        }
    }

    #[cfg(feature = "tasks")]
    fn insert_server_final_task_handoff_lease(
        state: &mut ServerFinalTaskState,
        task_id: fastmcp_protocol::FinalTaskId,
        generation: u64,
        kind: ServerFinalTaskHandoffKind,
        owner_id: &str,
        now: Instant,
    ) -> McpResult<()> {
        if let Some(reason) = server_final_task_execution_exhaustion(state, &task_id, now)? {
            return Err(McpError::invalid_params(reason));
        }
        let expires_at = server_final_task_handoff_expiry(now)?;
        if state.handoff_leases.contains_key(&task_id) {
            return Err(McpError::internal_error(
                "Server final task test-store overwrote a live handoff lease",
            ));
        }
        let budget = state.execution_budgets.get(&task_id).ok_or_else(|| {
            McpError::internal_error("Server final task is missing execution accounting")
        })?;
        let attempts = budget
            .attempts()
            .checked_add(1)
            .filter(|attempts| *attempts <= budget.limits().max_attempts())
            .ok_or_else(|| McpError::invalid_params("Task execution attempt limit exceeded"))?;
        let attempt_deadline = now
            .checked_add(budget.limits().attempt_runtime())
            .ok_or_else(|| {
                McpError::internal_error("Server final task attempt exceeds clock range")
            })?
            .min(budget.total_deadline());
        let execution_budget = crate::tasks::FinalTaskExecutionBudget::new(
            budget.total_deadline(),
            Some(attempt_deadline),
            attempts,
            budget.limits(),
        )?;
        state
            .execution_budgets
            .insert(task_id.clone(), execution_budget);
        state.handoff_leases.insert(
            task_id,
            ServerFinalTaskHandoffLease {
                generation,
                kind,
                owner_id: owner_id.to_owned(),
                dispatch_fence: None,
                expires_at,
            },
        );
        Ok(())
    }

    #[cfg(feature = "tasks")]
    fn next_server_final_task_recovery_id<'a>(
        task_ids: impl Iterator<Item = &'a fastmcp_protocol::FinalTaskId>,
        after_task_id: Option<&fastmcp_protocol::FinalTaskId>,
        mut eligible: impl FnMut(&fastmcp_protocol::FinalTaskId) -> McpResult<bool>,
    ) -> McpResult<Option<fastmcp_protocol::FinalTaskId>> {
        let task_ids = task_ids.collect::<Vec<_>>();
        for task_id in task_ids.iter().copied() {
            if after_task_id.is_none_or(|after| task_id > after) && eligible(task_id)? {
                return Ok(Some(task_id.clone()));
            }
        }
        for task_id in task_ids {
            if after_task_id.is_some_and(|after| task_id <= after) && eligible(task_id)? {
                return Ok(Some(task_id.clone()));
            }
        }
        Ok(None)
    }

    #[cfg(feature = "tasks")]
    fn record_server_final_task_cancellation(
        state: &mut ServerFinalTaskState,
        task_id: &fastmcp_protocol::FinalTaskId,
        now: Instant,
    ) -> McpResult<()> {
        let execution_budget = prepare_server_final_task_execution_release(state, task_id, now)?;
        let generation = state.generations.get(task_id).copied().ok_or_else(|| {
            McpError::internal_error("Server final task test-store is missing a task generation")
        })?;
        let dispatch_elected = state
            .handoff_leases
            .get(task_id)
            .is_some_and(|lease| lease.generation == generation && lease.dispatch_fence.is_some());
        let next_generation = (!dispatch_elected && !state.cancellation_requests.contains(task_id))
            .then(|| next_server_final_task_generation(state))
            .transpose()?;
        state.accepted_inputs.remove(task_id);
        state.initial_work.remove(task_id);
        if !dispatch_elected {
            state.handoff_leases.remove(task_id);
            state
                .execution_budgets
                .insert(task_id.clone(), execution_budget);
        }
        state.cancellation_requests.insert(task_id.clone());
        if let Some(next_generation) = next_generation {
            state.generations.insert(task_id.clone(), next_generation);
        }
        Ok(())
    }

    #[cfg(feature = "tasks")]
    fn ensure_server_final_task_notification_matches_task(
        task: &fastmcp_protocol::Task,
        notification: &fastmcp_protocol::TaskStatusNotification,
    ) -> McpResult<()> {
        let retained_task = serde_json::to_value(task).map_err(|error| {
            McpError::internal_error(format!(
                "Could not encode retained final task for validation: {error}"
            ))
        })?;
        let notified_task = serde_json::to_value(&notification.params.task).map_err(|error| {
            McpError::internal_error(format!(
                "Could not encode final task notification for validation: {error}"
            ))
        })?;
        if notified_task != retained_task {
            return Err(McpError::invalid_params(
                "Final task notification must contain exactly the retained task",
            ));
        }
        Ok(())
    }

    #[cfg(feature = "tasks")]
    impl FinalTaskStore for ServerFinalTaskStore {
        fn execution_limits(&self) -> McpResult<crate::tasks::FinalTaskExecutionLimits> {
            Ok(self.execution_limits)
        }

        fn task_execution_budget_if_current(
            &self,
            expected: &FinalTaskSnapshot,
        ) -> McpResult<Option<crate::tasks::FinalTaskExecutionBudget>> {
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            reclaim_expired_server_final_task_handoffs(&mut state, self.now());
            let task_id = &expected.task().base().task_id;
            if state.generations.get(task_id) != Some(&expected.generation()) {
                return Ok(None);
            }
            state
                .execution_budgets
                .get(task_id)
                .copied()
                .map(Some)
                .ok_or_else(|| {
                    McpError::internal_error("Server final task is missing execution accounting")
                })
        }

        fn expire_task_execution_if_current(
            &self,
            expected: &FinalTaskSnapshot,
        ) -> McpResult<Option<FinalTaskSnapshot>> {
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let now = self.now();
            reclaim_expired_server_final_task_handoffs(&mut state, now);
            let task_id = &expected.task().base().task_id;
            if state.generations.get(task_id) != Some(&expected.generation()) {
                return Ok(None);
            }
            let Some(reason) = server_final_task_execution_exhaustion(&state, task_id, now)? else {
                return Ok(None);
            };
            let retained = state.tasks.get(task_id).ok_or_else(|| {
                McpError::internal_error("Server final task expiry lost its retained task")
            })?;
            let task = fastmcp_protocol::Task::Failed {
                base: crate::tasks::transition_terminal_final_task_base(
                    retained.base().clone(),
                    fastmcp_protocol::FinalTaskStatus::Failed,
                    None,
                )?,
                error: fastmcp_protocol::FinalTaskError {
                    code: (-32000).into(),
                    message: reason.to_owned(),
                    data: None,
                    additional: BTreeMap::new(),
                },
            };
            let notification = crate::tasks::final_task_notification(&task);
            let execution_budget = released_server_final_task_execution_budget(&state, task_id)?;
            let generation = next_server_final_task_generation(&mut state)?;
            state.tasks.insert(task_id.clone(), task.clone());
            state.generations.insert(task_id.clone(), generation);
            state
                .execution_budgets
                .insert(task_id.clone(), execution_budget);
            state.initial_work.remove(task_id);
            state.accepted_inputs.remove(task_id);
            state.handoff_leases.remove(task_id);
            state.cancellation_requests.remove(task_id);
            state.notifications.push(notification);
            Ok(Some(FinalTaskSnapshot::new(task, generation)))
        }

        fn next_expired_execution_snapshot(&self) -> McpResult<Option<FinalTaskSnapshot>> {
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let now = self.now();
            reclaim_expired_server_final_task_handoffs(&mut state, now);
            for (task_id, task) in &state.tasks {
                if server_final_task_execution_exhaustion(&state, task_id, now)?.is_some() {
                    let generation = state.generations.get(task_id).copied().ok_or_else(|| {
                        McpError::internal_error("Server final task expiry lost its generation")
                    })?;
                    return Ok(Some(FinalTaskSnapshot::new(task.clone(), generation)));
                }
            }
            Ok(None)
        }

        fn create_task(
            &self,
            task: fastmcp_protocol::Task,
            notification: fastmcp_protocol::TaskStatusNotification,
        ) -> McpResult<()> {
            let task_id = task.base().task_id.clone();
            let ttl_ms = validate_server_final_task_durations(&task)?;
            ensure_server_final_task_notification_matches_task(&task, &notification)?;
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let now = self.now();
            let expires_at = server_final_task_expiry(ttl_ms, now)?;
            let execution_budget =
                new_server_final_task_execution_budget(self.execution_limits, now)?;
            reclaim_expired_server_final_task_handoffs(&mut state, now);
            if state.tasks.contains_key(&task_id) {
                return Err(McpError::invalid_params("Task already exists"));
            }
            let generation = next_server_final_task_generation(&mut state)?;
            state.tasks.insert(task_id.clone(), task);
            state.generations.insert(task_id.clone(), generation);
            state
                .execution_budgets
                .insert(task_id.clone(), execution_budget);
            state.notifications.push(notification);
            if let Some(expires_at) = expires_at {
                state.expires_at.insert(task_id, expires_at);
            }
            Ok(())
        }

        fn create_task_with_work(
            &self,
            task: fastmcp_protocol::Task,
            notification: fastmcp_protocol::TaskStatusNotification,
            work_descriptor: FinalTaskWorkDescriptor,
        ) -> McpResult<FinalTaskSnapshot> {
            let task_id = task.base().task_id.clone();
            let ttl_ms = validate_server_final_task_durations(&task)?;
            ensure_server_final_task_notification_matches_task(&task, &notification)?;
            if !matches!(task, fastmcp_protocol::Task::Working(_)) {
                return Err(McpError::invalid_params(
                    "Initial application work requires a working final task",
                ));
            }
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let now = self.now();
            let expires_at = server_final_task_expiry(ttl_ms, now)?;
            let execution_budget =
                new_server_final_task_execution_budget(self.execution_limits, now)?;
            reclaim_expired_server_final_task_handoffs(&mut state, now);
            if state.tasks.contains_key(&task_id) {
                return Err(McpError::invalid_params("Task already exists"));
            }
            let generation = next_server_final_task_generation(&mut state)?;
            state.tasks.insert(task_id.clone(), task);
            state.generations.insert(task_id.clone(), generation);
            state
                .execution_budgets
                .insert(task_id.clone(), execution_budget);
            state
                .work_descriptors
                .insert(task_id.clone(), work_descriptor.clone());
            state.initial_work.insert(task_id.clone(), work_descriptor);
            state.notifications.push(notification);
            let committed = FinalTaskSnapshot::new(state.tasks[&task_id].clone(), generation);
            if let Some(expires_at) = expires_at {
                state.expires_at.insert(task_id, expires_at);
            }
            Ok(committed)
        }

        fn get_task(
            &self,
            task_id: &fastmcp_protocol::FinalTaskId,
        ) -> McpResult<Option<fastmcp_protocol::Task>> {
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            reclaim_expired_server_final_task_handoffs(&mut state, self.now());
            Ok(state.tasks.get(task_id).cloned())
        }

        fn get_task_snapshot(
            &self,
            task_id: &fastmcp_protocol::FinalTaskId,
        ) -> McpResult<Option<FinalTaskSnapshot>> {
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            reclaim_expired_server_final_task_handoffs(&mut state, self.now());
            let Some(task) = state.tasks.get(task_id).cloned() else {
                return Ok(None);
            };
            let generation = state.generations.get(task_id).copied().ok_or_else(|| {
                McpError::internal_error("Server final task test store is missing a generation")
            })?;
            Ok(Some(FinalTaskSnapshot::new(task, generation)))
        }

        fn replace_task(
            &self,
            task: fastmcp_protocol::Task,
            notification: fastmcp_protocol::TaskStatusNotification,
        ) -> McpResult<()> {
            let task_id = task.base().task_id.clone();
            validate_server_final_task_durations(&task)?;
            ensure_server_final_task_notification_matches_task(&task, &notification)?;
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let now = self.now();
            reclaim_expired_server_final_task_handoffs(&mut state, now);
            if !state.tasks.contains_key(&task_id) {
                return Err(McpError::invalid_params("Task not found"));
            }
            let execution_budget =
                prepare_server_final_task_execution_release(&state, &task_id, now)?;
            let generation = next_server_final_task_generation(&mut state)?;
            let terminal = matches!(
                &task,
                fastmcp_protocol::Task::Completed { .. }
                    | fastmcp_protocol::Task::Failed { .. }
                    | fastmcp_protocol::Task::Cancelled(_)
            );
            state.tasks.insert(task_id.clone(), task);
            state.generations.insert(task_id.clone(), generation);
            state
                .execution_budgets
                .insert(task_id.clone(), execution_budget);
            state.accepted_inputs.remove(&task_id);
            state.handoff_leases.remove(&task_id);
            state.initial_work.remove(&task_id);
            state.notifications.push(notification);
            if terminal {
                state.cancellation_requests.remove(&task_id);
            }
            Ok(())
        }

        fn replace_task_if_current(
            &self,
            expected: &FinalTaskSnapshot,
            task: fastmcp_protocol::Task,
            notification: fastmcp_protocol::TaskStatusNotification,
        ) -> McpResult<bool> {
            let task_id = task.base().task_id.clone();
            if expected.task().base().task_id != task_id {
                return Err(McpError::invalid_params(
                    "Expected and replacement final task IDs must match",
                ));
            }
            validate_server_final_task_durations(&task)?;
            ensure_server_final_task_notification_matches_task(&task, &notification)?;
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let now = self.now();
            reclaim_expired_server_final_task_handoffs(&mut state, now);
            if state.generations.get(&task_id) != Some(&expected.generation()) {
                return Ok(false);
            }
            let execution_budget =
                prepare_server_final_task_execution_release(&state, &task_id, now)?;
            let generation = next_server_final_task_generation(&mut state)?;
            let terminal = matches!(
                &task,
                fastmcp_protocol::Task::Completed { .. }
                    | fastmcp_protocol::Task::Failed { .. }
                    | fastmcp_protocol::Task::Cancelled(_)
            );
            state.tasks.insert(task_id.clone(), task);
            state.generations.insert(task_id.clone(), generation);
            state
                .execution_budgets
                .insert(task_id.clone(), execution_budget);
            state.accepted_inputs.remove(&task_id);
            state.handoff_leases.remove(&task_id);
            state.initial_work.remove(&task_id);
            state.notifications.push(notification);
            if terminal {
                state.cancellation_requests.remove(&task_id);
            }
            Ok(true)
        }

        fn replace_task_and_append_input_if_current(
            &self,
            expected: &FinalTaskSnapshot,
            task: fastmcp_protocol::Task,
            notification: fastmcp_protocol::TaskStatusNotification,
            input_responses: fastmcp_protocol::TaskInputResponses,
        ) -> McpResult<Option<FinalTaskSnapshot>> {
            let task_id = task.base().task_id.clone();
            if expected.task().base().task_id != task_id {
                return Err(McpError::invalid_params(
                    "Expected and replacement final task IDs must match",
                ));
            }
            validate_server_final_task_durations(&task)?;
            ensure_server_final_task_notification_matches_task(&task, &notification)?;
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let now = self.now();
            reclaim_expired_server_final_task_handoffs(&mut state, now);
            if state.generations.get(&task_id) != Some(&expected.generation()) {
                return Ok(None);
            }
            let execution_budget =
                prepare_server_final_task_execution_release(&state, &task_id, now)?;
            let generation = next_server_final_task_generation(&mut state)?;
            state.tasks.insert(task_id.clone(), task);
            state.generations.insert(task_id.clone(), generation);
            state
                .execution_budgets
                .insert(task_id.clone(), execution_budget);
            state.handoff_leases.remove(&task_id);
            state.initial_work.remove(&task_id);
            let committed = FinalTaskSnapshot::new(state.tasks[&task_id].clone(), generation);
            if !input_responses.is_empty() {
                state
                    .accepted_inputs
                    .entry(task_id)
                    .or_default()
                    .extend(input_responses);
            }
            state.notifications.push(notification);
            Ok(Some(committed))
        }

        fn replace_task_and_clear_input_if_current(
            &self,
            expected: &FinalTaskSnapshot,
            task: fastmcp_protocol::Task,
            notification: fastmcp_protocol::TaskStatusNotification,
        ) -> McpResult<Option<FinalTaskSnapshot>> {
            let task_id = task.base().task_id.clone();
            if expected.task().base().task_id != task_id {
                return Err(McpError::invalid_params(
                    "Expected and replacement final task IDs must match",
                ));
            }
            validate_server_final_task_durations(&task)?;
            ensure_server_final_task_notification_matches_task(&task, &notification)?;
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let now = self.now();
            reclaim_expired_server_final_task_handoffs(&mut state, now);
            if state.generations.get(&task_id) != Some(&expected.generation()) {
                return Ok(None);
            }
            let execution_budget =
                prepare_server_final_task_execution_release(&state, &task_id, now)?;
            let generation = next_server_final_task_generation(&mut state)?;
            let terminal = matches!(
                &task,
                fastmcp_protocol::Task::Completed { .. }
                    | fastmcp_protocol::Task::Failed { .. }
                    | fastmcp_protocol::Task::Cancelled(_)
            );
            state.tasks.insert(task_id.clone(), task);
            state.generations.insert(task_id.clone(), generation);
            state
                .execution_budgets
                .insert(task_id.clone(), execution_budget);
            state.accepted_inputs.remove(&task_id);
            state.handoff_leases.remove(&task_id);
            state.initial_work.remove(&task_id);
            state.notifications.push(notification);
            if terminal {
                state.cancellation_requests.remove(&task_id);
            }
            Ok(Some(FinalTaskSnapshot::new(
                state.tasks[&task_id].clone(),
                generation,
            )))
        }

        fn replace_task_and_clear_input_for_handoff_if_current(
            &self,
            expected: &FinalTaskSnapshot,
            owner_id: &str,
            dispatch_fence: u64,
            cancellation_required: bool,
            task: fastmcp_protocol::Task,
            notification: fastmcp_protocol::TaskStatusNotification,
        ) -> McpResult<Option<FinalTaskSnapshot>> {
            if owner_id.is_empty() {
                return Err(McpError::invalid_params(
                    "Final task handoff owner must be non-empty",
                ));
            }
            let task_id = task.base().task_id.clone();
            if expected.task().base().task_id != task_id {
                return Err(McpError::invalid_params(
                    "Expected and replacement final task IDs must match",
                ));
            }
            if matches!(&task, fastmcp_protocol::Task::Cancelled(_)) != cancellation_required {
                return Err(McpError::invalid_params(
                    "Fenced final task cancellation disposition does not match the replacement task",
                ));
            }
            validate_server_final_task_durations(&task)?;
            ensure_server_final_task_notification_matches_task(&task, &notification)?;
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let now = self.now();
            reclaim_expired_server_final_task_handoffs(&mut state, now);
            let owns_exact_dispatch = state.handoff_leases.get(&task_id).is_some_and(|lease| {
                lease.generation == expected.generation()
                    && lease.owner_id == owner_id
                    && lease.dispatch_fence == Some(dispatch_fence)
            });
            if state.generations.get(&task_id) != Some(&expected.generation())
                || !owns_exact_dispatch
                || state.cancellation_requests.contains(&task_id) != cancellation_required
            {
                return Ok(None);
            }
            let execution_budget =
                prepare_server_final_task_execution_release(&state, &task_id, now)?;
            let generation = next_server_final_task_generation(&mut state)?;
            let terminal = matches!(
                &task,
                fastmcp_protocol::Task::Completed { .. }
                    | fastmcp_protocol::Task::Failed { .. }
                    | fastmcp_protocol::Task::Cancelled(_)
            );
            state.tasks.insert(task_id.clone(), task);
            state.generations.insert(task_id.clone(), generation);
            state
                .execution_budgets
                .insert(task_id.clone(), execution_budget);
            state.accepted_inputs.remove(&task_id);
            state.handoff_leases.remove(&task_id);
            state.initial_work.remove(&task_id);
            state.notifications.push(notification);
            if terminal {
                state.cancellation_requests.remove(&task_id);
            }
            Ok(Some(FinalTaskSnapshot::new(
                state.tasks[&task_id].clone(),
                generation,
            )))
        }

        fn take_input_if_current(
            &self,
            _expected: &FinalTaskSnapshot,
        ) -> McpResult<Option<fastmcp_protocol::TaskInputResponses>> {
            Err(McpError::internal_error(
                "Raw final task input claims require an authorized service owner",
            ))
        }

        fn take_input_for_owner_if_current(
            &self,
            expected: &FinalTaskSnapshot,
            owner_id: &str,
        ) -> McpResult<Option<fastmcp_protocol::TaskInputResponses>> {
            if owner_id.is_empty() {
                return Err(McpError::invalid_params(
                    "Final task handoff owner must be non-empty",
                ));
            }
            let task_id = &expected.task().base().task_id;
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let now = self.now();
            reclaim_expired_server_final_task_handoffs(&mut state, now);
            if !server_final_task_is_working(&state, task_id, expected.generation())
                || state.handoff_leases.contains_key(task_id)
                || server_final_task_execution_exhaustion(&state, task_id, now)?.is_some()
            {
                return Ok(None);
            }
            let Some(input_responses) = state.accepted_inputs.get(task_id).cloned() else {
                return Ok(None);
            };
            insert_server_final_task_handoff_lease(
                &mut state,
                task_id.clone(),
                expected.generation(),
                ServerFinalTaskHandoffKind::Resumed,
                owner_id,
                now,
            )?;
            Ok(Some(input_responses))
        }

        fn work_descriptor_if_current(
            &self,
            expected: &FinalTaskSnapshot,
        ) -> McpResult<Option<FinalTaskWorkDescriptor>> {
            let task_id = &expected.task().base().task_id;
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            reclaim_expired_server_final_task_handoffs(&mut state, self.now());
            if !server_final_task_is_working(&state, task_id, expected.generation()) {
                return Ok(None);
            }
            state
                .work_descriptors
                .get(task_id)
                .cloned()
                .map(Some)
                .ok_or_else(|| {
                    McpError::internal_error(
                        "Server final task test-store is missing a working task descriptor",
                    )
                })
        }

        fn next_initial_work_snapshot_after(
            &self,
            after_task_id: Option<&fastmcp_protocol::FinalTaskId>,
        ) -> McpResult<Option<FinalTaskSnapshot>> {
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let now = self.now();
            reclaim_expired_server_final_task_handoffs(&mut state, now);
            let Some(task_id) = next_server_final_task_recovery_id(
                state.initial_work.keys(),
                after_task_id,
                |task_id| {
                    Ok(state.generations.get(task_id).is_some_and(|generation| {
                        server_final_task_is_working(&state, task_id, *generation)
                    }) && !state.handoff_leases.contains_key(task_id)
                        && server_final_task_execution_exhaustion(&state, task_id, now)?.is_none())
                },
            )?
            else {
                return Ok(None);
            };
            let task = state.tasks.get(&task_id).cloned().ok_or_else(|| {
                McpError::internal_error(
                    "Server final task test-store retained initial work for a missing task",
                )
            })?;
            let generation = state.generations.get(&task_id).copied().ok_or_else(|| {
                McpError::internal_error(
                    "Server final task test-store retained initial work without a generation",
                )
            })?;
            Ok(Some(FinalTaskSnapshot::new(task, generation)))
        }

        fn next_initial_work_snapshot(&self) -> McpResult<Option<FinalTaskSnapshot>> {
            self.next_initial_work_snapshot_after(None)
        }

        fn take_initial_work_for_owner_if_current(
            &self,
            expected: &FinalTaskSnapshot,
            owner_id: &str,
        ) -> McpResult<Option<FinalTaskWorkDescriptor>> {
            if owner_id.is_empty() {
                return Err(McpError::invalid_params(
                    "Final task handoff owner must be non-empty",
                ));
            }
            let task_id = &expected.task().base().task_id;
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let now = self.now();
            reclaim_expired_server_final_task_handoffs(&mut state, now);
            if !server_final_task_is_working(&state, task_id, expected.generation())
                || state.handoff_leases.contains_key(task_id)
                || server_final_task_execution_exhaustion(&state, task_id, now)?.is_some()
            {
                return Ok(None);
            }
            let Some(work_descriptor) = state.initial_work.get(task_id).cloned() else {
                return Ok(None);
            };
            insert_server_final_task_handoff_lease(
                &mut state,
                task_id.clone(),
                expected.generation(),
                ServerFinalTaskHandoffKind::Initial,
                owner_id,
                now,
            )?;
            Ok(Some(work_descriptor))
        }

        fn restore_initial_work_for_owner_if_current(
            &self,
            task_id: &fastmcp_protocol::FinalTaskId,
            generation: u64,
            owner_id: &str,
            dispatch_fence: Option<u64>,
            work_descriptor: FinalTaskWorkDescriptor,
        ) -> McpResult<bool> {
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let now = self.now();
            reclaim_expired_server_final_task_handoffs(&mut state, now);
            let owns_lease = state.handoff_leases.get(task_id).is_some_and(|lease| {
                lease.generation == generation
                    && lease.kind == ServerFinalTaskHandoffKind::Initial
                    && lease.owner_id == owner_id
                    && lease.dispatch_fence == dispatch_fence
            });
            if !owns_lease {
                return Ok(false);
            }
            // The elected owner must retain its fence until it converts a
            // concurrent cancellation request into the terminal task state.
            // Removing it here would strand a working task with cancellation
            // intent after a supervisor error or dropped future.
            if state.cancellation_requests.contains(task_id)
                || server_final_task_execution_exhaustion(&state, task_id, now)?.is_some()
                || !server_final_task_is_working(&state, task_id, generation)
                || state.initial_work.get(task_id) != Some(&work_descriptor)
            {
                return Ok(false);
            }
            let execution_budget = released_server_final_task_execution_budget(&state, task_id)?;
            state.handoff_leases.remove(task_id);
            state
                .execution_budgets
                .insert(task_id.clone(), execution_budget);
            Ok(true)
        }

        fn next_accepted_input_snapshot_after(
            &self,
            after_task_id: Option<&fastmcp_protocol::FinalTaskId>,
        ) -> McpResult<Option<FinalTaskSnapshot>> {
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let now = self.now();
            reclaim_expired_server_final_task_handoffs(&mut state, now);
            let Some(task_id) = next_server_final_task_recovery_id(
                state.accepted_inputs.keys(),
                after_task_id,
                |task_id| {
                    Ok(state.generations.get(task_id).is_some_and(|generation| {
                        server_final_task_is_working(&state, task_id, *generation)
                    }) && !state.handoff_leases.contains_key(task_id)
                        && server_final_task_execution_exhaustion(&state, task_id, now)?.is_none())
                },
            )?
            else {
                return Ok(None);
            };
            let task = state.tasks.get(&task_id).cloned().ok_or_else(|| {
                McpError::internal_error(
                    "Server final task test-store retained input for a missing task",
                )
            })?;
            let generation = state.generations.get(&task_id).copied().ok_or_else(|| {
                McpError::internal_error(
                    "Server final task test-store retained input without a generation",
                )
            })?;
            Ok(Some(FinalTaskSnapshot::new(task, generation)))
        }

        fn next_accepted_input_snapshot(&self) -> McpResult<Option<FinalTaskSnapshot>> {
            self.next_accepted_input_snapshot_after(None)
        }

        fn restore_input_for_owner_if_current(
            &self,
            task_id: &fastmcp_protocol::FinalTaskId,
            generation: u64,
            owner_id: &str,
            dispatch_fence: Option<u64>,
            input_responses: fastmcp_protocol::TaskInputResponses,
        ) -> McpResult<bool> {
            if input_responses.is_empty() {
                return Err(McpError::internal_error(
                    "Cannot restore an empty accepted-input handoff",
                ));
            }
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let now = self.now();
            reclaim_expired_server_final_task_handoffs(&mut state, now);
            let owns_lease = state.handoff_leases.get(task_id).is_some_and(|lease| {
                lease.generation == generation
                    && lease.kind == ServerFinalTaskHandoffKind::Resumed
                    && lease.owner_id == owner_id
                    && lease.dispatch_fence == dispatch_fence
            });
            if !owns_lease {
                return Ok(false);
            }
            // See initial-work restoration: cancellation must retain the
            // elected fence until the runner records terminal cancellation.
            if state.cancellation_requests.contains(task_id)
                || server_final_task_execution_exhaustion(&state, task_id, now)?.is_some()
                || !server_final_task_is_working(&state, task_id, generation)
                || state.accepted_inputs.get(task_id) != Some(&input_responses)
            {
                return Ok(false);
            }
            let execution_budget = released_server_final_task_execution_budget(&state, task_id)?;
            state.handoff_leases.remove(task_id);
            state
                .execution_budgets
                .insert(task_id.clone(), execution_budget);
            Ok(true)
        }

        fn begin_handoff_dispatch_for_owner_if_current(
            &self,
            task_id: &fastmcp_protocol::FinalTaskId,
            generation: u64,
            owner_id: &str,
        ) -> McpResult<Option<u64>> {
            if owner_id.is_empty() {
                return Err(McpError::invalid_params(
                    "Final task handoff owner must be non-empty",
                ));
            }
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let now = self.now();
            reclaim_expired_server_final_task_handoffs(&mut state, now);
            if !server_final_task_is_working(&state, task_id, generation)
                || server_final_task_execution_exhaustion(&state, task_id, now)?.is_some()
                || !state.handoff_leases.get(task_id).is_some_and(|lease| {
                    lease.generation == generation
                        && lease.owner_id == owner_id
                        && lease.dispatch_fence.is_none()
                        && lease.expires_at > now
                })
            {
                return Ok(None);
            }
            let dispatch_fence = next_server_final_task_dispatch_fence(&mut state)?;
            let expires_at = server_final_task_handoff_expiry(now)?;
            let lease = state.handoff_leases.get_mut(task_id).ok_or_else(|| {
                McpError::internal_error("Server final task test-store lost a handoff lease")
            })?;
            lease.dispatch_fence = Some(dispatch_fence);
            lease.expires_at = expires_at;
            Ok(Some(dispatch_fence))
        }

        fn renew_handoff_dispatch_if_current(
            &self,
            task_id: &fastmcp_protocol::FinalTaskId,
            generation: u64,
            owner_id: &str,
            dispatch_fence: u64,
        ) -> McpResult<bool> {
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let now = self.now();
            reclaim_expired_server_final_task_handoffs(&mut state, now);
            if !server_final_task_is_working(&state, task_id, generation)
                || server_final_task_execution_exhaustion(&state, task_id, now)?.is_some()
                || !state.handoff_leases.get(task_id).is_some_and(|lease| {
                    lease.generation == generation
                        && lease.owner_id == owner_id
                        && lease.dispatch_fence == Some(dispatch_fence)
                })
            {
                return Ok(false);
            }
            let expires_at = server_final_task_handoff_expiry(now)?;
            let lease = state.handoff_leases.get_mut(task_id).ok_or_else(|| {
                McpError::internal_error("Server final task test-store lost a handoff lease")
            })?;
            lease.expires_at = expires_at;
            Ok(true)
        }

        fn handoff_dispatch_lease_heartbeat_interval(&self) -> McpResult<Duration> {
            Ok(SERVER_FINAL_TASK_HANDOFF_HEARTBEAT)
        }

        fn finish_handoff_dispatch_for_owner_if_current(
            &self,
            task_id: &fastmcp_protocol::FinalTaskId,
            generation: u64,
            owner_id: &str,
            dispatch_fence: u64,
        ) -> McpResult<bool> {
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let now = self.now();
            reclaim_expired_server_final_task_handoffs(&mut state, now);
            let Some(lease) = state.handoff_leases.get(task_id) else {
                return Ok(false);
            };
            if lease.generation != generation
                || lease.owner_id != owner_id
                || lease.dispatch_fence != Some(dispatch_fence)
            {
                return Ok(false);
            }
            // A cancellation race after the supervisor returns must preserve
            // this elected fence for fenced terminal retirement.
            if state.cancellation_requests.contains(task_id)
                || server_final_task_execution_exhaustion(&state, task_id, now)?.is_some()
            {
                return Ok(false);
            }
            let kind = lease.kind;
            let still_dispatchable = server_final_task_is_working(&state, task_id, generation);
            let execution_budget = released_server_final_task_execution_budget(&state, task_id)?;
            state.handoff_leases.remove(task_id);
            state
                .execution_budgets
                .insert(task_id.clone(), execution_budget);
            if still_dispatchable {
                match kind {
                    ServerFinalTaskHandoffKind::Initial => {
                        state.initial_work.remove(task_id);
                    }
                    ServerFinalTaskHandoffKind::Resumed => {
                        state.accepted_inputs.remove(task_id);
                    }
                }
            }
            Ok(still_dispatchable)
        }

        fn request_cancellation(&self, task_id: &fastmcp_protocol::FinalTaskId) -> McpResult<()> {
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let now = self.now();
            reclaim_expired_server_final_task_handoffs(&mut state, now);
            if !state.tasks.contains_key(task_id) {
                return Err(McpError::invalid_params("Task not found"));
            }
            record_server_final_task_cancellation(&mut state, task_id, now)
        }

        fn request_cancellation_if_current(&self, expected: &FinalTaskSnapshot) -> McpResult<bool> {
            let task_id = &expected.task().base().task_id;
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let now = self.now();
            reclaim_expired_server_final_task_handoffs(&mut state, now);
            if state.generations.get(task_id) != Some(&expected.generation()) {
                return Ok(false);
            }
            record_server_final_task_cancellation(&mut state, task_id, now)?;
            Ok(true)
        }

        fn request_cancellation_and_clear_input_if_current(
            &self,
            expected: &FinalTaskSnapshot,
            cancelled_task: fastmcp_protocol::Task,
            cancelled_notification: fastmcp_protocol::TaskStatusNotification,
        ) -> McpResult<Option<FinalTaskSnapshot>> {
            let task_id = &expected.task().base().task_id;
            if &cancelled_task.base().task_id != task_id {
                return Err(McpError::invalid_params(
                    "Expected and cancelled final task IDs must match",
                ));
            }
            if !matches!(&cancelled_task, fastmcp_protocol::Task::Cancelled(_)) {
                return Err(McpError::invalid_params(
                    "Atomic task cancellation requires a cancelled final task",
                ));
            }
            validate_server_final_task_durations(&cancelled_task)?;
            ensure_server_final_task_notification_matches_task(
                &cancelled_task,
                &cancelled_notification,
            )?;
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let now = self.now();
            reclaim_expired_server_final_task_handoffs(&mut state, now);
            if state.generations.get(task_id) != Some(&expected.generation()) {
                return Ok(None);
            }
            let execution_budget =
                prepare_server_final_task_execution_release(&state, task_id, now)?;
            let dispatch_elected = state.handoff_leases.get(task_id).is_some_and(|lease| {
                lease.generation == expected.generation() && lease.dispatch_fence.is_some()
            });
            if dispatch_elected {
                record_server_final_task_cancellation(&mut state, task_id, now)?;
                let task = state.tasks.get(task_id).cloned().ok_or_else(|| {
                    McpError::internal_error(
                        "Server final task test store lost an elected task during cancellation",
                    )
                })?;
                let generation = state.generations.get(task_id).copied().ok_or_else(|| {
                    McpError::internal_error(
                        "Server final task test store lost an elected task generation during cancellation",
                    )
                })?;
                return Ok(Some(FinalTaskSnapshot::new(task, generation)));
            }
            let generation = next_server_final_task_generation(&mut state)?;
            state.tasks.insert(task_id.clone(), cancelled_task.clone());
            state.generations.insert(task_id.clone(), generation);
            state
                .execution_budgets
                .insert(task_id.clone(), execution_budget);
            state.accepted_inputs.remove(task_id);
            state.initial_work.remove(task_id);
            state.handoff_leases.remove(task_id);
            state.cancellation_requests.remove(task_id);
            state.notifications.push(cancelled_notification);
            Ok(Some(FinalTaskSnapshot::new(cancelled_task, generation)))
        }

        fn is_cancellation_requested(
            &self,
            task_id: &fastmcp_protocol::FinalTaskId,
        ) -> McpResult<bool> {
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            reclaim_expired_server_final_task_handoffs(&mut state, self.now());
            if !state.tasks.contains_key(task_id) {
                return Err(McpError::invalid_params("Task not found"));
            }
            Ok(state.cancellation_requests.contains(task_id))
        }

        fn retention_clock_now(&self) -> Instant {
            self.now()
        }

        fn task_retention_deadline_if_current(
            &self,
            task_id: &fastmcp_protocol::FinalTaskId,
            generation: u64,
        ) -> McpResult<Option<FinalTaskRetentionDeadline>> {
            let state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if state.generations.get(task_id) != Some(&generation) {
                return Ok(None);
            }
            if let Some(expires_at) = state.expires_at.get(task_id).copied() {
                Ok(Some(FinalTaskRetentionDeadline::Finite(expires_at)))
            } else if state.tasks.contains_key(task_id) {
                Ok(Some(FinalTaskRetentionDeadline::Unlimited))
            } else {
                Ok(None)
            }
        }
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn server_final_task_store_execution_budget_survives_renewal_and_reclaim() {
        let start = Instant::now();
        let clock_now = Arc::new(Mutex::new(start));
        let clock = {
            let clock_now = Arc::clone(&clock_now);
            Arc::new(move || {
                *clock_now
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
            })
        };
        let mut backend = ServerFinalTaskStore::with_clock(clock);
        backend.execution_limits = crate::tasks::FinalTaskExecutionLimits::new(
            Duration::from_secs(120),
            Duration::from_secs(60),
            2,
        )
        .expect("finite backend execution policy");
        let store = Arc::new(backend);
        let runtime = server_final_task_store_runtime(Arc::clone(&store));
        let mut service = start_final_tasks_test_service(&runtime);

        let healthy = runtime
            .create_task_with_work(final_tasks_test_work_descriptor(), None)
            .expect("public admission accepts a bounded backend");
        let mut poll_cx = std::task::Context::from_waker(std::task::Waker::noop());
        assert!(Future::poll(service.as_mut(), &mut poll_cx).is_pending());
        assert!(matches!(
            runtime
                .get_task(&healthy.task.base().task_id)
                .expect("read service completion")
                .task,
            fastmcp_protocol::Task::Completed { .. }
        ));

        let created = runtime
            .create_task_with_work(final_tasks_test_work_descriptor(), None)
            .expect("public admission stamps execution accounting");
        let task_id = created.task.base().task_id.clone();
        let snapshot = store.get_task_snapshot(&task_id).unwrap().unwrap();
        let original = store
            .task_execution_budget_if_current(&snapshot)
            .unwrap()
            .unwrap();
        assert_eq!(original.total_deadline(), start + Duration::from_secs(120));
        assert_eq!(original.attempt_deadline(), None);
        assert_eq!(original.attempts(), 0);

        let work = store
            .take_initial_work_for_owner_if_current(&snapshot, "first-owner")
            .unwrap()
            .unwrap();
        let claimed = store
            .task_execution_budget_if_current(&snapshot)
            .unwrap()
            .unwrap();
        assert_eq!(claimed.attempts(), 1);
        assert_eq!(
            claimed.attempt_deadline(),
            Some(start + Duration::from_secs(60))
        );
        assert!(
            store
                .take_initial_work_for_owner_if_current(&snapshot, "other-owner")
                .unwrap()
                .is_none()
        );
        assert_eq!(
            store.task_execution_budget_if_current(&snapshot).unwrap(),
            Some(claimed)
        );
        let fence = store
            .begin_handoff_dispatch_for_owner_if_current(
                &task_id,
                snapshot.generation(),
                "first-owner",
            )
            .unwrap()
            .unwrap();

        *clock_now
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = start + Duration::from_secs(10);
        assert!(
            store
                .renew_handoff_dispatch_if_current(
                    &task_id,
                    snapshot.generation(),
                    "first-owner",
                    fence,
                )
                .unwrap()
        );
        assert_eq!(
            store.task_execution_budget_if_current(&snapshot).unwrap(),
            Some(claimed)
        );

        *clock_now
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = start + Duration::from_secs(40);
        let recovered = store.get_task_snapshot(&task_id).unwrap().unwrap();
        assert!(recovered.generation() > snapshot.generation());
        assert!(
            store
                .task_execution_budget_if_current(&snapshot)
                .unwrap()
                .is_none()
        );
        let released = store
            .task_execution_budget_if_current(&recovered)
            .unwrap()
            .unwrap();
        assert_eq!(released.total_deadline(), original.total_deadline());
        assert_eq!(released.attempt_deadline(), None);
        assert_eq!(released.attempts(), 1);
        assert!(
            !store
                .restore_initial_work_for_owner_if_current(
                    &task_id,
                    snapshot.generation(),
                    "first-owner",
                    Some(fence),
                    work.clone(),
                )
                .unwrap()
        );
        assert_eq!(
            store.task_execution_budget_if_current(&recovered).unwrap(),
            Some(released)
        );

        assert!(
            store
                .take_initial_work_for_owner_if_current(&recovered, "second-owner")
                .unwrap()
                .is_some()
        );
        let retried = store
            .task_execution_budget_if_current(&recovered)
            .unwrap()
            .unwrap();
        assert_eq!(retried.total_deadline(), original.total_deadline());
        assert_eq!(
            retried.attempt_deadline(),
            Some(start + Duration::from_secs(100))
        );
        assert_eq!(retried.attempts(), 2);
        assert!(
            store
                .restore_initial_work_for_owner_if_current(
                    &task_id,
                    recovered.generation(),
                    "second-owner",
                    None,
                    work,
                )
                .unwrap()
        );
        assert!(
            store
                .take_initial_work_for_owner_if_current(&recovered, "third-owner")
                .unwrap()
                .is_none()
        );
        let fastmcp_protocol::Task::Failed { error, .. } = runtime
            .get_task(&task_id)
            .expect("public read retires exhausted claims")
            .task
        else {
            panic!("claim exhaustion must retain a failed task");
        };
        assert_eq!(error.message, "Task execution attempt limit exceeded");
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn server_final_task_store_execution_expiry_fences_completion_and_retains_identity() {
        let start = Instant::now();
        let clock_now = Arc::new(Mutex::new(start));
        let clock = {
            let clock_now = Arc::clone(&clock_now);
            Arc::new(move || {
                *clock_now
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
            })
        };
        let mut backend = ServerFinalTaskStore::with_clock(clock);
        backend.execution_limits = crate::tasks::FinalTaskExecutionLimits::new(
            Duration::from_millis(100),
            Duration::from_millis(10),
            2,
        )
        .expect("finite backend execution policy");
        let store = Arc::new(backend);
        let runtime = server_final_task_store_runtime(Arc::clone(&store));
        let _service = start_final_tasks_test_service(&runtime);
        let created = runtime
            .create_task_with_work(final_tasks_test_work_descriptor(), None)
            .unwrap();
        let sibling = runtime
            .create_task_with_work(final_tasks_test_work_descriptor(), None)
            .unwrap();
        let task_id = created.task.base().task_id.clone();
        let snapshot = store.get_task_snapshot(&task_id).unwrap().unwrap();
        let sibling_snapshot = store
            .get_task_snapshot(&sibling.task.base().task_id)
            .unwrap()
            .unwrap();
        store
            .take_initial_work_for_owner_if_current(&snapshot, "owner")
            .unwrap()
            .unwrap();
        let fence = store
            .begin_handoff_dispatch_for_owner_if_current(&task_id, snapshot.generation(), "owner")
            .unwrap()
            .unwrap();
        let claimed = store
            .task_execution_budget_if_current(&snapshot)
            .unwrap()
            .unwrap();
        let retained_ttl = snapshot.task().base().ttl_ms.clone();
        let retained_created_at = snapshot.task().base().created_at.clone();
        assert!(
            store
                .expire_task_execution_if_current(&snapshot)
                .unwrap()
                .is_none()
        );

        *clock_now
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = start + Duration::from_millis(10);
        assert!(
            !store
                .renew_handoff_dispatch_if_current(&task_id, snapshot.generation(), "owner", fence)
                .unwrap()
        );
        let completed = fastmcp_protocol::Task::Completed {
            base: crate::tasks::transition_terminal_final_task_base(
                snapshot.task().base().clone(),
                fastmcp_protocol::FinalTaskStatus::Completed,
                None,
            )
            .unwrap(),
            result: serde_json::from_value(serde_json::json!({"content": []})).unwrap(),
        };
        let error = store
            .replace_task_and_clear_input_for_handoff_if_current(
                &snapshot,
                "owner",
                fence,
                false,
                completed.clone(),
                crate::tasks::final_task_notification(&completed),
            )
            .expect_err("late fenced completion cannot replace the pending timeout");
        assert_eq!(error.code, McpErrorCode::InvalidParams);
        assert_eq!(
            store
                .get_task_snapshot(&task_id)
                .unwrap()
                .unwrap()
                .generation(),
            snapshot.generation()
        );
        assert_eq!(
            store.task_execution_budget_if_current(&snapshot).unwrap(),
            Some(claimed)
        );
        {
            let state = store
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            assert_eq!(state.notifications.len(), 2);
            assert_eq!(state.handoff_leases[&task_id].dispatch_fence, Some(fence));
        }
        assert_eq!(
            store
                .next_expired_execution_snapshot()
                .unwrap()
                .unwrap()
                .task()
                .base()
                .task_id,
            task_id
        );

        let mut forged_base = snapshot.task().base().clone();
        forged_base.ttl_ms = None;
        let forged = FinalTaskSnapshot::new(
            fastmcp_protocol::Task::Working(forged_base),
            snapshot.generation(),
        );
        let expired = store
            .expire_task_execution_if_current(&forged)
            .unwrap()
            .unwrap();
        assert_eq!(expired.task().base().ttl_ms, retained_ttl);
        assert_eq!(expired.task().base().created_at, retained_created_at);
        assert!(expired.generation() > snapshot.generation());
        let fastmcp_protocol::Task::Failed { error, .. } = expired.task() else {
            panic!("attempt timeout must commit a typed failure");
        };
        assert_eq!(error.code, (-32000).into());
        assert_eq!(error.message, "Task attempt execution deadline exceeded");
        assert!(
            store
                .expire_task_execution_if_current(&snapshot)
                .unwrap()
                .is_none()
        );
        assert!(matches!(
            runtime.get_task(&task_id).unwrap().task,
            fastmcp_protocol::Task::Failed { .. }
        ));
        assert_eq!(
            store
                .get_task_snapshot(&sibling.task.base().task_id)
                .unwrap()
                .unwrap()
                .generation(),
            sibling_snapshot.generation()
        );
        {
            let state = store
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            assert_eq!(state.notifications.len(), 3);
            assert!(!state.handoff_leases.contains_key(&task_id));
            assert!(!state.initial_work.contains_key(&task_id));
            assert_eq!(state.execution_budgets[&task_id].attempt_deadline(), None);
            assert_eq!(state.execution_budgets[&task_id].attempts(), 1);
        }

        *clock_now
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) =
            start + Duration::from_millis(100);
        assert!(store.next_initial_work_snapshot().unwrap().is_none());
        let fastmcp_protocol::Task::Failed { error, .. } =
            runtime.get_task(&sibling.task.base().task_id).unwrap().task
        else {
            panic!("queued work must expire without first acquiring a worker");
        };
        assert_eq!(error.message, "Task total execution deadline exceeded");
        let state = store
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert_eq!(
            state.execution_budgets[&sibling.task.base().task_id].attempts(),
            0
        );
        assert_eq!(state.notifications.len(), 4);
    }

    #[cfg(feature = "tasks")]
    struct FinalTasksTestSupervisor;

    #[cfg(feature = "tasks")]
    impl ApplicationTaskSupervisor for FinalTasksTestSupervisor {
        fn resume<'a>(
            &'a self,
            _cx: &'a Cx,
            handoff: FinalTaskSupervisorHandoff,
        ) -> FinalTaskSupervisorFuture<'a> {
            Box::pin(async move {
                let result = serde_json::from_value(serde_json::json!({"content": []}))
                    .expect("typed terminal task result");
                match handoff {
                    FinalTaskSupervisorHandoff::Initial(initial) => {
                        initial
                            .complete_task(result, Some("completed by test service".to_owned()))?;
                    }
                    FinalTaskSupervisorHandoff::Resumed(accepted) => {
                        accepted
                            .complete_task(result, Some("completed by test service".to_owned()))?;
                    }
                }
                Ok(())
            })
        }
    }

    /// Starts an owned Tasks runner and advances it to its receive boundary.
    ///
    /// Callers retain the returned future for the server lifetime. Tests that
    /// claim handoff consumption drive that same future after a durable wakeup
    /// rather than treating readiness alone as execution evidence.
    #[cfg(feature = "tasks")]
    fn start_final_tasks_test_service(
        runtime: &FinalTaskRuntime,
    ) -> std::pin::Pin<Box<dyn Future<Output = McpResult<()>>>> {
        let runner = runtime
            .install_task_service(1, Arc::new(FinalTasksTestSupervisor))
            .expect("test final Tasks service must install");
        let service_cx = Cx::for_testing();
        let mut service = Box::pin(async move { runner.run(&service_cx).await });
        let mut poll_cx = std::task::Context::from_waker(std::task::Waker::noop());
        assert!(
            Future::poll(service.as_mut(), &mut poll_cx).is_pending(),
            "test final Tasks service must publish readiness and remain owned",
        );
        service
    }

    #[cfg(feature = "tasks")]
    fn final_tasks_test_work_descriptor() -> FinalTaskWorkDescriptor {
        FinalTaskWorkDescriptor::new(serde_json::json!({
            "operation": "server-final-tasks-test",
        }))
        .expect("test final Tasks work descriptor must be valid")
    }

    #[cfg(feature = "tasks")]
    struct RecordingServerFinalTaskSupervisor {
        started: Arc<Mutex<Vec<fastmcp_protocol::FinalTaskId>>>,
    }

    #[cfg(feature = "tasks")]
    impl ApplicationTaskSupervisor for RecordingServerFinalTaskSupervisor {
        fn resume<'a>(
            &'a self,
            cx: &'a Cx,
            handoff: FinalTaskSupervisorHandoff,
        ) -> FinalTaskSupervisorFuture<'a> {
            let started = Arc::clone(&self.started);
            Box::pin(async move {
                let FinalTaskSupervisorHandoff::Initial(initial) = handoff else {
                    return Err(McpError::internal_error(
                        "server final task test supervisor expected initial work",
                    ));
                };
                started
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .push(initial.task_id().clone());
                let result = serde_json::from_value(serde_json::json!({"content": []}))
                    .expect("typed terminal task result");
                initial.complete_task(result, None)?;
                cx.cancel_with(asupersync::CancelKind::User, None);
                Ok(())
            })
        }
    }

    #[cfg(feature = "tasks")]
    fn server_final_task_store_runtime(store: Arc<ServerFinalTaskStore>) -> FinalTaskRuntime {
        FinalTaskRuntime::new(
            store,
            FinalTaskRuntimeConfig::new(60_000, None)
                .expect("server final task test policy is valid"),
            Arc::new(|_| {}),
        )
    }

    #[cfg(feature = "tasks")]
    fn poll_final_task_service_once<F>(
        service: std::pin::Pin<&mut F>,
    ) -> std::task::Poll<McpResult<()>>
    where
        F: Future<Output = McpResult<()>>,
    {
        let mut task_cx = std::task::Context::from_waker(std::task::Waker::noop());
        Future::poll(service, &mut task_cx)
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn server_final_task_store_service_consumes_durable_initial_work() {
        let store = Arc::new(ServerFinalTaskStore::default());
        let runtime = server_final_task_store_runtime(Arc::clone(&store));
        let started = Arc::new(Mutex::new(Vec::new()));
        let runner = runtime
            .install_task_service(
                1,
                Arc::new(RecordingServerFinalTaskSupervisor {
                    started: Arc::clone(&started),
                }),
            )
            .expect("test task service installs");
        let service_cx = Cx::for_testing();
        let mut service = Box::pin(runner.run(&service_cx));

        assert!(matches!(
            poll_final_task_service_once(service.as_mut()),
            std::task::Poll::Pending
        ));
        let created = runtime
            .create_task_with_work(final_tasks_test_work_descriptor(), None)
            .expect("ready service admits durable initial work");
        let task_id = created.task.base().task_id.clone();

        assert!(matches!(
            poll_final_task_service_once(service.as_mut()),
            std::task::Poll::Ready(Ok(()))
        ));
        assert_eq!(
            started
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .as_slice(),
            &[task_id],
            "the service consumes exactly the initial descriptor retained with task creation"
        );
        assert!(
            FinalTaskStore::next_initial_work_snapshot(&*store)
                .expect("completed initial-work scan is valid")
                .is_none(),
            "successful owner-fenced dispatch consumes the initial handoff"
        );
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn server_final_task_store_cancellation_before_wakeup_fences_initial_work() {
        let store = Arc::new(ServerFinalTaskStore::default());
        let runtime = server_final_task_store_runtime(Arc::clone(&store));
        let started = Arc::new(Mutex::new(Vec::new()));
        let runner = runtime
            .install_task_service(
                1,
                Arc::new(RecordingServerFinalTaskSupervisor {
                    started: Arc::clone(&started),
                }),
            )
            .expect("test task service installs");
        let service_cx = Cx::for_testing();
        let mut service = Box::pin(runner.run(&service_cx));

        assert!(matches!(
            poll_final_task_service_once(service.as_mut()),
            std::task::Poll::Pending
        ));
        let created = runtime
            .create_task_with_work(final_tasks_test_work_descriptor(), None)
            .expect("ready service admits durable initial work");
        let task_id = created.task.base().task_id.clone();
        runtime
            .cancel_task(&task_id)
            .expect("changing only cancellation records intent before service polling");

        assert!(matches!(
            poll_final_task_service_once(service.as_mut()),
            std::task::Poll::Pending
        ));
        assert!(
            started
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .is_empty(),
            "cancellation before dispatch prevents application initial work"
        );
        assert!(
            FinalTaskStore::next_initial_work_snapshot(&*store)
                .expect("cancelled initial-work scan is valid")
                .is_none(),
            "cancellation fences the durable initial handoff instead of allowing recovery"
        );
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn server_final_task_store_expired_elected_cancellation_lease_retires_task() {
        let start = Instant::now();
        let clock_now = Arc::new(Mutex::new(start));
        let clock = {
            let clock_now = Arc::clone(&clock_now);
            Arc::new(move || {
                *clock_now
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
            })
        };
        let store = ServerFinalTaskStore::with_clock(clock);
        let task_id = fastmcp_protocol::FinalTaskId::parse("server-expired-elected-cancellation")
            .expect("fixed final task ID must be valid");
        let timestamp = fastmcp_protocol::TaskTimestamp::parse("2026-07-28T12:00:00.000Z")
            .expect("fixed final task timestamp must be valid");
        let task = fastmcp_protocol::Task::Working(fastmcp_protocol::TaskBase {
            task_id: task_id.clone(),
            status: fastmcp_protocol::FinalTaskStatus::Working,
            status_message: None,
            created_at: timestamp.clone(),
            last_updated_at: timestamp,
            ttl_ms: None,
            poll_interval_ms: None,
        });
        let notification = crate::tasks::final_task_notification(&task);
        store
            .create_task_with_work(task, notification, final_tasks_test_work_descriptor())
            .expect("initial work is atomically retained");
        let snapshot = store
            .get_task_snapshot(&task_id)
            .expect("elected task snapshot is readable")
            .expect("elected task remains retained");
        let owner_id = "server-expired-cancelled-owner";
        assert!(
            store
                .take_initial_work_for_owner_if_current(&snapshot, owner_id)
                .expect("initial work claim is valid")
                .is_some()
        );
        store
            .begin_handoff_dispatch_for_owner_if_current(&task_id, snapshot.generation(), owner_id)
            .expect("dispatch election is valid")
            .expect("claimed owner becomes elected");
        store
            .request_cancellation(&task_id)
            .expect("elected task records durable cancellation intent");

        *clock_now
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = start
            .checked_add(SERVER_FINAL_TASK_HANDOFF_LEASE)
            .expect("fixed server handoff lease fits the monotonic clock");

        let retired = store
            .get_task_snapshot(&task_id)
            .expect("expired lease reclamation is readable")
            .expect("unlimited-retention task remains stored after lease expiry");
        assert!(matches!(
            retired.task(),
            fastmcp_protocol::Task::Cancelled(_)
        ));
        assert!(
            !store
                .is_cancellation_requested(&task_id)
                .expect("terminal retirement consumes cancellation intent")
        );
        let state = store
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert!(
            !state.handoff_leases.contains_key(&task_id)
                && !state.initial_work.contains_key(&task_id)
                && !state.accepted_inputs.contains_key(&task_id),
            "changing only cancellation from normal server-lease expiry leaves no stranded work"
        );
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn server_final_task_store_reclaims_finite_ttl_task_and_work_at_creation_expiry() {
        let start = Instant::now();
        let clock_now = Arc::new(Mutex::new(start));
        let clock = {
            let clock_now = Arc::clone(&clock_now);
            Arc::new(move || {
                *clock_now
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
            })
        };
        let store = ServerFinalTaskStore::with_clock(clock);
        let task_id = fastmcp_protocol::FinalTaskId::parse("server-store-ttl-test")
            .expect("fixed final task ID must be valid");
        let timestamp = fastmcp_protocol::TaskTimestamp::parse("2026-07-28T12:00:00.000Z")
            .expect("fixed final task timestamp must be valid");
        let task = fastmcp_protocol::Task::Working(fastmcp_protocol::TaskBase {
            task_id: task_id.clone(),
            status: fastmcp_protocol::FinalTaskStatus::Working,
            status_message: None,
            created_at: timestamp.clone(),
            last_updated_at: timestamp,
            ttl_ms: Some(
                serde_json::from_value(serde_json::json!(10_u64))
                    .expect("positive finite task TTL must be valid"),
            ),
            poll_interval_ms: None,
        });
        let notification = fastmcp_protocol::TaskStatusNotification::new(
            fastmcp_protocol::tasks_extension::TaskStatusNotificationParams {
                task: task.clone(),
                meta: None,
                additional: BTreeMap::new(),
            },
        );
        store
            .create_task_with_work(task, notification, final_tasks_test_work_descriptor())
            .expect("finite task creation atomically retains task and initial work");

        let pre_expiry_snapshot = store
            .get_task_snapshot(&task_id)
            .expect("pre-expiry task snapshot is readable")
            .expect("finite task remains readable before its creation-time TTL expires");
        assert!(
            store
                .work_descriptor_if_current(&pre_expiry_snapshot)
                .expect("pre-expiry work lookup is valid")
                .is_some(),
            "the initial descriptor remains readable before expiry"
        );
        assert!(
            store
                .next_initial_work_snapshot()
                .expect("pre-expiry initial-work recovery scan is valid")
                .is_some(),
            "the initial descriptor remains recoverable before expiry"
        );

        *clock_now
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = start
            .checked_add(Duration::from_millis(10))
            .expect("test monotonic clock must represent task expiry");

        assert!(
            store
                .get_task(&task_id)
                .expect("post-expiry task lookup is valid")
                .is_none(),
            "changing only the clock to the finite creation-time expiry reclaims the task"
        );
        assert!(
            store
                .get_task_snapshot(&task_id)
                .expect("post-expiry task snapshot lookup is valid")
                .is_none(),
            "expiry leaves no readable task generation"
        );
        assert!(
            store
                .next_initial_work_snapshot()
                .expect("post-expiry initial-work recovery scan is valid")
                .is_none(),
            "expiry leaves no recoverable initial work"
        );
        let state = store
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert!(
            !state.work_descriptors.contains_key(&task_id)
                && !state.initial_work.contains_key(&task_id)
                && !state.expires_at.contains_key(&task_id),
            "post-expiry reclamation clears only the expired task's private work and expiry state"
        );
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn server_final_task_store_rejects_out_of_range_ttl_before_mutation() {
        let store = ServerFinalTaskStore::default();
        let task_id = fastmcp_protocol::FinalTaskId::parse("server-store-oversized-ttl")
            .expect("fixed final task ID must be valid");
        let timestamp = fastmcp_protocol::TaskTimestamp::parse("2026-07-28T12:00:00.000Z")
            .expect("fixed final task timestamp must be valid");
        let task = fastmcp_protocol::Task::Working(fastmcp_protocol::TaskBase {
            task_id: task_id.clone(),
            status: fastmcp_protocol::FinalTaskStatus::Working,
            status_message: None,
            created_at: timestamp.clone(),
            last_updated_at: timestamp,
            ttl_ms: None,
            poll_interval_ms: None,
        });
        let mut wire = serde_json::to_value(task).expect("serialize valid task baseline");
        wire["ttlMs"] = serde_json::from_str("18446744073709551616")
            .expect("retain the oversized mathematical JSON integer");
        let error = serde_json::from_value::<fastmcp_protocol::Task>(wire)
            .expect_err("out-of-range task TTL must be rejected during typed admission");
        assert_eq!(error.classify(), serde_json::error::Category::Data);
        let state = store
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert!(
            state.tasks.is_empty()
                && state.generations.is_empty()
                && state.notifications.is_empty()
                && state.expires_at.is_empty(),
            "typed TTL admission fails before task-store mutation"
        );
        assert_eq!(state.next_generation, 0);
        assert!(!state.tasks.contains_key(&task_id));
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn server_final_task_store_rejects_out_of_range_poll_before_reclaiming_expired_state() {
        let start = Instant::now();
        let clock_now = Arc::new(Mutex::new(start));
        let clock = {
            let clock_now = Arc::clone(&clock_now);
            Arc::new(move || {
                *clock_now
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
            })
        };
        let store = ServerFinalTaskStore::with_clock(clock);
        let timestamp = fastmcp_protocol::TaskTimestamp::parse("2026-07-28T12:00:00.000Z")
            .expect("fixed final task timestamp must be valid");
        let expired_id = fastmcp_protocol::FinalTaskId::parse("server-store-expired-before-poll")
            .expect("fixed expired task ID must be valid");
        let expired_task = fastmcp_protocol::Task::Working(fastmcp_protocol::TaskBase {
            task_id: expired_id.clone(),
            status: fastmcp_protocol::FinalTaskStatus::Working,
            status_message: None,
            created_at: timestamp.clone(),
            last_updated_at: timestamp.clone(),
            ttl_ms: Some(
                serde_json::from_value(serde_json::json!(1_u64))
                    .expect("finite expiry TTL must be valid"),
            ),
            poll_interval_ms: None,
        });
        let expired_notification = fastmcp_protocol::TaskStatusNotification::new(
            fastmcp_protocol::tasks_extension::TaskStatusNotificationParams {
                task: expired_task.clone(),
                meta: None,
                additional: BTreeMap::new(),
            },
        );
        store
            .create_task(expired_task, expired_notification)
            .expect("baseline expired task must enter the store");
        *clock_now
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = start
            .checked_add(Duration::from_millis(1))
            .expect("test monotonic clock must represent expiry");

        let rejected_id = fastmcp_protocol::FinalTaskId::parse("server-store-oversized-poll")
            .expect("fixed rejected task ID must be valid");
        let rejected_task = fastmcp_protocol::Task::Working(fastmcp_protocol::TaskBase {
            task_id: rejected_id.clone(),
            status: fastmcp_protocol::FinalTaskStatus::Working,
            status_message: None,
            created_at: timestamp.clone(),
            last_updated_at: timestamp,
            ttl_ms: None,
            poll_interval_ms: None,
        });
        let mut wire = serde_json::to_value(rejected_task).expect("serialize valid task baseline");
        wire["pollIntervalMs"] = serde_json::from_str("18446744073709551616")
            .expect("retain the oversized mathematical JSON integer");
        let error = serde_json::from_value::<fastmcp_protocol::Task>(wire)
            .expect_err("out-of-range task poll interval must fail typed admission");
        assert_eq!(error.classify(), serde_json::error::Category::Data);
        let state = store
            .state
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert!(
            state.tasks.contains_key(&expired_id)
                && state.expires_at.contains_key(&expired_id)
                && state.generations.contains_key(&expired_id)
                && !state.tasks.contains_key(&rejected_id),
            "typed poll admission rejects before reclaiming unrelated expired state"
        );
        assert_eq!(state.notifications.len(), 1);
        assert_eq!(state.next_generation, 1);
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn server_final_task_store_rejects_same_id_notification_base_drift_without_mutation() {
        let store = Arc::new(ServerFinalTaskStore::default());
        let timestamp = fastmcp_protocol::TaskTimestamp::parse("2026-07-28T12:00:00.000Z")
            .expect("fixed final task timestamp must be valid");
        let task = fastmcp_protocol::Task::Working(fastmcp_protocol::TaskBase {
            task_id: fastmcp_protocol::FinalTaskId::parse("server-store-drift-test")
                .expect("fixed final task ID must be valid"),
            status: fastmcp_protocol::FinalTaskStatus::Working,
            status_message: None,
            created_at: timestamp.clone(),
            last_updated_at: timestamp,
            ttl_ms: None,
            poll_interval_ms: None,
        });
        let notification = fastmcp_protocol::TaskStatusNotification::new(
            fastmcp_protocol::tasks_extension::TaskStatusNotificationParams {
                task: task.clone(),
                meta: None,
                additional: BTreeMap::new(),
            },
        );
        store
            .create_task(task.clone(), notification)
            .expect("matching task and notification create");
        let task_id = task.base().task_id.clone();
        let snapshot_before = store
            .get_task_snapshot(&task_id)
            .expect("stored task snapshot is readable")
            .expect("created task is retained");
        let task_before = serde_json::to_value(snapshot_before.task())
            .expect("serialize retained task before rejection");
        let notifications_before = {
            let state = store
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            serde_json::to_value(&state.notifications)
                .expect("serialize retained notifications before rejection")
        };

        let mut drifted_notification = {
            let state = store
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            state
                .notifications
                .last()
                .cloned()
                .expect("created task retains its notification")
        };
        let fastmcp_protocol::Task::Working(base) = &mut drifted_notification.params.task else {
            panic!("baseline notification contains the working task");
        };
        base.status_message = Some("only the notification task base drifted".to_owned());

        let error = store
            .replace_task_if_current(&snapshot_before, task, drifted_notification)
            .expect_err("same-ID notification base drift must be rejected");

        assert_eq!(error.code, fastmcp_core::McpErrorCode::InvalidParams);
        let snapshot_after = store
            .get_task_snapshot(&task_id)
            .expect("stored task snapshot remains readable")
            .expect("rejection preserves the retained task");
        assert_eq!(
            serde_json::to_value(snapshot_after.task())
                .expect("serialize retained task after rejection"),
            task_before,
            "rejection preserves the retained task"
        );
        assert_eq!(
            snapshot_after.generation(),
            snapshot_before.generation(),
            "rejection preserves the compare-and-swap generation"
        );
        let notifications_after = {
            let state = store
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            serde_json::to_value(&state.notifications)
                .expect("serialize retained notifications after rejection")
        };
        assert_eq!(
            notifications_after, notifications_before,
            "rejection preserves the retained notification history"
        );
    }

    #[cfg(feature = "tasks")]
    fn final_tasks_test_runtime(
        delivered: Arc<Mutex<Vec<fastmcp_protocol::TaskStatusNotification>>>,
    ) -> FinalTaskRuntime {
        let emitter: FinalTaskNotificationEmitter = Arc::new(move |notification| {
            delivered
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(notification);
        });
        FinalTaskRuntime::in_memory(
            FinalTaskRuntimeConfig::new(60_000, Some(5_000))
                .expect("valid final Tasks timing policy"),
            emitter,
        )
    }

    #[cfg(feature = "tasks")]
    fn final_tasks_test_server(
        delivered: Arc<Mutex<Vec<fastmcp_protocol::TaskStatusNotification>>>,
    ) -> (
        Server,
        std::pin::Pin<Box<dyn Future<Output = McpResult<()>>>>,
    ) {
        let runtime = final_tasks_test_runtime(delivered);
        let service = start_final_tasks_test_service(&runtime);
        let server = Server::new("final-tasks-server", "1.0.0")
            .final_tasks(runtime)
            .expect("final Tasks must install")
            .build();
        (server, service)
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn final_tasks_test_server_drives_retained_service_after_task_creation() {
        let delivered = Arc::new(Mutex::new(Vec::new()));
        let (server, mut service) = final_tasks_test_server(Arc::clone(&delivered));
        let runtime = server
            .final_task_runtime()
            .expect("configured final Tasks runtime must be retained");
        let task_id = runtime
            .create_task_with_work(final_tasks_test_work_descriptor(), None)
            .expect("ready service accepts durable task creation")
            .task
            .base()
            .task_id
            .clone();

        let mut poll_cx = std::task::Context::from_waker(std::task::Waker::noop());
        assert!(
            Future::poll(service.as_mut(), &mut poll_cx).is_pending(),
            "the retained service continues waiting after committing its task transition",
        );

        assert!(matches!(
            runtime
                .get_task(&task_id)
                .expect("completed task remains readable")
                .task,
            fastmcp_protocol::Task::Completed { .. }
        ));
        assert_eq!(
            delivered
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .len(),
            2,
            "task creation and the fenced terminal completion each emit one notification",
        );
    }

    #[cfg(feature = "tasks")]
    struct FinalTaskCreatingTool;

    #[cfg(feature = "tasks")]
    impl ToolHandler for FinalTaskCreatingTool {
        fn definition(&self) -> Tool {
            Tool {
                name: "durable_final_task".to_owned(),
                description: Some("Creates one negotiated final task".to_owned()),
                input_schema: serde_json::json!({"type": "object"}),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(
            &self,
            _ctx: &McpContext,
            _arguments: serde_json::Value,
        ) -> McpResult<Vec<Content>> {
            Ok(vec![Content::text("exact legacy completion")])
        }

        fn call_final_outcome(
            &self,
            _ctx: &McpContext,
            _arguments: serde_json::Value,
        ) -> McpResult<FinalToolOutcome> {
            Ok(FinalToolOutcome::CreateTask {
                work_descriptor: FinalTaskWorkDescriptor::new(serde_json::json!({
                    "operation": "durable-final-task-tool",
                }))?,
                status_message: Some("accepted by negotiated tool".to_owned()),
            })
        }

        fn declares_final_tasks(&self) -> bool {
            true
        }
    }

    #[cfg(feature = "tasks")]
    fn final_task_creating_tool_request(declare_tasks: bool) -> JsonRpcRequest {
        let capabilities = if declare_tasks {
            serde_json::json!({
                "extensions": { "io.modelcontextprotocol/tasks": {} }
            })
        } else {
            serde_json::json!({})
        };
        JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({
                "_meta": {
                    "io.modelcontextprotocol/protocolVersion": MODERN_PROTOCOL_VERSION,
                    "io.modelcontextprotocol/clientCapabilities": capabilities,
                },
                "name": "durable_final_task",
                "arguments": {},
            })),
            81_i64,
        )
    }

    #[cfg(feature = "tasks")]
    struct HttpConditionalTaskOutcomeTool {
        calls: Arc<AtomicUsize>,
    }

    #[cfg(feature = "tasks")]
    impl ToolHandler for HttpConditionalTaskOutcomeTool {
        fn definition(&self) -> Tool {
            Tool {
                name: "durable_final_task".to_owned(),
                description: Some("Creates one negotiated final task".to_owned()),
                input_schema: serde_json::json!({
                    "type": "object",
                    "properties": {"createTask": {"type": "boolean"}},
                    "required": ["createTask"],
                    "unevaluatedProperties": false,
                }),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(
            &self,
            _ctx: &McpContext,
            _arguments: serde_json::Value,
        ) -> McpResult<Vec<Content>> {
            Ok(vec![Content::text("exact legacy completion")])
        }

        fn call_final_outcome(
            &self,
            ctx: &McpContext,
            arguments: serde_json::Value,
        ) -> McpResult<FinalToolOutcome> {
            self.calls.fetch_add(1, Ordering::SeqCst);
            ctx.report_progress(1.0, Some("before task capability admission"));
            if arguments
                .get("createTask")
                .and_then(serde_json::Value::as_bool)
                .is_some_and(|create_task| !create_task)
            {
                return Ok(FinalToolOutcome::Complete(
                    crate::handler::promote_legacy_tool_content(vec![Content::text(
                        "exact final non-task completion",
                    )])?,
                ));
            }
            Ok(FinalToolOutcome::CreateTask {
                work_descriptor: FinalTaskWorkDescriptor::new(serde_json::json!({
                    "operation": "durable-final-task-http-outcome",
                }))?,
                status_message: Some("requires negotiated Tasks capability".to_owned()),
            })
        }

        fn declares_final_tasks(&self) -> bool {
            true
        }
    }

    #[cfg(feature = "tasks")]
    fn final_http_task_outcome_request(
        create_task: bool,
        include_progress_marker: bool,
    ) -> JsonRpcRequest {
        let metadata = if include_progress_marker {
            serde_json::json!({
                "io.modelcontextprotocol/protocolVersion": MODERN_PROTOCOL_VERSION,
                "io.modelcontextprotocol/clientCapabilities": {},
                "progressToken": "missing-task-capability",
            })
        } else {
            serde_json::json!({
                "io.modelcontextprotocol/protocolVersion": MODERN_PROTOCOL_VERSION,
                "io.modelcontextprotocol/clientCapabilities": {},
            })
        };
        JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({
                "_meta": metadata,
                "name": "durable_final_task",
                "arguments": {"createTask": create_task},
            })),
            81_i64,
        )
    }

    #[cfg(feature = "tasks")]
    fn public_http_missing_required_capability_response(
        accept: &str,
        create_task: bool,
    ) -> (HttpResponse, usize, usize) {
        let cx = Cx::for_testing();
        let calls = Arc::new(AtomicUsize::new(0));
        let delivered = Arc::new(Mutex::new(Vec::new()));
        let endpoint = Server::new("missing-capability-http", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .tool(HttpConditionalTaskOutcomeTool {
                calls: Arc::clone(&calls),
            })
            .final_tasks(final_tasks_test_runtime(Arc::clone(&delivered)))
            .expect("final Tasks runtime must install for HTTP outcome admission")
            .test_http_endpoint("http://final.test")
            .expect("modern endpoint must build");
        let mut session = endpoint
            .open_session(&cx)
            .expect("modern endpoint session must open");
        let request = final_http_task_outcome_request(create_task, accept == "text/event-stream");
        let response = block_on(
            session.handle_async(
                &cx,
                HttpRequest::new(HttpMethod::Post, "/mcp")
                    .with_header("content-type", "application/json")
                    .with_header("accept", accept)
                    .with_header("mcp-protocol-version", MODERN_PROTOCOL_VERSION)
                    .with_header("mcp-method", "tools/call")
                    .with_header("mcp-name", "durable_final_task")
                    .with_body(
                        serde_json::to_vec(&request)
                            .expect("missing-capability request must serialize"),
                    ),
            ),
        )
        .expect("missing-capability request must be handled");
        let ServerHttpEndpointResponse::Immediate(response) = response else {
            panic!("missing capability must reject before committing a response stream");
        };
        let delivered = delivered
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .len();
        (response, calls.load(Ordering::SeqCst), delivered)
    }

    #[cfg(feature = "tasks")]
    fn assert_public_http_missing_required_capability(
        response: HttpResponse,
        handler_calls: usize,
        delivered_task_notifications: usize,
    ) {
        assert_eq!(response.status, HttpStatus::BAD_REQUEST);
        assert_eq!(
            response.headers.get("content-type").map(String::as_str),
            Some("application/json")
        );
        let response: JsonRpcResponse =
            serde_json::from_slice(&response.body).expect("rejection body must be JSON-RPC");
        assert_eq!(response.id, Some(81_i64.into()));
        assert_eq!(
            response
                .error
                .as_ref()
                .and_then(|error| error.code.as_i32()),
            Some(MISSING_REQUIRED_CLIENT_CAPABILITY_ERROR_CODE)
        );
        assert_eq!(
            response.error.and_then(|error| error.data),
            Some(serde_json::json!({
                "requiredCapabilities": {
                    "extensions": { "io.modelcontextprotocol/tasks": {} }
                }
            }))
        );
        assert_eq!(
            handler_calls, 1,
            "the declared task-capable handler must choose CreateTask before capability admission",
        );
        assert_eq!(
            delivered_task_notifications, 0,
            "rejected task creation must preserve runtime state before either endpoint representation commits",
        );
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn public_http_json_missing_required_capability_maps_to_400_before_response_commit() {
        let (response, handler_calls, delivered_task_notifications) =
            public_http_missing_required_capability_response("application/json", true);
        assert_public_http_missing_required_capability(
            response,
            handler_calls,
            delivered_task_notifications,
        );
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn public_http_sse_missing_required_capability_maps_to_400_before_stream_commit() {
        let (response, handler_calls, delivered_task_notifications) =
            public_http_missing_required_capability_response("text/event-stream", true);
        assert_public_http_missing_required_capability(
            response,
            handler_calls,
            delivered_task_notifications,
        );
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn public_http_task_capable_tool_create_task_false_preserves_complete_outcome_precedence() {
        let (response, handler_calls, delivered_task_notifications) =
            public_http_missing_required_capability_response("application/json", false);

        assert_eq!(response.status, HttpStatus::OK);
        let response: JsonRpcResponse =
            serde_json::from_slice(&response.body).expect("complete result must be JSON-RPC");
        assert!(response.error.is_none());
        assert_eq!(
            response
                .result
                .as_ref()
                .and_then(|result| result.get("resultType")),
            Some(&serde_json::json!("complete")),
        );
        assert_eq!(
            handler_calls, 1,
            "createTask:false must reach the declared task-capable handler",
        );
        assert_eq!(
            delivered_task_notifications, 0,
            "a complete outcome must not create or notify a Task",
        );
    }

    #[derive(Debug, Clone)]
    struct HttpCapabilityErrorMiddleware {
        data: serde_json::Value,
        emit_progress: bool,
    }

    impl Middleware for HttpCapabilityErrorMiddleware {
        fn on_request(
            &self,
            ctx: &McpContext,
            _request: &JsonRpcRequest,
        ) -> McpResult<MiddlewareDecision> {
            if self.emit_progress {
                ctx.report_progress(1.0, Some("before canonical capability error"));
            }
            Err(McpError::with_data(
                McpErrorCode::Custom(MISSING_REQUIRED_CLIENT_CAPABILITY_ERROR_CODE),
                "Required client capability is missing",
                self.data.clone(),
            ))
        }
    }

    #[derive(Debug, Clone, Default)]
    struct HttpSubscriptionProgressMiddleware;

    impl Middleware for HttpSubscriptionProgressMiddleware {
        fn on_request(
            &self,
            ctx: &McpContext,
            request: &JsonRpcRequest,
        ) -> McpResult<MiddlewareDecision> {
            if request.method == SUBSCRIPTIONS_LISTEN {
                ctx.report_progress(1.0, Some("before subscription acknowledgement"));
            }
            Ok(MiddlewareDecision::Continue)
        }
    }

    #[derive(Debug, Clone)]
    struct HttpSubscriptionResponseCapabilityErrorMiddleware {
        data: serde_json::Value,
    }

    impl Middleware for HttpSubscriptionResponseCapabilityErrorMiddleware {
        fn on_response(
            &self,
            _ctx: &McpContext,
            request: &JsonRpcRequest,
            response: serde_json::Value,
        ) -> McpResult<serde_json::Value> {
            if request.method == SUBSCRIPTIONS_LISTEN {
                return Err(McpError::with_data(
                    McpErrorCode::Custom(MISSING_REQUIRED_CLIENT_CAPABILITY_ERROR_CODE),
                    "Required client capability is missing",
                    self.data.clone(),
                ));
            }
            Ok(response)
        }
    }

    #[test]
    fn modern_sse_elected_representation_survives_losing_elections() {
        let (stream, _receiver) = ModernSseOutcomeGate::new();
        assert!(!stream.stream_admitted());
        assert!(stream.elect(ModernSseDispatchElection::Stream));
        assert!(stream.stream_admitted());
        assert!(
            !stream.elect(ModernSseDispatchElection::Immediate(HttpResponse::new(
                HttpStatus::BAD_REQUEST
            ),))
        );
        assert!(!stream.elect(ModernSseDispatchElection::Failed));
        assert!(
            stream.stream_admitted(),
            "the elected stream owns its terminal response"
        );

        let (immediate, _receiver) = ModernSseOutcomeGate::new();
        assert!(
            immediate.elect(ModernSseDispatchElection::Immediate(HttpResponse::new(
                HttpStatus::BAD_REQUEST
            ),))
        );
        assert!(!immediate.elect(ModernSseDispatchElection::Stream));
        assert!(
            !immediate.stream_admitted(),
            "a losing Stream cannot authorize SSE output"
        );
    }

    #[test]
    fn modern_sse_admission_elects_before_draining_bounded_pending_notifications() {
        let (outcome_gate, _receiver) = ModernSseOutcomeGate::new();
        let failed = Arc::new(AtomicBool::new(false));
        let delivered = Arc::new(Mutex::new(Vec::new()));
        let (sender, receiver) = std::sync::mpsc::sync_channel(1);
        let receiver = Arc::new(Mutex::new(receiver));
        let committed_sender: NotificationSender = {
            let outcome_gate = Arc::clone(&outcome_gate);
            let failed = Arc::clone(&failed);
            let delivered = Arc::clone(&delivered);
            let receiver = Arc::clone(&receiver);
            Arc::new(move |notification| {
                // Model a capacity-one body whose writer can drain only once
                // it receives the real Stream election.
                if outcome_gate.stream_admitted()
                    && let Ok(previous) = receiver.lock().unwrap().try_recv()
                {
                    delivered.lock().unwrap().push(previous);
                }
                if sender.try_send(notification).is_err() {
                    failed.store(true, Ordering::Release);
                }
            })
        };
        let gate = ModernSseNotificationGate {
            delivery: Mutex::new(ModernSseNotificationDelivery::Pending(Vec::new())),
            subscription_request: false,
            outcome_gate: Some(Arc::clone(&outcome_gate)),
            terminal_delivery: Arc::new(FinalSubscriptionTerminalDelivery::default()),
            committed_sender,
            commit_failed: Arc::clone(&failed),
            stream_admitted: Arc::new(AtomicBool::new(false)),
        };
        let first = JsonRpcRequest::notification(
            "notifications/progress",
            Some(serde_json::json!({
                "progressToken": "bounded-gate", "progress": 1
            })),
        );
        let second = JsonRpcRequest::notification(
            "notifications/progress",
            Some(serde_json::json!({
                "progressToken": "bounded-gate", "progress": 2
            })),
        );
        gate.publish(first.clone());
        gate.publish(second.clone());
        assert!(receiver.lock().unwrap().try_recv().is_err());
        assert!(
            !outcome_gate.stream_admitted(),
            "middleware cannot open the body"
        );
        gate.admit_handler();
        assert!(outcome_gate.stream_admitted());
        assert!(
            !failed.load(Ordering::Acquire),
            "the admitted writer must drain before the second commit"
        );
        delivered
            .lock()
            .unwrap()
            .push(receiver.lock().unwrap().try_recv().unwrap());
        assert_eq!(
            serde_json::to_string(&*delivered.lock().unwrap()).unwrap(),
            serde_json::to_string(&[first, second]).unwrap(),
        );
    }

    #[test]
    fn modern_sse_ready_election_wins_over_simultaneous_request_cancellation() {
        let cx = Cx::for_testing();
        let request_cancellation = McpRequestCancellation::new();
        let (outcome_gate, mut receiver) = ModernSseOutcomeGate::new();

        assert!(outcome_gate.elect(ModernSseDispatchElection::Stream));
        request_cancellation.cancel();

        assert!(matches!(
            block_on(await_modern_sse_dispatch_election(
                &cx,
                &request_cancellation,
                &mut receiver,
            )),
            Ok(ModernSseDispatchElection::Stream)
        ));
        assert!(
            !outcome_gate.elect(ModernSseDispatchElection::Failed),
            "the ready Stream election must remain the one linearized outcome"
        );

        let pre_election_cancellation = McpRequestCancellation::new();
        let (_unelected_gate, mut unelected_receiver) = ModernSseOutcomeGate::new();
        pre_election_cancellation.cancel();
        assert!(
            block_on(await_modern_sse_dispatch_election(
                &cx,
                &pre_election_cancellation,
                &mut unelected_receiver,
            ))
            .is_err(),
            "peer body-drop before an election must still cancel the pending writer"
        );
    }

    fn public_http_capability_error_test_server(data: serde_json::Value) -> Server {
        Server::new("http-capability-error-shape", "1.0.0")
            .mask_error_details(false)
            .middleware(HttpCapabilityErrorMiddleware {
                data,
                emit_progress: false,
            })
            .build()
    }

    #[test]
    fn public_http_sse_middleware_missing_capability_has_zero_events_and_maps_to_400() {
        let canonical_data = serde_json::json!({
            "requiredCapabilities": {
                "extensions": { "io.modelcontextprotocol/tasks": {} }
            }
        });
        let cx = Cx::for_testing();
        let endpoint = Server::new("http-middleware-capability-sse", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .mask_error_details(false)
            .middleware(HttpCapabilityErrorMiddleware {
                data: canonical_data.clone(),
                emit_progress: true,
            })
            .test_http_endpoint("http://final.test")
            .expect("modern endpoint must build");
        let mut session = endpoint
            .open_session(&cx)
            .expect("modern endpoint session must open");
        let request = JsonRpcRequest::new(
            SERVER_DISCOVER_METHOD,
            Some(serde_json::json!({
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                    "progressToken": "middleware-capability-progress",
                },
            })),
            84_i64,
        );
        let response = block_on(
            session.handle_async(
                &cx,
                HttpRequest::new(HttpMethod::Post, "/mcp")
                    .with_header("content-type", "application/json")
                    .with_header("accept", "text/event-stream")
                    .with_header("mcp-protocol-version", MODERN_PROTOCOL_VERSION)
                    .with_header("mcp-method", SERVER_DISCOVER_METHOD)
                    .with_body(
                        serde_json::to_vec(&request)
                            .expect("middleware capability request must serialize"),
                    ),
            ),
        )
        .expect("middleware capability request must be handled");
        let ServerHttpEndpointResponse::Immediate(response) = response else {
            panic!("canonical middleware error must commit neither an SSE event nor stream");
        };

        assert_eq!(response.status, HttpStatus::BAD_REQUEST);
        assert_eq!(
            response.headers.get("content-type").map(String::as_str),
            Some("application/json")
        );
        let response: JsonRpcResponse =
            serde_json::from_slice(&response.body).expect("rejection body must be JSON-RPC");
        let error = response.error.expect("middleware error must be retained");
        assert_eq!(
            error.code.as_i32(),
            Some(MISSING_REQUIRED_CLIENT_CAPABILITY_ERROR_CODE)
        );
        assert_eq!(error.data, Some(canonical_data));
    }

    #[test]
    fn public_http_modern_malformed_missing_capability_error_stays_json_rpc_ok() {
        let malformed_data = serde_json::json!({"requiredCapabilities": []});
        let request = JsonRpcRequest::new(
            SERVER_DISCOVER_METHOD,
            Some(serde_json::json!({
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                },
            })),
            82_i64,
        );
        let inbound =
            InboundRequestContext::new(Cx::for_testing(), 82, InboundRequestTransport::Http);
        let response = block_on(
            public_http_capability_error_test_server(malformed_data.clone())
                .dispatch_http_with_protocol_policy(ProtocolPolicy::ModernOnly, &inbound, &request),
        );

        assert_eq!(response.status, HttpStatus::OK);
        let response: JsonRpcResponse =
            serde_json::from_slice(&response.body).expect("lookalike response must be JSON-RPC");
        let error = response
            .error
            .expect("middleware must preserve its lookalike error");
        assert_eq!(
            error.code.as_i32(),
            Some(MISSING_REQUIRED_CLIENT_CAPABILITY_ERROR_CODE)
        );
        assert_eq!(error.data, Some(malformed_data));
    }

    #[test]
    fn public_http_legacy_only_missing_capability_error_stays_json_rpc_ok() {
        let canonical_data = serde_json::json!({
            "requiredCapabilities": {
                "extensions": { "io.modelcontextprotocol/tasks": {} }
            }
        });
        let request = JsonRpcRequest::new(
            "initialize",
            Some(serde_json::json!({
                "protocolVersion": LEGACY_PROTOCOL_VERSION,
                "capabilities": {},
                "clientInfo": {"name": "legacy-http-client", "version": "1.0.0"},
            })),
            83_i64,
        );
        let inbound =
            InboundRequestContext::new(Cx::for_testing(), 83, InboundRequestTransport::Http);
        let response = block_on(
            public_http_capability_error_test_server(canonical_data.clone())
                .dispatch_http_with_protocol_policy(ProtocolPolicy::LegacyOnly, &inbound, &request),
        );

        assert_eq!(response.status, HttpStatus::OK);
        let response: JsonRpcResponse =
            serde_json::from_slice(&response.body).expect("legacy response must be JSON-RPC");
        let error = response
            .error
            .expect("middleware must preserve its canonical error");
        assert_eq!(
            error.code.as_i32(),
            Some(MISSING_REQUIRED_CLIENT_CAPABILITY_ERROR_CODE)
        );
        assert_eq!(error.data, Some(canonical_data));
    }

    #[cfg(feature = "tasks")]
    fn unrelated_extension_registry(
        method: &str,
    ) -> (ExtensionHandlerRegistry, ServerExtensionDiscovery) {
        let extension_id = fastmcp_protocol::ExtensionId::parse("com.example/echo")
            .expect("test extension identifier must be valid");
        let mut descriptors = ExtensionDescriptorRegistry::new();
        descriptors
            .register(fastmcp_protocol::ExtensionDescriptor {
                id: extension_id.clone(),
                client_settings: fastmcp_protocol::ExtensionSettingsSchema {
                    schema_id: "example-client-v1".to_owned(),
                    codec_id: "example-client-codec-v1".to_owned(),
                },
                server_settings: fastmcp_protocol::ExtensionSettingsSchema {
                    schema_id: "example-server-v1".to_owned(),
                    codec_id: "example-server-codec-v1".to_owned(),
                },
                resolver: fastmcp_protocol::ExtensionNegotiationResolver {
                    id: "example-compatibility-v1".to_owned(),
                    version: 1,
                    fallback: fastmcp_protocol::ExtensionFallbackPolicy::RejectOneSided,
                },
                method: Some(fastmcp_protocol::ExtensionMethodDescriptor {
                    name: method.to_owned(),
                    direction: fastmcp_protocol::ExtensionDirection::ClientToServer,
                    http_era_disposition: Some(
                        fastmcp_protocol::ExtensionHttpEraDisposition::ModernExclusive,
                    ),
                    legacy_fallback: false,
                }),
                notification: None,
                result_discriminator: Some("example-result".to_owned()),
                routing_headers: Vec::new(),
                stdio_correlation: None,
            })
            .expect("unrelated extension descriptor must register");
        let mut handlers = ExtensionHandlerRegistry::new(descriptors);
        handlers
            .register(
                extension_id.clone(),
                method,
                |_context: &McpContext, parameters: serde_json::Value| {
                    Ok::<serde_json::Value, McpError>(parameters)
                },
            )
            .expect("unrelated extension handler must register");
        (
            handlers,
            ServerExtensionDiscovery {
                extensions: BTreeMap::from([(
                    extension_id,
                    fastmcp_protocol::ExtensionSettings::new(serde_json::json!({}))
                        .expect("empty unrelated extension settings must be valid"),
                )]),
            },
        )
    }

    #[cfg(feature = "tasks")]
    fn final_tasks_params(
        task_id: &fastmcp_protocol::FinalTaskId,
        settings: serde_json::Value,
    ) -> serde_json::Value {
        serde_json::json!({
            "taskId": task_id.as_str(),
            "_meta": {
                "io.modelcontextprotocol/protocolVersion": MODERN_PROTOCOL_VERSION,
                "io.modelcontextprotocol/clientCapabilities": {
                    "extensions": {
                        "io.modelcontextprotocol/tasks": settings,
                    },
                },
            },
        })
    }

    #[cfg(feature = "tasks")]
    fn final_tasks_get_params(
        task_id: &fastmcp_protocol::FinalTaskId,
        settings: serde_json::Value,
    ) -> serde_json::Value {
        serde_json::json!({
            "taskId": task_id.as_str(),
            "_meta": {
                "io.modelcontextprotocol/protocolVersion": MODERN_PROTOCOL_VERSION,
                "io.modelcontextprotocol/clientCapabilities": {
                    "extensions": {
                        "io.modelcontextprotocol/tasks": settings,
                    },
                },
            },
        })
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn configured_final_tasks_route_methods_and_typed_notifications() {
        let delivered = Arc::new(Mutex::new(Vec::new()));
        let (server, _service) = final_tasks_test_server(Arc::clone(&delivered));
        let runtime = server
            .final_task_runtime()
            .expect("configured final Tasks runtime must be retained");
        let task_id = runtime
            .create_task_with_work(
                final_tasks_test_work_descriptor(),
                Some("accepted".to_owned()),
            )
            .expect("application store must accept task before reply")
            .task
            .base()
            .task_id
            .clone();
        let notification = delivered
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .first()
            .cloned()
            .expect("durable task creation must route a typed notification");
        assert_eq!(
            serde_json::to_value(notification).expect("notification must serialize")["method"],
            fastmcp_protocol::TASK_STATUS_NOTIFICATION
        );

        let inbound =
            InboundRequestContext::new(Cx::for_testing(), 71, InboundRequestTransport::Memory);
        let get = block_on(server.dispatch_stateless(
            &inbound,
            &JsonRpcRequest::new(
                fastmcp_protocol::TASK_GET,
                Some(final_tasks_get_params(&task_id, serde_json::json!({}))),
                71_i64,
            ),
        ))
        .expect("tasks/get must respond");
        assert_eq!(
            get.result.as_ref().map(|result| &result["resultType"]),
            Some(&serde_json::json!("complete"))
        );
        assert_eq!(
            get.result.as_ref().map(|result| &result["taskId"]),
            Some(&serde_json::json!(task_id.as_str()))
        );

        let mut session = initialized_test_session(&server);
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let session_get = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            JsonRpcRequest::new(
                fastmcp_protocol::TASK_GET,
                Some(final_tasks_get_params(&task_id, serde_json::json!({}))),
                72_i64,
            ),
            &notification_sender,
            &test_request_sender(),
        ))
        .expect("session tasks/get must produce a JSON-RPC response");
        assert_eq!(
            session_get.result.as_ref().map(|result| &result["taskId"]),
            Some(&serde_json::json!(task_id.as_str())),
            "stdio/session dispatch must serve official tasks/get"
        );
        let missing = fastmcp_protocol::FinalTaskId::parse("missing-task-id-0001")
            .expect("planted missing task id");
        let session_missing = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            JsonRpcRequest::new(
                fastmcp_protocol::TASK_GET,
                Some(final_tasks_get_params(&missing, serde_json::json!({}))),
                73_i64,
            ),
            &notification_sender,
            &test_request_sender(),
        ))
        .expect("session tasks/get of an unknown id must respond");
        let missing_error = session_missing
            .error
            .as_ref()
            .expect("unknown task id must fail");
        assert_ne!(
            missing_error.code,
            i32::from(McpErrorCode::MethodNotFound).into(),
            "unknown task id is not MethodNotFound after official Tasks is installed"
        );

        let mut requests = fastmcp_protocol::TaskInputRequests::new();
        requests.insert(
            "roots".to_owned(),
            serde_json::from_value(serde_json::json!({ "method": "roots/list" }))
                .expect("typed roots request"),
        );
        runtime
            .require_input(&task_id, requests, Some("awaiting roots".to_owned()))
            .expect("caller-owned supervisor can enter input_required");
        let mut update_params = final_tasks_params(&task_id, serde_json::json!({}));
        update_params
            .as_object_mut()
            .expect("final Tasks parameters are an object")
            .insert(
                "inputResponses".to_owned(),
                serde_json::json!({ "roots": { "roots": [] } }),
            );
        let update = block_on(server.dispatch_stateless(
            &inbound,
            &JsonRpcRequest::new(
                fastmcp_protocol::tasks_extension::TASK_UPDATE,
                Some(update_params),
                71_i64,
            ),
        ))
        .expect("tasks/update must respond");
        assert_eq!(
            update.result,
            Some(serde_json::json!({ "resultType": "complete" }))
        );

        let cancel = block_on(server.dispatch_stateless(
            &inbound,
            &JsonRpcRequest::new(
                fastmcp_protocol::TASK_CANCEL,
                Some(final_tasks_get_params(&task_id, serde_json::json!({}))),
                71_i64,
            ),
        ))
        .expect("tasks/cancel must respond");
        assert_eq!(
            cancel.result,
            Some(serde_json::json!({ "resultType": "complete" }))
        );
        assert!(matches!(
            runtime
                .get_task(&task_id)
                .expect("final cancellation must remain in application storage")
                .task,
            fastmcp_protocol::Task::Cancelled(_)
        ));
        assert!(
            !runtime
                .is_cancellation_requested(&task_id)
                .expect("terminal task has no outstanding cooperative intent")
        );
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn default_built_server_serves_official_tasks_get() {
        let server = Server::new("default-tasks-server", "1.0.0").build();
        let runtime = server
            .final_task_runtime()
            .expect("default build must install an in-memory official Tasks runtime");
        let _service = start_final_tasks_test_service(runtime);
        let task_id = runtime
            .create_task_with_work(
                final_tasks_test_work_descriptor(),
                Some("accepted".to_owned()),
            )
            .expect("default store must accept a task once its service is ready")
            .task
            .base()
            .task_id
            .clone();

        let mut session = initialized_test_session(&server);
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let session_get = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            JsonRpcRequest::new(
                fastmcp_protocol::TASK_GET,
                Some(final_tasks_get_params(&task_id, serde_json::json!({}))),
                80_i64,
            ),
            &notification_sender,
            &test_request_sender(),
        ))
        .expect("default session tasks/get must produce a JSON-RPC response");
        assert_eq!(
            session_get.result.as_ref().map(|result| &result["taskId"]),
            Some(&serde_json::json!(task_id.as_str())),
            "Server::new().build() must serve official tasks/get without final_tasks()"
        );

        let missing = fastmcp_protocol::FinalTaskId::parse("missing-default-task-0001")
            .expect("planted missing task id");
        let session_missing = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            JsonRpcRequest::new(
                fastmcp_protocol::TASK_GET,
                Some(final_tasks_get_params(&missing, serde_json::json!({}))),
                81_i64,
            ),
            &notification_sender,
            &test_request_sender(),
        ))
        .expect("unknown default-runtime task id must still be a Tasks response");
        let missing_error = session_missing
            .error
            .as_ref()
            .expect("unknown task id must fail");
        assert_ne!(
            missing_error.code,
            i32::from(McpErrorCode::MethodNotFound).into(),
            "unknown id is not MethodNotFound once default official Tasks is installed"
        );
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn default_built_server_advertises_official_tasks_in_discovery() {
        let discovery = Server::new("default-tasks-discovery", "1.0.0")
            .build()
            .server_discovery()
            .expect("default server must produce discovery");
        let capabilities = serde_json::to_value(discovery.capabilities())
            .expect("discovery capabilities serialize");
        assert!(
            capabilities
                .pointer("/extensions/io.modelcontextprotocol~1tasks")
                .is_some(),
            "default build must advertise official Tasks so clients can negotiate it"
        );
    }

    // Exact-2024 era: exercises the exact-legacy completion route.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn session_dispatch_serves_legacy_completion_complete() {
        let server = Server::new("session-completion", "1.0.0")
            .completion_handler(LiveLegacyCompletionHandler)
            .build();
        let mut session = initialized_test_session(&server);
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let response = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            JsonRpcRequest::new(
                "completion/complete",
                Some(serde_json::json!({
                    "ref": {"type": "ref/prompt", "name": "deploy"},
                    "argument": {"name": "environment", "value": "sta"},
                })),
                90_i64,
            ),
            &notification_sender,
            &test_request_sender(),
        ))
        .expect("session completion/complete must produce a JSON-RPC response");
        let values = response
            .result
            .as_ref()
            .and_then(|result| result.pointer("/completion/values"))
            .cloned()
            .expect("legacy completion must return values");
        assert_eq!(values, serde_json::json!(["legacy:sta"]));

        let missing_handler = Server::new("session-completion-missing", "1.0.0").build();
        let mut missing_session = initialized_test_session(&missing_handler);
        let missing = block_on(missing_handler.dispatch_request(
            &Cx::for_testing(),
            &mut missing_session,
            JsonRpcRequest::new(
                "completion/complete",
                Some(serde_json::json!({
                    "ref": {"type": "ref/prompt", "name": "deploy"},
                    "argument": {"name": "environment", "value": "sta"},
                })),
                91_i64,
            ),
            &notification_sender,
            &test_request_sender(),
        ))
        .expect("missing completion handler must still produce a JSON-RPC response");
        let error = missing
            .error
            .as_ref()
            .expect("no completion handler is MethodNotFound");
        assert_eq!(error.code, i32::from(McpErrorCode::MethodNotFound).into());
    }

    #[test]
    fn completion_handler_is_advertised_on_initialize() {
        let with_handler = Server::new("advertise-completion", "1.0.0")
            .completion_handler(LiveLegacyCompletionHandler)
            .build();
        assert!(with_handler.capabilities().completions.is_some());
        let mut session = Session::new(
            with_handler.info.clone(),
            with_handler.capabilities().clone(),
        );
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let response = block_on(with_handler.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            initialize_test_request(1, "client", ClientCapabilities::default()),
            &notification_sender,
            &test_request_sender(),
        ))
        .expect("initialize must respond");
        assert_eq!(
            response
                .result
                .as_ref()
                .and_then(|result| result.pointer("/capabilities/completions")),
            Some(&serde_json::json!({})),
            "initialize must advertise completions when a handler is installed"
        );

        let without = Server::new("no-completion", "1.0.0").build();
        assert!(without.capabilities().completions.is_none());
    }

    // Exact-2024 era: legacy initialize completion capability.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn legacy_completion_handler_is_advertised_on_initialize_only() {
        let server = Server::new("legacy-advertise-completion", "1.0.0")
            .legacy_completion_handler(LiveLegacyCompletionHandler)
            .build();
        assert!(server.capabilities().completions.is_some());
        let mut session = Session::new(server.info.clone(), server.capabilities().clone());
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let response = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            initialize_test_request(1, "client", ClientCapabilities::default()),
            &notification_sender,
            &test_request_sender(),
        ))
        .expect("initialize must respond");
        assert_eq!(
            response
                .result
                .as_ref()
                .and_then(|result| result.pointer("/capabilities/completions")),
            Some(&serde_json::json!({})),
            "initialize must advertise completions when only the 2024 handler is installed"
        );

        let discovery = server
            .server_discovery()
            .expect("legacy-only completion server must still produce discovery");
        let capabilities = serde_json::to_value(discovery.capabilities())
            .expect("discovery capabilities serialize");
        assert!(
            capabilities.pointer("/completions").is_none(),
            "legacy-only completion must not appear on final server/discover"
        );

        let mut session = initialized_test_session(&server);
        let served = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            JsonRpcRequest::new(
                "completion/complete",
                Some(serde_json::json!({
                    "ref": {"type": "ref/prompt", "name": "deploy"},
                    "argument": {"name": "environment", "value": "sta"},
                })),
                92_i64,
            ),
            &notification_sender,
            &test_request_sender(),
        ))
        .expect("session completion/complete must produce a JSON-RPC response");
        let values = served
            .result
            .as_ref()
            .and_then(|result| result.pointer("/completion/values"))
            .cloned()
            .expect("legacy-only completion must return values");
        assert_eq!(values, serde_json::json!(["legacy:sta"]));
    }

    #[test]
    fn registered_resource_advertises_subscribe_on_initialize() {
        struct SubscribeResource;
        impl ResourceHandler for SubscribeResource {
            fn definition(&self) -> Resource {
                Resource {
                    uri: "file:///subscribe.txt".to_string(),
                    name: "subscribe".to_string(),
                    description: None,
                    mime_type: None,
                    icon: None,
                    version: None,
                    tags: vec![],
                }
            }
            fn read(&self, _ctx: &McpContext) -> McpResult<Vec<fastmcp_protocol::ResourceContent>> {
                Ok(vec![fastmcp_protocol::ResourceContent {
                    uri: "file:///subscribe.txt".to_string(),
                    mime_type: None,
                    text: Some("ok".to_string()),
                    blob: None,
                }])
            }
        }

        let server = Server::new("advertise-subscribe", "1.0.0")
            .resource(SubscribeResource)
            .build();
        assert!(
            server
                .capabilities()
                .resources
                .as_ref()
                .is_some_and(|resources| resources.subscribe)
        );
        let mut session = Session::new(server.info.clone(), server.capabilities().clone());
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let response = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            initialize_test_request(1, "client", ClientCapabilities::default()),
            &notification_sender,
            &test_request_sender(),
        ))
        .expect("initialize must respond");
        assert_eq!(
            response
                .result
                .as_ref()
                .and_then(|result| result.pointer("/capabilities/resources/subscribe")),
            Some(&serde_json::json!(true)),
            "initialize must advertise resources.subscribe once a resource is registered"
        );

        let mut session = initialized_test_session(&server);
        let subscribed = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            JsonRpcRequest::new(
                "resources/subscribe",
                Some(serde_json::json!({ "uri": "file:///subscribe.txt" })),
                93_i64,
            ),
            &notification_sender,
            &test_request_sender(),
        ))
        .expect("session resources/subscribe must produce a JSON-RPC response");
        assert!(
            subscribed.error.is_none(),
            "registered resource must be subscribable without resource_subscriptions(): {subscribed:?}"
        );
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn public_tasks_update_requires_an_id_before_the_extension_handler_can_mutate_state() {
        let delivered = Arc::new(Mutex::new(Vec::new()));
        let (server, _service) = final_tasks_test_server(Arc::clone(&delivered));
        let runtime = server
            .final_task_runtime()
            .expect("configured final Tasks runtime must be retained");
        let task_id = runtime
            .create_task_with_work(
                final_tasks_test_work_descriptor(),
                Some("accepted".to_owned()),
            )
            .expect("application store must accept task before the update")
            .task
            .base()
            .task_id
            .clone();
        let mut requests = fastmcp_protocol::TaskInputRequests::new();
        requests.insert(
            "roots".to_owned(),
            serde_json::from_value(serde_json::json!({ "method": "roots/list" }))
                .expect("typed roots request"),
        );
        runtime
            .require_input(&task_id, requests, Some("awaiting roots".to_owned()))
            .expect("caller-owned supervisor can enter input_required");
        let mut parameters = final_tasks_params(&task_id, serde_json::json!({}));
        parameters
            .as_object_mut()
            .expect("final Tasks parameters are an object")
            .insert(
                "inputResponses".to_owned(),
                serde_json::json!({ "roots": { "roots": [] } }),
            );
        let task_before = serde_json::to_vec(
            &runtime
                .get_task(&task_id)
                .expect("serialize the complete task before rejected update"),
        )
        .expect("complete task serializes before rejected update");
        let notifications_before = serde_json::to_vec(
            &*delivered
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner),
        )
        .expect("notification sequence serializes before rejected update");

        let notification = JsonRpcRequest::notification(
            fastmcp_protocol::tasks_extension::TASK_UPDATE,
            Some(parameters.clone()),
        );
        let no_response = block_on(server.dispatch_stateless(
            &InboundRequestContext::new(Cx::for_testing(), 0, InboundRequestTransport::Memory),
            &notification,
        ));
        assert!(
            no_response.is_none(),
            "an id-less extension request cannot produce a JSON-RPC response"
        );
        let task_after = serde_json::to_vec(
            &runtime
                .get_task(&task_id)
                .expect("rejected update must leave the durable task readable"),
        )
        .expect("complete task serializes after rejected update");
        let notifications_after = serde_json::to_vec(
            &*delivered
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner),
        )
        .expect("notification sequence serializes after rejected update");
        assert_eq!(
            task_after, task_before,
            "the id-less rejected update cannot alter any serialized task field"
        );
        assert_eq!(
            notifications_after, notifications_before,
            "the id-less rejected update cannot append, replace, or alter notifications"
        );

        let update = block_on(server.dispatch_stateless(
            &InboundRequestContext::new(Cx::for_testing(), 72, InboundRequestTransport::Memory),
            &JsonRpcRequest::new(
                fastmcp_protocol::tasks_extension::TASK_UPDATE,
                Some(parameters),
                72_i64,
            ),
        ))
        .expect("adding only a request id admits the same Tasks update");
        assert_eq!(
            update.result,
            Some(serde_json::json!({ "resultType": "complete" }))
        );
        assert!(matches!(
            runtime
                .get_task(&task_id)
                .expect("admitted update retains its durable result")
                .task,
            fastmcp_protocol::Task::Working(_)
        ));
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn final_tool_task_result_mutates_only_after_capability_admission_and_legacy_stays_exact() {
        let delivered = Arc::new(Mutex::new(Vec::new()));
        let delivered_for_emitter = Arc::clone(&delivered);
        let runtime = FinalTaskRuntime::in_memory(
            FinalTaskRuntimeConfig::new(60_000, Some(5_000))
                .expect("valid final Tasks timing policy"),
            Arc::new(move |notification| {
                delivered_for_emitter
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .push(notification);
            }),
        );
        let _service = start_final_tasks_test_service(&runtime);
        let server = Server::new("final-tool-task-server", "1.0.0")
            .tool(FinalTaskCreatingTool)
            .mask_error_details(true)
            .final_tasks(runtime.clone())
            .expect("final Tasks must install before task-capable tool dispatch")
            .build();
        let inbound =
            InboundRequestContext::new(Cx::for_testing(), 81, InboundRequestTransport::Memory);

        let admitted =
            block_on(server.dispatch_stateless(&inbound, &final_task_creating_tool_request(true)))
                .expect("declared final Tasks tool request must respond");
        assert!(admitted.error.is_none());
        assert_eq!(
            admitted.result.as_ref().map(|result| &result["resultType"]),
            Some(&serde_json::json!("task"))
        );
        assert_eq!(
            admitted.result.as_ref().map(|result| &result["status"]),
            Some(&serde_json::json!("working"))
        );
        let task_id = admitted
            .result
            .as_ref()
            .and_then(|result| result["taskId"].as_str())
            .and_then(|task_id| fastmcp_protocol::FinalTaskId::parse(task_id).ok())
            .expect("the task result must expose its durable task ID");
        assert_eq!(
            runtime
                .get_task(&task_id)
                .expect("the application task store must remain readable")
                .task
                .base()
                .task_id,
            task_id,
            "the admitted result must name a task already durable in the application store"
        );
        assert_eq!(
            delivered
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .len(),
            1,
            "the admitted request publishes exactly one durable task transition"
        );

        let rejected =
            block_on(server.dispatch_stateless(&inbound, &final_task_creating_tool_request(false)))
                .expect("missing-capability final tool request must respond");
        let error = rejected
            .error
            .expect("removing only the Tasks declaration must reject task creation");
        assert_eq!(
            error.code,
            MISSING_REQUIRED_CLIENT_CAPABILITY_ERROR_CODE.into()
        );
        assert_eq!(
            error.data,
            Some(serde_json::json!({
                "requiredCapabilities": {
                    "extensions": { "io.modelcontextprotocol/tasks": {} }
                }
            }))
        );
        assert_eq!(
            delivered
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .len(),
            1,
            "rejected task capability must leave durable state unchanged"
        );

        let mut legacy_session = initialized_test_session(&server);
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let legacy = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut legacy_session,
            JsonRpcRequest::new(
                "tools/call",
                Some(serde_json::json!({
                    "name": "durable_final_task",
                    "arguments": {},
                })),
                81_i64,
            ),
            &notification_sender,
            &test_request_sender(),
        ))
        .expect("exact legacy tool call must respond through its original handler surface");
        assert!(legacy.error.is_none());
        assert_eq!(
            legacy
                .result
                .as_ref()
                .and_then(|result| result.pointer("/content/0/text")),
            Some(&serde_json::json!("exact legacy completion"))
        );
        assert_eq!(
            delivered
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .len(),
            1,
            "exact MCP 2024-11-05 must never enter the final task producer"
        );
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn final_tasks_compose_with_an_existing_extension_registry_before_freeze() {
        let delivered = Arc::new(Mutex::new(Vec::new()));
        let (handlers, discovery) = unrelated_extension_registry("example/echo");
        let runtime = final_tasks_test_runtime(Arc::clone(&delivered));
        let _service = start_final_tasks_test_service(&runtime);
        let server = Server::new("composed-final-tasks-server", "1.0.0")
            .extension_registry(
                handlers,
                discovery,
                |_descriptor: &fastmcp_protocol::ExtensionDescriptor,
                 client: &fastmcp_protocol::ExtensionSettings,
                 _server: &fastmcp_protocol::ExtensionSettings|
                 -> Result<fastmcp_protocol::ExtensionSettings, ExtensionNegotiationError> {
                    Ok(client.clone())
                },
            )
            .expect("unrelated extension registry must install")
            .final_tasks(runtime)
            .expect("final Tasks must merge into the existing registry")
            .build();

        assert_eq!(
            server
                .extension_registry_receipt()
                .expect("composed registry must be frozen")
                .descriptor_count(),
            2,
            "the caller extension and official Tasks share one receipt"
        );
        let discovery = serde_json::to_value(
            server
                .server_discovery()
                .expect("composed discovery must be valid"),
        )
        .expect("composed discovery must serialize");
        assert_eq!(
            discovery.pointer("/capabilities/extensions/com.example~1echo"),
            Some(&serde_json::json!({}))
        );
        assert_eq!(
            discovery.pointer("/capabilities/extensions/io.modelcontextprotocol~1tasks"),
            Some(&serde_json::json!({}))
        );

        let runtime = server
            .final_task_runtime()
            .expect("composed final Tasks runtime must be retained");
        let task_id = runtime
            .create_task_with_work(final_tasks_test_work_descriptor(), None)
            .expect("application-owned task store must accept task")
            .task
            .base()
            .task_id
            .clone();
        // The caller extension registered with RejectOneSided, so the client
        // must declare it alongside the official Tasks extension or the whole
        // per-request negotiation (correctly) rejects.
        let mut get_params = final_tasks_get_params(&task_id, serde_json::json!({}));
        get_params
            .pointer_mut("/_meta/io.modelcontextprotocol~1clientCapabilities/extensions")
            .and_then(serde_json::Value::as_object_mut)
            .expect("baseline request declares client extensions")
            .insert("com.example/echo".to_owned(), serde_json::json!({}));
        let response = block_on(server.dispatch_stateless(
            &InboundRequestContext::new(Cx::for_testing(), 71, InboundRequestTransport::Memory),
            &JsonRpcRequest::new(fastmcp_protocol::TASK_GET, Some(get_params), 71_i64),
        ))
        .expect("merged final Tasks handler must route requests");
        assert!(response.error.is_none());
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn final_tasks_rejects_only_a_true_owned_method_collision() {
        let delivered = Arc::new(Mutex::new(Vec::new()));
        let (handlers, discovery) = unrelated_extension_registry(fastmcp_protocol::TASK_GET);
        let result = Server::new("conflicting-final-tasks-server", "1.0.0")
            .extension_registry(
                handlers,
                discovery,
                |_descriptor: &fastmcp_protocol::ExtensionDescriptor,
                 client: &fastmcp_protocol::ExtensionSettings,
                 _server: &fastmcp_protocol::ExtensionSettings|
                 -> Result<fastmcp_protocol::ExtensionSettings, ExtensionNegotiationError> {
                    Ok(client.clone())
                },
            )
            .expect("unrelated registry must install before the conflicting method is merged")
            .final_tasks(final_tasks_test_runtime(delivered));
        let error = match result {
            Ok(_) => panic!("only the duplicated tasks/get ownership must be rejected"),
            Err(error) => error,
        };
        assert!(matches!(
            error,
            ServerExtensionConfigurationError::Registry(
                fastmcp_protocol::ExtensionRegistryError::OwnershipCollision {
                    field: "method",
                    value
                }
            ) if value == fastmcp_protocol::TASK_GET
        ));
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn final_tasks_reject_one_variable_incompatible_extension_settings() {
        let delivered = Arc::new(Mutex::new(Vec::new()));
        let (server, _service) = final_tasks_test_server(Arc::clone(&delivered));
        let runtime = server
            .final_task_runtime()
            .expect("configured final Tasks runtime must be retained");
        let task_id = runtime
            .create_task_with_work(final_tasks_test_work_descriptor(), None)
            .expect("task must persist")
            .task
            .base()
            .task_id
            .clone();
        let inbound =
            InboundRequestContext::new(Cx::for_testing(), 71, InboundRequestTransport::Memory);

        let admitted = block_on(server.dispatch_stateless(
            &inbound,
            &JsonRpcRequest::new(
                fastmcp_protocol::TASK_GET,
                Some(final_tasks_get_params(&task_id, serde_json::json!({}))),
                71_i64,
            ),
        ))
        .expect("baseline final Tasks request must respond");
        assert!(admitted.error.is_none());
        let notification_count = delivered
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .len();

        let mut rejected_params = final_tasks_get_params(&task_id, serde_json::json!({}));
        *rejected_params
            .pointer_mut(
                "/_meta/io.modelcontextprotocol~1clientCapabilities/extensions/io.modelcontextprotocol~1tasks",
            )
            .expect("baseline request must contain Tasks settings") =
            serde_json::json!({ "unexpected": true });
        let rejected = block_on(server.dispatch_stateless(
            &inbound,
            &JsonRpcRequest::new(fastmcp_protocol::TASK_GET, Some(rejected_params), 71_i64),
        ))
        .expect("rejected final Tasks request must respond");
        let error = rejected
            .error
            .expect("changing only Tasks settings must reject the request");
        assert_eq!(error.code, i32::from(McpErrorCode::InvalidParams).into());
        assert_eq!(
            delivered
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .len(),
            notification_count,
            "rejected settings must not invoke the final Tasks runtime"
        );
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn legacy_dispatch_remains_isolated_from_configured_final_tasks() {
        let (server, _service) = final_tasks_test_server(Arc::new(Mutex::new(Vec::new())));
        let mut session = initialized_test_session(&server);
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();

        let response = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            JsonRpcRequest::new(
                fastmcp_protocol::TASK_GET,
                Some(serde_json::json!({ "taskId": "legacy-task" })),
                71_i64,
            ),
            &notification_sender,
            &request_sender,
        ))
        .expect("legacy request must respond");
        assert_eq!(
            response.error.map(|error| error.code),
            Some(i32::from(McpErrorCode::MethodNotFound).into())
        );
    }

    #[test]
    fn http_server_uses_its_configured_request_handler_policy() {
        let handler_config = HttpHandlerConfig {
            base_path: "/private/mcp".to_string(),
            allow_cors: false,
            cors_origins: vec!["https://trusted.example".to_string()],
            max_body_size: 321,
        };
        let server = Server::new("http-policy-test", "1.0.0")
            .http_config(
                HttpServerConfig::new()
                    .mcp_path("/private/mcp")
                    .handler_config(handler_config),
            )
            .build();

        let handler = server.configured_http_request_handler();
        let actual = handler.config();
        assert_eq!(actual.base_path, "/private/mcp");
        assert!(!actual.allow_cors);
        assert_eq!(
            actual.cors_origins,
            vec!["https://trusted.example".to_string()]
        );
        assert_eq!(actual.max_body_size, 321);

        let options = HttpRequest::new(HttpMethod::Options, "/private/mcp")
            .with_header("origin", "https://trusted.example");
        assert_eq!(
            handler.handle_options(&options).status,
            HttpStatus::METHOD_NOT_ALLOWED
        );

        let oversized = HttpRequest::new(HttpMethod::Post, "/private/mcp")
            .with_header("content-type", "application/json")
            .with_body(vec![b'x'; 322]);
        assert!(matches!(
            handler.parse_request(&oversized),
            Err(fastmcp_transport::http::HttpError::BodyTooLarge {
                size: 322,
                max: 321
            })
        ));
    }

    #[test]
    fn http_server_mcp_path_updates_the_authoritative_handler_path() {
        let config = HttpServerConfig::new().mcp_path("/single-source");
        assert_eq!(config.handler_config.base_path, "/single-source");

        let server = Server::new("http-path-test", "1.0.0")
            .http_config(config)
            .build();
        let handler = server.configured_http_request_handler();
        assert_eq!(handler.config().base_path, "/single-source");
    }

    #[tool(
        name = "http_overlap_tool",
        description = "Records concurrent overlap for HTTP tests",
        annotations(read_only)
    )]
    fn http_overlap_tool(_ctx: &McpContext) -> String {
        let metrics = http_overlap_metrics();
        let current = metrics.current.fetch_add(1, Ordering::SeqCst) + 1;
        metrics.max.fetch_max(current, Ordering::SeqCst);
        http_overlap_control().enter_and_wait();
        metrics.current.fetch_sub(1, Ordering::SeqCst);
        "overlap-ok".to_string()
    }

    #[tool(
        name = "http_auth_echo_tool_runtime",
        description = "Returns the request-scoped auth subject while recording overlap",
        annotations(read_only)
    )]
    fn http_auth_echo_tool_runtime(ctx: &McpContext) -> String {
        ctx.auth()
            .and_then(|auth| auth.subject)
            .unwrap_or_else(|| "anonymous".to_string())
    }

    #[tool(
        name = "http_stateful_increment_tool",
        description = "Increments a session counter across HTTP requests"
    )]
    fn http_stateful_increment_tool(ctx: &McpContext) -> String {
        let count: i32 = ctx.get_state("http_counter").unwrap_or(0);
        let next = count + 1;
        assert!(ctx.set_state("http_counter", next));
        format!("Counter: {next}")
    }

    #[tool(
        name = "http_current_auth_subject_tool",
        description = "Returns the current request auth subject",
        annotations(read_only)
    )]
    fn http_current_auth_subject_tool(ctx: &McpContext) -> String {
        ctx.auth()
            .and_then(|auth| auth.subject)
            .unwrap_or_else(|| "anonymous".to_string())
    }

    #[tool(
        name = "http_current_auth_subject_exclusive_tool",
        description = "Returns the current request auth subject from the exclusive path"
    )]
    fn http_current_auth_subject_exclusive_tool(ctx: &McpContext) -> String {
        ctx.auth()
            .and_then(|auth| auth.subject)
            .unwrap_or_else(|| "anonymous".to_string())
    }

    #[derive(Debug, Clone)]
    struct CapturingAuthMiddleware {
        seen: Arc<Mutex<Vec<(String, Option<String>)>>>,
    }

    impl Middleware for CapturingAuthMiddleware {
        fn on_request(
            &self,
            ctx: &McpContext,
            request: &JsonRpcRequest,
        ) -> McpResult<MiddlewareDecision> {
            self.seen
                .lock()
                .expect("captured auth middleware mutex should not be poisoned")
                .push((
                    request.method.clone(),
                    ctx.auth().and_then(|auth| auth.subject),
                ));
            Ok(MiddlewareDecision::Continue)
        }
    }

    #[derive(Debug, Clone)]
    struct OverridingAuthMiddleware {
        subject: &'static str,
    }

    impl Middleware for OverridingAuthMiddleware {
        fn on_request(
            &self,
            ctx: &McpContext,
            _request: &JsonRpcRequest,
        ) -> McpResult<MiddlewareDecision> {
            if ctx.set_auth(AuthContext::with_subject(self.subject)) {
                return Err(McpError::internal_error(
                    "middleware replaced a committed authenticated principal",
                ));
            }
            Ok(MiddlewareDecision::Continue)
        }
    }

    #[derive(Debug)]
    struct AlwaysFailAuthProvider;

    impl AuthProvider for AlwaysFailAuthProvider {
        fn authenticate(
            &self,
            _ctx: &McpContext,
            _request: AuthRequest<'_>,
        ) -> McpResult<AuthContext> {
            Err(McpError::invalid_request("auth failed"))
        }
    }

    #[derive(Debug, Clone)]
    struct RewritingErrorMiddleware;

    impl Middleware for RewritingErrorMiddleware {
        fn on_error(
            &self,
            _ctx: &McpContext,
            _request: &JsonRpcRequest,
            error: McpError,
        ) -> McpError {
            McpError::new(error.code, format!("rewritten: {}", error.message))
        }
    }

    #[derive(Debug, Clone)]
    struct ResponseCancellationRewriter;

    impl Middleware for ResponseCancellationRewriter {
        fn on_response(
            &self,
            _ctx: &McpContext,
            _request: &JsonRpcRequest,
            _response: serde_json::Value,
        ) -> McpResult<serde_json::Value> {
            Err(McpError::request_cancelled())
        }

        fn on_error(
            &self,
            _ctx: &McpContext,
            _request: &JsonRpcRequest,
            _error: McpError,
        ) -> McpError {
            McpError::internal_error("hostile cancellation rewrite")
        }
    }

    #[derive(Debug, Clone)]
    struct RejectResponseMiddleware;

    impl Middleware for RejectResponseMiddleware {
        fn on_response(
            &self,
            _ctx: &McpContext,
            _request: &JsonRpcRequest,
            _response: serde_json::Value,
        ) -> McpResult<serde_json::Value> {
            Err(McpError::internal_error(
                "response middleware rejected provisional session mutation",
            ))
        }
    }

    const EXTENSION_PANIC_CANARY: &str =
        "EXTENSION_PANIC_CANARY Bearer peer-secret\n\u{001b}[31mpayload\u{001b}[0m";

    #[derive(Debug)]
    struct PanickingAuthProvider;

    impl AuthProvider for PanickingAuthProvider {
        fn authenticate(
            &self,
            _ctx: &McpContext,
            _request: AuthRequest<'_>,
        ) -> McpResult<AuthContext> {
            panic!("{EXTENSION_PANIC_CANARY}")
        }
    }

    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    enum PanickingMiddlewareHook {
        Request,
        Response,
        Error,
    }

    type MiddlewareEvent = (&'static str, &'static str);

    #[derive(Debug, Clone)]
    struct RecordingPanicMiddleware {
        name: &'static str,
        panic_at: Option<PanickingMiddlewareHook>,
        events: Arc<Mutex<Vec<MiddlewareEvent>>>,
    }

    impl RecordingPanicMiddleware {
        fn new(
            name: &'static str,
            panic_at: Option<PanickingMiddlewareHook>,
            events: &Arc<Mutex<Vec<MiddlewareEvent>>>,
        ) -> Self {
            Self {
                name,
                panic_at,
                events: Arc::clone(events),
            }
        }

        fn record(&self, hook: &'static str) {
            self.events
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push((self.name, hook));
        }

        fn should_panic(&self, hook: PanickingMiddlewareHook) -> bool {
            self.panic_at == Some(hook)
        }
    }

    impl Middleware for RecordingPanicMiddleware {
        fn on_request(
            &self,
            _ctx: &McpContext,
            _request: &JsonRpcRequest,
        ) -> McpResult<MiddlewareDecision> {
            self.record("request");
            if self.should_panic(PanickingMiddlewareHook::Request) {
                panic!("{EXTENSION_PANIC_CANARY}");
            }
            Ok(MiddlewareDecision::Continue)
        }

        fn on_response(
            &self,
            _ctx: &McpContext,
            _request: &JsonRpcRequest,
            response: serde_json::Value,
        ) -> McpResult<serde_json::Value> {
            self.record("response");
            if self.should_panic(PanickingMiddlewareHook::Response) {
                panic!("{EXTENSION_PANIC_CANARY}");
            }
            Ok(response)
        }

        fn on_error(
            &self,
            _ctx: &McpContext,
            _request: &JsonRpcRequest,
            error: McpError,
        ) -> McpError {
            self.record("error");
            if self.should_panic(PanickingMiddlewareHook::Error) {
                panic!("{EXTENSION_PANIC_CANARY}");
            }
            error
        }
    }

    fn recorded_middleware_events(
        events: &Arc<Mutex<Vec<MiddlewareEvent>>>,
    ) -> Vec<MiddlewareEvent> {
        events
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone()
    }

    fn assert_peer_extension_error_is_sanitized(response: &JsonRpcResponse) {
        let error = response
            .error
            .as_ref()
            .expect("extension panic must produce a JSON-RPC error");
        assert_eq!(error.message, "Internal server error");
        assert_eq!(error.data, None);

        let wire = serde_json::to_string(response).expect("JSON-RPC response should serialize");
        for forbidden in [
            "EXTENSION_PANIC_CANARY",
            "Bearer",
            "peer-secret",
            "payload",
            "\\u001b",
        ] {
            assert!(
                !wire.contains(forbidden),
                "peer response exposed panic payload fragment {forbidden:?}: {wire}"
            );
        }
    }

    // ── parse_params ────────────────────────────────────────────────

    #[cfg(feature = "tasks")]
    #[test]
    fn configured_task_manager_does_not_advertise_or_enable_task_rpc_methods() {
        let server = Server::new("quarantined-task-rpc-test", "1.0.0")
            .with_task_manager(TaskManager::new().into_shared())
            .build();
        assert!(server.task_manager().is_some());
        assert!(server.capabilities().tasks.is_none());

        let mut session = initialized_test_session(&server);
        for method in [
            "tasks/list",
            "tasks/get",
            "tasks/update",
            "tasks/cancel",
            "tasks/submit",
        ] {
            let response = dispatch_test_request(&server, &mut session, method);
            let error = response
                .error
                .as_ref()
                .unwrap_or_else(|| panic!("{method} must fail closed"));
            assert_eq!(error.code, i32::from(McpErrorCode::MethodNotFound).into());
            assert!(response.result.is_none());
        }
    }

    #[test]
    fn task_rpc_quarantine_matches_exact_legacy_task_method_names() {
        assert!(is_quarantined_task_rpc("tasks/list"));
        assert!(is_quarantined_task_rpc("tasks/submit"));
        assert!(
            !is_quarantined_task_rpc("tasks/get"),
            "official final Tasks methods are not quarantined"
        );
        assert!(
            !is_quarantined_task_rpc("tasks/lists"),
            "changing only the owned method name must not quarantine an unrelated extension"
        );
    }

    #[test]
    fn notification_only_methods_reject_ids_and_bare_initialized_is_unknown() {
        let server = Server::new("notification-envelope-test", "1.0.0").build();
        let mut session = initialized_test_session(&server);

        for method in ["notifications/initialized", "notifications/cancelled"] {
            let response = dispatch_test_request(&server, &mut session, method);
            let error = response
                .error
                .unwrap_or_else(|| panic!("{method} with an id must be rejected"));
            assert_eq!(error.code, i32::from(McpErrorCode::InvalidRequest).into());
            assert!(response.result.is_none());
        }

        let response = dispatch_test_request(&server, &mut session, "initialized");
        let error = response
            .error
            .expect("the legacy bare initialized spelling must not be routed");
        assert_eq!(error.code, i32::from(McpErrorCode::MethodNotFound).into());
    }

    #[test]
    fn log_level_is_session_local_and_does_not_mutate_process_filter() {
        let server = Server::new("session-log-level-test", "1.0.0")
            .log_level(Level::Debug)
            .build();
        let mut first = initialized_test_session(&server);
        let mut second = initialized_test_session(&server);
        let process_level = log::max_level();
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();

        for (session, id, level) in [
            (&mut first, 1_i64, LogLevel::Debug),
            (&mut second, 2_i64, LogLevel::Error),
        ] {
            let request = JsonRpcRequest::new(
                "logging/setLevel",
                Some(
                    serde_json::to_value(SetLogLevelParams { level })
                        .expect("serialize log-level request"),
                ),
                id,
            );
            let response = block_on(server.dispatch_request(
                &Cx::for_testing(),
                session,
                request,
                &notification_sender,
                &request_sender,
            ))
            .expect("setLevel request must have a response");
            assert!(
                response.error.is_none(),
                "unexpected response: {response:?}"
            );
        }

        assert_eq!(first.log_level(), Some(LogLevel::Debug));
        assert_eq!(second.log_level(), Some(LogLevel::Error));
        assert_eq!(log::max_level(), process_level);
    }

    #[test]
    fn disabled_server_logging_does_not_enable_session_notifications() {
        let server = Server::new("disabled-session-log-level-test", "1.0.0")
            .log_level_filter(LevelFilter::Off)
            .build();
        let mut session = initialized_test_session(&server);
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();
        let request = JsonRpcRequest::new(
            "logging/setLevel",
            Some(
                serde_json::to_value(SetLogLevelParams {
                    level: LogLevel::Debug,
                })
                .expect("serialize log-level request"),
            ),
            3_i64,
        );

        let response = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            request,
            &notification_sender,
            &request_sender,
        ))
        .expect("setLevel request must have a response");

        assert!(
            response.error.is_none(),
            "unexpected response: {response:?}"
        );
        assert_eq!(session.log_level(), None);
    }

    #[test]
    fn panicking_log_sender_cannot_discard_response_or_leak_active_request() {
        let server = Server::new("log-sender-panic-test", "1.0.0")
            .log_level(Level::Debug)
            .build();
        let mut session = initialized_test_session(&server);
        session.set_log_level(LogLevel::Debug);
        let sender: NotificationSender =
            Arc::new(|_| panic!("LOG-SENDER-PANIC-CANARY Bearer secret\r\nforged-line"));
        let request_sender = test_request_sender();

        let response = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            JsonRpcRequest::new("ping", Some(serde_json::json!({})), 77_i64),
            &sender,
            &request_sender,
        ))
        .expect("ping must retain its response despite sender panic");

        assert!(
            response.error.is_none(),
            "unexpected response: {response:?}"
        );
        assert!(
            server
                .active_requests
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .is_empty()
        );

        let failing_server = Server::new("auth-failure-log-sender-panic-test", "1.0.0")
            .log_level(Level::Debug)
            .auth_provider(AlwaysFailAuthProvider)
            .build();
        let mut failing_session = initialized_test_session(&failing_server);
        failing_session.set_log_level(LogLevel::Debug);
        let response = block_on(failing_server.dispatch_request(
            &Cx::for_testing(),
            &mut failing_session,
            JsonRpcRequest::new("tools/list", Some(serde_json::json!({})), 78_i64),
            &sender,
            &request_sender,
        ))
        .expect("auth failure must retain its response despite sender panic");
        assert!(response.error.is_some());
        assert!(
            failing_server
                .active_requests
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .is_empty()
        );
    }

    #[test]
    fn credential_is_visible_only_to_auth_then_stripped_before_middleware() {
        #[derive(Debug, Clone)]
        struct CaptureRawAuth {
            seen: Arc<Mutex<Option<serde_json::Value>>>,
        }

        impl AuthProvider for CaptureRawAuth {
            fn authenticate(
                &self,
                _ctx: &McpContext,
                request: AuthRequest<'_>,
            ) -> McpResult<AuthContext> {
                assert!(request.access_token().is_some());
                *self
                    .seen
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner) = request.params.cloned();
                Ok(AuthContext::with_subject("fixed-test-principal"))
            }
        }

        #[derive(Debug, Clone)]
        struct CaptureSanitizedParams {
            seen: Arc<Mutex<Option<serde_json::Value>>>,
        }

        impl Middleware for CaptureSanitizedParams {
            fn on_request(
                &self,
                _ctx: &McpContext,
                request: &JsonRpcRequest,
            ) -> McpResult<MiddlewareDecision> {
                *self
                    .seen
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner) = request.params.clone();
                Ok(MiddlewareDecision::Continue)
            }
        }

        let raw = Arc::new(Mutex::new(None));
        let sanitized = Arc::new(Mutex::new(None));
        let server = Server::new("credential-custody-test", "1.0.0")
            .auth_provider(CaptureRawAuth {
                seen: Arc::clone(&raw),
            })
            .middleware(CaptureSanitizedParams {
                seen: Arc::clone(&sanitized),
            })
            .build();
        let mut session = initialized_test_session(&server);
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();

        // The fail-closed credential grammar rejects a request carrying more
        // than one recognized credential source, so each recognized location
        // proves its visible-to-auth-then-stripped custody in its own
        // single-source dispatch.
        let cases = [
            (
                91_i64,
                serde_json::json!({
                    "authorization": "Bearer top-level-secret",
                    "arguments": {
                        "token": "domain-value",
                        "nested": {"authorization": "domain-authorization"}
                    }
                }),
            ),
            (
                92_i64,
                serde_json::json!({
                    "_meta": {
                        "accessToken": "Bearer metadata-secret",
                        "trace": "preserved-metadata"
                    }
                }),
            ),
            (
                93_i64,
                serde_json::json!({
                    "headers": {
                        "Authorization": "Bearer header-secret",
                        "x-preserved": "yes"
                    }
                }),
            ),
        ];
        for (id, params) in cases {
            let request = JsonRpcRequest::new("tools/list", Some(params.clone()), id);
            let response = block_on(server.dispatch_request(
                &Cx::for_testing(),
                &mut session,
                request,
                &notification_sender,
                &request_sender,
            ))
            .expect("authenticated tools/list must respond");
            assert!(
                response.error.is_none(),
                "unexpected response for id {id}: {response:?}"
            );

            let raw = raw
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .take()
                .expect("auth provider must receive raw params");
            assert_eq!(raw, params, "auth must see the unstripped params");

            let sanitized = sanitized
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .take()
                .expect("middleware must receive sanitized params");
            match id {
                91 => {
                    assert!(sanitized.get("authorization").is_none());
                    assert_eq!(sanitized["arguments"]["token"], "domain-value");
                    assert_eq!(
                        sanitized["arguments"]["nested"]["authorization"],
                        "domain-authorization"
                    );
                }
                92 => {
                    assert!(sanitized["_meta"].get("accessToken").is_none());
                    assert_eq!(sanitized["_meta"]["trace"], "preserved-metadata");
                }
                _ => {
                    assert!(sanitized["headers"].get("Authorization").is_none());
                    assert_eq!(sanitized["headers"]["x-preserved"], "yes");
                }
            }
        }
    }

    // Exact-2024 era: exact-2024 dispatch.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn exact_2024_dispatch_without_transport_custody_still_evaluates_auth_provider() {
        let verifier = StaticTokenVerifier::new([(
            "good-token",
            AuthContext::with_subject("legacy-stdio-owner"),
        )])
        .expect("valid verifier configuration")
        .with_allowed_schemes(["Bearer"])
        .expect("valid scheme configuration");
        let server = Server::new("legacy-stdio-auth", "1.0.0")
            .auth_provider(TokenAuthProvider::new(verifier))
            .build();
        let session_principal = crate::session::SessionPrincipalBinding::default();
        let missing = JsonRpcRequest::new("tools/list", None, 1_i64);
        let missing_dispatch = fastmcp_core::block_on(server.dispatch_legacy_2024(
            &Cx::for_testing(),
            1,
            &session_principal,
            None,
            None,
            &missing,
            None,
            None,
        ))
        .expect("missing-token admission still returns a dispatch record");
        let missing_error = missing_dispatch
            .result
            .expect_err("exact-2024 tools/list without a token must fail closed");
        assert_eq!(missing_error.code, McpErrorCode::ResourceForbidden);

        let wrong = JsonRpcRequest::new(
            "tools/list",
            Some(serde_json::json!({"authorization": "Bearer wrong-token"})),
            2_i64,
        );
        let wrong_dispatch = fastmcp_core::block_on(server.dispatch_legacy_2024(
            &Cx::for_testing(),
            1,
            &session_principal,
            None,
            None,
            &wrong,
            None,
            None,
        ))
        .expect("wrong-token admission still returns a dispatch record");
        let wrong_error = wrong_dispatch
            .result
            .expect_err("exact-2024 tools/list with the wrong token must fail closed");
        assert_eq!(wrong_error.code, McpErrorCode::ResourceForbidden);

        let admitted = JsonRpcRequest::new(
            "tools/list",
            Some(serde_json::json!({"authorization": "Bearer good-token"})),
            3_i64,
        );
        let dispatch = fastmcp_core::block_on(server.dispatch_legacy_2024(
            &Cx::for_testing(),
            1,
            &session_principal,
            None,
            None,
            &admitted,
            None,
            None,
        ))
        .expect("exact-2024 tools/list with the admitted token must dispatch");
        dispatch
            .result
            .expect("admitted exact-2024 tools/list must succeed");
    }

    #[test]
    fn auth_provider_covers_initialize_ping_and_control_notifications() {
        #[derive(Debug, Clone)]
        struct RecordingAuthProvider {
            methods: Arc<Mutex<Vec<String>>>,
        }

        impl AuthProvider for RecordingAuthProvider {
            fn authenticate(
                &self,
                _ctx: &McpContext,
                request: AuthRequest<'_>,
            ) -> McpResult<AuthContext> {
                self.methods
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .push(request.method.to_string());
                Ok(AuthContext::with_subject("connection-owner"))
            }
        }

        let methods = Arc::new(Mutex::new(Vec::new()));
        let server = Server::new("auth-all-methods-test", "1.0.0")
            .auth_provider(RecordingAuthProvider {
                methods: Arc::clone(&methods),
            })
            .build();
        let mut session = Session::new(server.info.clone(), server.capabilities.clone());
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();

        let initialize = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            initialize_test_request(
                101,
                "authenticated-client",
                fastmcp_protocol::ClientCapabilities::default(),
            ),
            &notification_sender,
            &request_sender,
        ))
        .expect("initialize request must respond");
        assert!(initialize.error.is_none());

        assert!(
            block_on(server.dispatch_request(
                &Cx::for_testing(),
                &mut session,
                JsonRpcRequest::notification("notifications/initialized", None),
                &notification_sender,
                &request_sender,
            ))
            .is_none()
        );

        let ping = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            JsonRpcRequest::new("ping", Some(serde_json::json!({})), 102_i64),
            &notification_sender,
            &request_sender,
        ))
        .expect("ping request must respond");
        assert!(ping.error.is_none());

        assert!(
            block_on(
                server.dispatch_request(
                    &Cx::for_testing(),
                    &mut session,
                    JsonRpcRequest::notification(
                        "notifications/cancelled",
                        Some(
                            serde_json::to_value(CancelledParams {
                                request_id: RequestId::Number(999),
                                reason: None,
                                meta: None,
                            })
                            .expect("serialize cancellation"),
                        ),
                    ),
                    &notification_sender,
                    &request_sender,
                )
            )
            .is_none()
        );

        assert_eq!(
            *methods
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner),
            vec![
                "initialize",
                "notifications/initialized",
                "ping",
                "notifications/cancelled",
            ]
        );
    }

    #[test]
    fn malformed_or_ambiguous_credentials_never_reach_the_provider() {
        #[derive(Debug, Clone)]
        struct CountingAuthProvider {
            calls: Arc<AtomicUsize>,
        }

        impl AuthProvider for CountingAuthProvider {
            fn authenticate(
                &self,
                _ctx: &McpContext,
                _request: AuthRequest<'_>,
            ) -> McpResult<AuthContext> {
                self.calls.fetch_add(1, Ordering::SeqCst);
                Ok(AuthContext::with_subject("must-not-run"))
            }
        }

        #[derive(Debug, Clone)]
        struct CapturingAdmissionError {
            seen: Arc<Mutex<Vec<(Option<serde_json::Value>, McpError)>>>,
        }

        impl Middleware for CapturingAdmissionError {
            fn on_error(
                &self,
                _ctx: &McpContext,
                request: &JsonRpcRequest,
                error: McpError,
            ) -> McpError {
                self.seen
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .push((request.params.clone(), error.clone()));
                error
            }
        }

        let calls = Arc::new(AtomicUsize::new(0));
        let seen = Arc::new(Mutex::new(Vec::new()));
        let server = Server::new("credential-admission-test", "1.0.0")
            .auth_provider(CountingAuthProvider {
                calls: Arc::clone(&calls),
            })
            .middleware(CapturingAdmissionError {
                seen: Arc::clone(&seen),
            })
            .build();
        let mut session = initialized_test_session(&server);
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();
        let cases = [
            (
                Some("Bearer native"),
                serde_json::json!({
                    "authorization": "Bearer in-band",
                    "cursor": "preserved"
                }),
            ),
            (
                None,
                serde_json::json!({
                    "authorization": "Bearer first",
                    "_meta": {"accessToken": "Bearer second"},
                    "cursor": "preserved"
                }),
            ),
            (Some("Bearer"), serde_json::json!({"cursor": "preserved"})),
        ];

        for (index, (native, params)) in cases.into_iter().enumerate() {
            let response = block_on(server.handle_request_internal(
                &Cx::for_testing(),
                &mut session,
                JsonRpcRequest::new(
                    "tools/list",
                    Some(params),
                    i64::try_from(index + 1).expect("bounded test request ID"),
                ),
                &notification_sender,
                &request_sender,
                None,
                native,
            ))
            .map(|handled| handled.finalize_for_return(&mut session))
            .expect("request must receive an authentication error");
            let error = response.error.expect("authentication must fail");
            assert_eq!(
                error.code,
                i32::from(McpErrorCode::ResourceForbidden).into()
            );
            assert_eq!(error.message, "Authentication failed");
            assert!(error.data.is_none());
        }

        assert_eq!(calls.load(Ordering::SeqCst), 0);
        let seen = seen
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert_eq!(seen.len(), 3);
        for (params, error) in seen.iter() {
            assert_eq!(error.message, "Authentication failed");
            assert!(error.data.is_none());
            let params = params.as_ref().expect("non-credential params remain");
            assert_eq!(params["cursor"], "preserved");
            let wire = serde_json::to_string(params).expect("serialize sanitized params");
            assert!(!wire.contains("Bearer"));
            assert!(!wire.contains("first"));
            assert!(!wire.contains("second"));
            assert!(!wire.contains("native"));
        }
    }

    // Exact-2024 era: legacy cancellation control-notification authentication.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn cancellation_control_cannot_claim_an_unbound_session_principal() {
        let server = Server::new("cancel-control-owner-test", "1.0.0").build();
        let session = Session::new(server.info.clone(), server.capabilities.clone());
        let binding = session.principal_binding();
        let mut cancellation = JsonRpcRequest::notification(
            "notifications/cancelled",
            Some(
                serde_json::to_value(CancelledParams {
                    request_id: RequestId::Number(17),
                    reason: None,
                    meta: None,
                })
                .expect("serialize cancellation"),
            ),
        );

        let error = server
            .authenticate_cancelled_control_notification(
                &Cx::for_testing(),
                &binding,
                ProtocolEra::Legacy2024,
                &mut cancellation,
                None,
            )
            .expect_err("a control frame must not establish session ownership");
        assert_eq!(error.code, McpErrorCode::ResourceForbidden);

        let admitted_anonymous = auth::principal_fingerprint(None).expect("bounded fingerprint");
        assert!(binding.bind_or_verify(admitted_anonymous));
        let mut cancellation = JsonRpcRequest::notification(
            "notifications/cancelled",
            Some(
                serde_json::to_value(CancelledParams {
                    request_id: RequestId::Number(17),
                    reason: None,
                    meta: None,
                })
                .expect("serialize cancellation"),
            ),
        );
        assert!(
            server
                .authenticate_cancelled_control_notification(
                    &Cx::for_testing(),
                    &binding,
                    ProtocolEra::Legacy2024,
                    &mut cancellation,
                    None,
                )
                .is_ok()
        );
    }

    #[test]
    fn failed_initialize_auth_does_not_initialize_session() {
        let server = Server::new("initialize-auth-failure-test", "1.0.0")
            .auth_provider(AlwaysFailAuthProvider)
            .build();
        let mut session = Session::new(server.info.clone(), server.capabilities.clone());
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();

        let response = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            initialize_test_request(
                103,
                "unauthenticated-client",
                fastmcp_protocol::ClientCapabilities::default(),
            ),
            &notification_sender,
            &request_sender,
        ))
        .expect("initialize auth failure must respond");

        assert!(response.error.is_some());
        assert!(!session.is_initialized());
    }

    // Extension panic-containment regressions.
    #[test]
    fn auth_provider_panic_is_counted_sanitized_and_runs_global_reverse_cleanup() {
        let events = Arc::new(Mutex::new(Vec::new()));
        let server = Server::new("auth-panic-containment-test", "1.0.0")
            .auth_provider(PanickingAuthProvider)
            .middleware(RecordingPanicMiddleware::new("first", None, &events))
            .middleware(RecordingPanicMiddleware::new("second", None, &events))
            .middleware(RecordingPanicMiddleware::new("third", None, &events))
            .build();
        let mut session = initialized_test_session(&server);
        let panic_count_before = REDACTED_EXTENSION_PANIC_COUNT.load(Ordering::Relaxed);

        let response = dispatch_test_request(&server, &mut session, "tools/list");

        let panic_count_after = REDACTED_EXTENSION_PANIC_COUNT.load(Ordering::Relaxed);
        assert!(
            panic_count_after > panic_count_before,
            "the installed redaction hook must count the contained auth-provider panic"
        );
        assert_peer_extension_error_is_sanitized(&response);
        assert_eq!(
            recorded_middleware_events(&events),
            vec![("third", "error"), ("second", "error"), ("first", "error"),]
        );
    }

    #[test]
    fn middleware_on_request_panic_runs_entered_stack_reverse_cleanup() {
        let events = Arc::new(Mutex::new(Vec::new()));
        let server = Server::new("middleware-request-panic-test", "1.0.0")
            .middleware(RecordingPanicMiddleware::new("first", None, &events))
            .middleware(RecordingPanicMiddleware::new(
                "second",
                Some(PanickingMiddlewareHook::Request),
                &events,
            ))
            .middleware(RecordingPanicMiddleware::new("third", None, &events))
            .build();
        let mut session = initialized_test_session(&server);

        let response = dispatch_test_request(&server, &mut session, "ping");

        assert_peer_extension_error_is_sanitized(&response);
        assert_eq!(
            recorded_middleware_events(&events),
            vec![
                ("first", "request"),
                ("second", "request"),
                ("second", "error"),
                ("first", "error"),
            ]
        );
    }

    #[test]
    fn middleware_on_response_panic_runs_full_entered_stack_reverse_cleanup() {
        let events = Arc::new(Mutex::new(Vec::new()));
        let server = Server::new("middleware-response-panic-test", "1.0.0")
            .middleware(RecordingPanicMiddleware::new("first", None, &events))
            .middleware(RecordingPanicMiddleware::new(
                "second",
                Some(PanickingMiddlewareHook::Response),
                &events,
            ))
            .middleware(RecordingPanicMiddleware::new("third", None, &events))
            .build();
        let mut session = initialized_test_session(&server);

        let response = dispatch_test_request(&server, &mut session, "ping");

        assert_peer_extension_error_is_sanitized(&response);
        assert_eq!(
            recorded_middleware_events(&events),
            vec![
                ("first", "request"),
                ("second", "request"),
                ("third", "request"),
                ("third", "response"),
                ("second", "response"),
                ("third", "error"),
                ("second", "error"),
                ("first", "error"),
            ]
        );
    }

    #[test]
    fn middleware_response_cancellation_cannot_be_rewritten_by_error_hook() {
        let server = Server::new("middleware-response-cancellation-test", "1.0.0")
            .middleware(ResponseCancellationRewriter)
            .build();
        let mut session = initialized_test_session(&server);

        let response = dispatch_test_request(&server, &mut session, "ping");

        let error = response
            .error
            .expect("response-stage cancellation must remain an error");
        assert_eq!(error.code, i32::from(McpErrorCode::RequestCancelled).into());
        assert_eq!(error.message, "Request cancelled");
        assert!(!error.message.contains("hostile"));
    }

    #[test]
    fn middleware_on_error_panic_does_not_skip_remaining_reverse_cleanup() {
        let events = Arc::new(Mutex::new(Vec::new()));
        let server = Server::new("middleware-error-panic-test", "1.0.0")
            .middleware(RecordingPanicMiddleware::new("first", None, &events))
            .middleware(RecordingPanicMiddleware::new(
                "second",
                Some(PanickingMiddlewareHook::Error),
                &events,
            ))
            .middleware(RecordingPanicMiddleware::new("third", None, &events))
            .build();
        let mut session = initialized_test_session(&server);

        let response = dispatch_test_request(&server, &mut session, "unknown/test-method");

        assert_peer_extension_error_is_sanitized(&response);
        assert_eq!(
            recorded_middleware_events(&events),
            vec![
                ("first", "request"),
                ("second", "request"),
                ("third", "request"),
                ("third", "error"),
                ("second", "error"),
                ("first", "error"),
            ]
        );
    }

    // Parameter parsing regressions.
    #[test]
    fn parse_params_none_returns_error() {
        let result = parse_params::<serde_json::Value>(None);
        let err = result.unwrap_err();
        assert!(err.message.contains("Missing required parameters"));
    }

    #[test]
    fn parse_params_invalid_json_returns_error() {
        // Pass a string where a struct is expected
        let result = parse_params::<ListToolsParams>(Some(serde_json::json!("not_an_object")));
        assert!(result.is_err());
    }

    #[test]
    fn parse_params_valid_json_succeeds() {
        let result = parse_params::<ReadResourceParams>(Some(serde_json::json!({"uri": "x://y"})));
        let params = result.unwrap();
        assert_eq!(params.uri, "x://y");
    }

    // ── parse_params_or_default ─────────────────────────────────────

    #[test]
    fn parse_params_or_default_none_returns_default() {
        let result = parse_params_or_default::<ListToolsParams>(None);
        let params = result.unwrap();
        assert!(params.cursor.is_none());
    }

    #[test]
    fn parse_params_or_default_invalid_json_returns_error() {
        let result =
            parse_params_or_default::<ListToolsParams>(Some(serde_json::json!("bad_input")));
        assert!(result.is_err());
    }

    #[test]
    fn parse_params_or_default_valid_json_succeeds() {
        let result =
            parse_params_or_default::<ListToolsParams>(Some(serde_json::json!({"cursor": "abc"})));
        let params = result.unwrap();
        assert_eq!(params.cursor.as_deref(), Some("abc"));
    }

    // ── request_id_to_u64 ───────────────────────────────────────────

    #[test]
    fn request_id_to_u64_number() {
        let id = RequestId::Number(42);
        assert_eq!(request_id_to_u64(Some(&id)), 42);
    }

    #[test]
    fn request_id_to_u64_string() {
        let id = RequestId::String("req-123".to_string());
        let result = request_id_to_u64(Some(&id));
        assert_ne!(result, 0);
    }

    #[test]
    fn request_id_to_u64_none() {
        assert_eq!(request_id_to_u64(None), 0);
    }

    // ── stable_hash_request_id ──────────────────────────────────────

    #[test]
    fn stable_hash_is_deterministic() {
        let h1 = stable_hash_request_id("test");
        let h2 = stable_hash_request_id("test");
        assert_eq!(h1, h2);
    }

    #[test]
    fn stable_hash_never_returns_zero() {
        // Empty string and various inputs should never produce 0
        assert_ne!(stable_hash_request_id(""), 0);
        assert_ne!(stable_hash_request_id("a"), 0);
    }

    #[test]
    fn stable_hash_different_inputs_differ() {
        let h1 = stable_hash_request_id("alpha");
        let h2 = stable_hash_request_id("beta");
        assert_ne!(h1, h2);
    }

    #[test]
    fn dispatch_queue_reservation_spans_dispatch_until_response_completion() {
        let queue = DispatchQueueState::default();
        let request_id = RequestId::String("linearized-request".to_string());

        assert!(queue.admit(&request_id, true));
        let cancellation = queue
            .admitted_request_cancellation(&request_id)
            .expect("admitted requests retain their cancellation authority");
        assert!(!queue.begin_dispatch(&request_id));
        assert!(
            !queue.admit(&request_id, true),
            "an active request must retain its queue reservation"
        );
        assert_eq!(
            queue.cancel_reserved(&request_id),
            DispatchCancellationDisposition::Accepted,
            "an active request must retain the authority admitted at queue entry"
        );
        assert!(cancellation.is_cancel_requested());

        queue.discard(&request_id);
        assert!(
            queue.admit(&request_id, true),
            "the id may be reused only after response completion releases it"
        );
    }

    #[test]
    fn correlated_response_drain_completes_only_after_the_reservation_is_discarded() {
        let queue = DispatchQueueState::default();
        let request_id = RequestId::String("pending-response".to_owned());
        assert!(queue.admit(&request_id, true));
        assert!(
            !queue.wait_for_correlated_response_drain(Duration::ZERO),
            "an admitted response reservation prevents an immediate drain"
        );
        queue.discard(&request_id);
        assert!(
            queue.wait_for_correlated_response_drain(Duration::ZERO),
            "discarding the response reservation completes the drain"
        );
    }

    #[test]
    fn queued_initialize_ignores_peer_cancellation_and_remains_dispatchable() {
        let queue = DispatchQueueState::default();
        let initialize_id = RequestId::Number(6);

        assert!(queue.admit(&initialize_id, false));
        assert_eq!(
            queue.cancel_reserved(&initialize_id),
            DispatchCancellationDisposition::Protected,
            "peer cancellation must not erase a queued initialize request"
        );
        assert!(
            !queue.begin_dispatch(&initialize_id),
            "the unchanged initialize request must remain ready to dispatch"
        );
        queue.discard(&initialize_id);
    }

    #[derive(Clone, Copy)]
    enum QueuedToActiveProbeEra {
        Legacy2024,
        Modern2026,
    }

    fn queued_to_active_cancellation_probe(
        era: QueuedToActiveProbeEra,
        cancelled_id: RequestId,
    ) -> (DispatchCancellationDisposition, bool, bool) {
        let queue = Arc::new(DispatchQueueState::default());
        let request_id = RequestId::Integer("7e0".to_owned());
        assert!(queue.admit(&request_id, true));

        // The modern child must share the request authority created at queue
        // admission; exact-2024 obtains that authority through its adapter.
        let modern_reservation = matches!(era, QueuedToActiveProbeEra::Modern2026).then(|| {
            assert!(queue.reserve_modern_slot());
            ModernDispatchReservation::new(
                Arc::clone(&queue),
                Some(request_id.clone()),
                0,
                Arc::new(AtomicBool::new(false)),
            )
        });
        let cancellation = modern_reservation.as_ref().map_or_else(
            || {
                queue
                    .admitted_request_cancellation(&RequestId::Number(7))
                    .expect("numeric aliases must select the admitted cancellation authority")
            },
            ModernDispatchReservation::cancellation,
        );
        let (started_sender, started_receiver) = sync_channel(1);
        let (release_sender, release_receiver) = sync_channel(1);
        let (result_sender, result_receiver) = sync_channel(1);
        let worker_queue = Arc::clone(&queue);
        let worker_request_id = request_id.clone();

        let worker = thread::spawn(move || {
            started_sender
                .send(())
                .expect("queued-to-active worker must report its gate");
            release_receiver
                .recv_timeout(Duration::from_secs(2))
                .expect("queued-to-active worker release must be bounded");
            let cancelled = match era {
                QueuedToActiveProbeEra::Legacy2024 => {
                    worker_queue.begin_dispatch(&worker_request_id)
                }
                QueuedToActiveProbeEra::Modern2026 => matches!(
                    worker_queue.begin_modern_dispatch(Some(&worker_request_id)),
                    ModernDispatchStart::Cancelled
                ),
            };
            result_sender
                .send(cancelled)
                .expect("queued-to-active worker must report its dispatch outcome");
        });

        started_receiver
            .recv_timeout(Duration::from_secs(2))
            .expect("queued-to-active worker must reach the cancellation gate");
        let disposition = queue.cancel_reserved(&cancelled_id);
        release_sender
            .send(())
            .expect("queued-to-active worker must remain available for release");
        let cancelled_before_dispatch = result_receiver
            .recv_timeout(Duration::from_secs(2))
            .expect("queued-to-active dispatch result must be bounded");
        worker
            .join()
            .expect("queued-to-active worker must not panic");

        (
            disposition,
            cancelled_before_dispatch,
            cancellation.is_cancel_requested(),
        )
    }

    #[test]
    fn queued_to_active_cancellation_admits_the_exact_id_for_modern_and_legacy() {
        for era in [
            QueuedToActiveProbeEra::Legacy2024,
            QueuedToActiveProbeEra::Modern2026,
        ] {
            let (disposition, cancelled_before_dispatch, cancellation_observed) =
                queued_to_active_cancellation_probe(era, RequestId::Integer("7.0".to_owned()));

            assert_eq!(disposition, DispatchCancellationDisposition::Accepted);
            assert!(cancelled_before_dispatch);
            assert!(cancellation_observed);
        }
    }

    #[test]
    fn queued_to_active_cancellation_rejects_one_id_negative_for_modern_and_legacy() {
        for era in [
            QueuedToActiveProbeEra::Legacy2024,
            QueuedToActiveProbeEra::Modern2026,
        ] {
            let (disposition, cancelled_before_dispatch, cancellation_observed) =
                queued_to_active_cancellation_probe(era, RequestId::Integer("8e0".to_owned()));

            assert_eq!(disposition, DispatchCancellationDisposition::NotOwned);
            assert!(!cancelled_before_dispatch);
            assert!(!cancellation_observed);
        }
    }

    // Exact-2024 era: the legacy loop's dispatch-queue stop state.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn dispatch_queue_stop_rejects_admission_and_cancels_queued_start() {
        let queue = DispatchQueueState::default();
        let queued = RequestId::Number(7);
        assert!(queue.admit(&queued, true));

        queue.stop();

        assert!(queue.is_stopping());
        assert!(queue.begin_dispatch(&queued));
        assert!(!queue.admit(&RequestId::Number(8), true));
    }

    #[test]
    fn dispatch_queue_enforces_and_releases_aggregate_byte_budget() {
        let queue = DispatchQueueState::default();

        assert!(queue.reserve_queued_bytes(MAX_DISPATCH_QUEUE_BYTES));
        assert!(!queue.reserve_queued_bytes(1));
        queue.release_queued_bytes(MAX_DISPATCH_QUEUE_BYTES / 2);
        assert!(queue.reserve_queued_bytes(MAX_DISPATCH_QUEUE_BYTES / 2));
        assert!(!queue.reserve_queued_bytes(usize::MAX));

        queue.release_queued_bytes(MAX_DISPATCH_QUEUE_BYTES);
        queue.stop();
        assert!(!queue.reserve_queued_bytes(1));
    }

    #[test]
    fn dispatch_request_measurement_matches_wire_serialization() {
        let request = JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({"payload": "bounded"})),
            7_i64,
        );
        assert_eq!(
            measure_dispatch_request(&request),
            Some(serde_json::to_vec(&request).unwrap().len())
        );
    }

    // ── RequestCompletion ───────────────────────────────────────────

    #[test]
    fn request_completion_new_is_not_done() {
        let rc = RequestCompletion::new();
        assert!(!rc.is_done());
    }

    #[test]
    fn request_completion_mark_done_sets_done() {
        let rc = RequestCompletion::new();
        rc.mark_done();
        assert!(rc.is_done());
    }

    #[test]
    fn request_completion_mark_done_idempotent() {
        let rc = RequestCompletion::new();
        rc.mark_done();
        rc.mark_done(); // should not panic
        assert!(rc.is_done());
    }

    #[test]
    fn request_completion_wait_timeout_returns_true_if_done() {
        let rc = RequestCompletion::new();
        rc.mark_done();
        assert!(rc.wait_timeout(Duration::from_millis(10)));
    }

    #[test]
    fn request_completion_wait_timeout_returns_false_if_not_done() {
        let rc = RequestCompletion::new();
        assert!(!rc.wait_timeout(Duration::from_millis(10)));
    }

    // ── DuplicateBehavior ───────────────────────────────────────────

    #[test]
    fn duplicate_behavior_default_is_warn() {
        assert_eq!(DuplicateBehavior::default(), DuplicateBehavior::Warn);
    }

    #[test]
    fn duplicate_behavior_debug_and_clone() {
        let b = DuplicateBehavior::Error;
        let debug = format!("{:?}", b);
        assert!(debug.contains("Error"));
        let cloned = b;
        assert_eq!(cloned, DuplicateBehavior::Error);
    }

    #[test]
    fn duplicate_behavior_all_variants_are_distinct() {
        assert_ne!(DuplicateBehavior::Error, DuplicateBehavior::Warn);
        assert_ne!(DuplicateBehavior::Warn, DuplicateBehavior::Replace);
        assert_ne!(DuplicateBehavior::Replace, DuplicateBehavior::Ignore);
    }

    // ── LoggingConfig ───────────────────────────────────────────────

    #[test]
    fn logging_config_default_values() {
        let config = LoggingConfig::default();
        assert_eq!(config.level, LevelFilter::Info);
        assert!(config.timestamps);
        assert!(config.targets);
        assert!(!config.file_line);
    }

    // Exact-2024 era: legacy logging/setLevel level mapping.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn legacy_logging_maps_all_eight_levels_without_losing_severity() {
        for (wire, ceiling, expected) in [
            ("debug", LevelFilter::Debug, LogLevel::Debug),
            ("info", LevelFilter::Info, LogLevel::Info),
            ("notice", LevelFilter::Info, LogLevel::Notice),
            ("warning", LevelFilter::Warn, LogLevel::Warning),
            ("error", LevelFilter::Error, LogLevel::Error),
            ("critical", LevelFilter::Error, LogLevel::Critical),
            ("alert", LevelFilter::Error, LogLevel::Alert),
            ("emergency", LevelFilter::Error, LogLevel::Emergency),
        ] {
            assert_eq!(map_legacy_log_level(wire, ceiling), Some(expected));
        }
    }

    #[test]
    fn legacy_set_log_level_preserves_all_eight_levels_when_unclamped() {
        let server = Server::new("legacy-log-levels", "1.0.0")
            .log_level(Level::Debug)
            .build();
        let mut session = initialized_test_session(&server);

        for level in [
            LogLevel::Debug,
            LogLevel::Info,
            LogLevel::Notice,
            LogLevel::Warning,
            LogLevel::Error,
            LogLevel::Critical,
            LogLevel::Alert,
            LogLevel::Emergency,
        ] {
            server.handle_set_log_level(&mut session, SetLogLevelParams { level });
            assert_eq!(session.log_level(), Some(level));
        }
    }

    // Exact-2024 era: legacy logging/setLevel level mapping.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn legacy_logging_clamps_to_server_ceiling_and_off() {
        assert_eq!(
            map_legacy_log_level("notice", LevelFilter::Warn),
            Some(LogLevel::Warning)
        );
        assert_eq!(
            map_legacy_log_level("error", LevelFilter::Warn),
            Some(LogLevel::Error)
        );
        assert_eq!(map_legacy_log_level("emergency", LevelFilter::Off), None);
        assert_eq!(
            map_legacy_log_level("not-a-level", LevelFilter::Error),
            None
        );
    }

    // ── LifespanHooks ───────────────────────────────────────────────

    #[test]
    fn lifespan_hooks_new_has_no_hooks() {
        let hooks = LifespanHooks::new();
        assert!(hooks.on_startup.is_none());
        assert!(hooks.on_shutdown.is_none());
    }

    // ── log_level_rank ──────────────────────────────────────────────

    #[test]
    fn log_level_rank_ordering() {
        for (level, expected_rank) in [
            (LogLevel::Debug, 1),
            (LogLevel::Info, 2),
            (LogLevel::Notice, 3),
            (LogLevel::Warning, 4),
            (LogLevel::Error, 5),
            (LogLevel::Critical, 6),
            (LogLevel::Alert, 7),
            (LogLevel::Emergency, 8),
        ] {
            assert_eq!(Server::log_level_rank(level), expected_rank);
        }
    }

    // ── ActiveRequestGuard ──────────────────────────────────────────

    #[test]
    fn active_request_pending_activation_preserves_parent_and_sibling() {
        active_request_pending_case(None);
    }

    #[test]
    fn active_request_pending_cancel_before_activation_preserves_parent_and_sibling() {
        active_request_pending_case(Some(true));
    }

    #[test]
    fn active_request_pending_cancel_after_activation_preserves_parent_and_sibling() {
        active_request_pending_case(Some(false));
    }

    fn active_request_pending_case(cancel_before_activation: Option<bool>) {
        let runtime = RuntimeBuilder::current_thread()
            .build()
            .expect("ownership test runtime must initialize");
        let parent = runtime.request_cx_with_budget(Budget::INFINITE);
        let child = runtime.request_cx_with_budget(Budget::INFINITE);
        let sibling = runtime.request_cx_with_budget(Budget::INFINITE);
        let server = Server::new("pending-request-owner", "1.0.0").build();
        let cancellation = McpRequestCancellation::new();
        let guard = ActiveRequestGuard::try_reserve(
            Arc::clone(&server.active_requests),
            11,
            RequestId::Number(7),
            parent.region_id(),
            cancellation.clone(),
        )
        .expect("pending request should reserve its wire ID");
        let completion = Arc::clone(&guard.completion);
        assert_eq!(server.active_requests.lock().unwrap().len(), 1);
        assert!(!completion.is_done());
        assert!(
            ActiveRequestGuard::try_new(
                Arc::clone(&server.active_requests),
                11,
                RequestId::Integer("7e0".to_owned()),
                sibling.clone(),
            )
            .is_err(),
            "queued ownership must reject an equivalent duplicate without replacement"
        );
        if cancel_before_activation == Some(true) {
            server.cancel_active_requests(CancelKind::Shutdown, false);
        }
        assert_eq!(
            guard.activate(child.clone()),
            cancel_before_activation != Some(true)
        );
        if cancel_before_activation == Some(false) {
            server.cancel_active_requests(CancelKind::Shutdown, false);
        }
        assert_eq!(
            child.is_cancel_requested(),
            cancel_before_activation.is_some()
        );
        assert_eq!(
            cancellation.is_cancel_requested(),
            cancel_before_activation.is_some()
        );
        assert!(!parent.is_cancel_requested());
        assert!(!sibling.is_cancel_requested());
        assert!(!completion.is_done());
        assert_eq!(server.active_requests.lock().unwrap().len(), 1);
        drop(guard);
        assert!(completion.is_done());
        assert!(server.active_requests.lock().unwrap().is_empty());
        let replacement = ActiveRequestGuard::try_new(
            Arc::clone(&server.active_requests),
            11,
            RequestId::Number(7),
            sibling.clone(),
        )
        .expect("retirement must permit exact ID reuse");
        assert!(!replacement.cancellation().is_cancel_requested());
        assert!(!sibling.is_cancel_requested());
        drop(replacement);
        assert!(server.active_requests.lock().unwrap().is_empty());
    }

    #[test]
    fn active_request_guard_removes_on_drop() {
        let map = Arc::new(Mutex::new(HashMap::new()));
        let cx = Cx::for_testing();
        let id = RequestId::Number(1);
        {
            let _guard = ActiveRequestGuard::try_new(Arc::clone(&map), 11, id.clone(), cx)
                .expect("insert guard");
            assert_eq!(map.lock().unwrap().len(), 1);
        }
        // After drop, the entry should be removed
        assert_eq!(map.lock().unwrap().len(), 0);
    }

    #[test]
    fn active_request_guard_rejects_duplicate_request_id() {
        let map = Arc::new(Mutex::new(HashMap::new()));
        let first = ActiveRequestGuard::try_new(
            Arc::clone(&map),
            11,
            RequestId::Number(7),
            Cx::for_testing(),
        )
        .expect("first request should register");
        let duplicate = ActiveRequestGuard::try_new(
            Arc::clone(&map),
            11,
            RequestId::Integer("7e0".to_owned()),
            Cx::for_testing(),
        );
        assert!(
            duplicate.is_err(),
            "equivalent numeric active request IDs must be rejected"
        );
        drop(first);
        assert!(map.lock().unwrap().is_empty());
    }

    #[test]
    fn active_request_guard_allows_same_request_id_in_distinct_sessions() {
        let map = Arc::new(Mutex::new(HashMap::new()));
        let first = ActiveRequestGuard::try_new(
            Arc::clone(&map),
            11,
            RequestId::Number(7),
            Cx::for_testing(),
        )
        .expect("first session should register");
        let second = ActiveRequestGuard::try_new(
            Arc::clone(&map),
            12,
            RequestId::Number(7),
            Cx::for_testing(),
        )
        .expect("second session may reuse the same wire request id");
        assert_eq!(map.lock().unwrap().len(), 2);
        drop((first, second));
        assert!(map.lock().unwrap().is_empty());
    }

    #[test]
    fn cancellation_notification_is_bound_to_originating_session() {
        let server = Server::new("cancel-owner-test", "1.0.0").build();
        let first_cx = Cx::for_testing();
        let second_cx = Cx::for_testing();
        let request_id = RequestId::Number(7);
        let first = ActiveRequestGuard::try_new(
            Arc::clone(&server.active_requests),
            11,
            request_id.clone(),
            first_cx.clone(),
        )
        .expect("first session should register");
        let second = ActiveRequestGuard::try_new(
            Arc::clone(&server.active_requests),
            12,
            request_id.clone(),
            second_cx.clone(),
        )
        .expect("second session should register");
        let first_cancellation = first.cancellation();
        let second_cancellation = second.cancellation();

        server.handle_cancelled_notification(
            11,
            CancelledParams {
                request_id,
                reason: Some("owner requested cancellation".to_string()),
                meta: None,
            },
        );

        assert!(first_cancellation.is_cancel_requested());
        assert!(!second_cancellation.is_cancel_requested());
        assert!(!first_cx.is_cancel_requested());
        assert!(!second_cx.is_cancel_requested());
        drop((first, second));
    }

    #[test]
    fn cancelled_notification_does_not_block_the_receive_path() {
        let server = Server::new("nonblocking-cancellation-test", "1.0.0").build();
        let request_id = RequestId::Number(41);
        let guard = ActiveRequestGuard::try_new(
            Arc::clone(&server.active_requests),
            11,
            request_id.clone(),
            Cx::for_testing(),
        )
        .expect("request should register");
        let cancellation = guard.cancellation();

        server.handle_cancelled_notification(
            11,
            CancelledParams {
                request_id,
                reason: None,
                meta: None,
            },
        );

        // bd-mvpne: an `assert!(start.elapsed() < Duration::from_secs(1))` stood here and was
        // removed, with its `Instant::now()` binding. It ran AFTER the call it bounded, so a
        // genuine block never reached it -- it could not detect the defect its own message
        // named -- while still being able to fail because the machine was merely slow. The
        // two assertions below carry everything recoverable. Do not re-add a wall-clock
        // bound here; the property is structural, not temporal.
        assert!(cancellation.is_cancel_requested());
        assert!(!guard.completion.is_done());
    }

    #[test]
    fn duplicate_cancellation_is_not_misclassified_as_finalization() {
        let server = Server::new("duplicate-cancellation-state-test", "1.0.0").build();
        let request_id = RequestId::Number(42);
        let guard = ActiveRequestGuard::try_new(
            Arc::clone(&server.active_requests),
            11,
            request_id.clone(),
            Cx::for_testing(),
        )
        .expect("request should register");
        let cancellation = guard.cancellation();

        for _ in 0..2 {
            server.handle_cancelled_notification(
                11,
                CancelledParams {
                    request_id: request_id.clone(),
                    reason: None,
                    meta: None,
                },
            );
        }

        assert!(cancellation.is_cancel_requested());
        assert!(!cancellation.is_finalizing());
        assert!(!guard.completion.is_done());
    }

    #[test]
    fn cancellation_notification_accepts_arbitrary_precision_integer_request_ids() {
        let server = Server::new("large-cancellation-id-test", "1.0.0").build();
        let request_id = RequestId::Integer(
            "9223372036854775808922337203685477580892233720368547758089".to_string(),
        );
        let guard = ActiveRequestGuard::try_new(
            Arc::clone(&server.active_requests),
            11,
            request_id.clone(),
            Cx::for_testing(),
        )
        .expect("an arbitrary-precision mathematical integer must register");
        let cancellation = guard.cancellation();

        assert!(server.handle_cancelled_notification(
            11,
            CancelledParams {
                request_id,
                reason: Some("large-id cancellation".to_string()),
                meta: None,
            },
        ));
        assert!(cancellation.is_cancel_requested());
    }

    // Exact-2024 era: legacy active-request registry.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn invalid_or_unknown_cancellation_does_not_mutate_an_active_request() {
        let server = Server::new("ignored-cancellation-test", "1.0.0").build();
        let active_request_id = RequestId::Number(42);
        let guard = ActiveRequestGuard::try_new(
            Arc::clone(&server.active_requests),
            11,
            active_request_id.clone(),
            Cx::for_testing(),
        )
        .expect("active request must register");
        let cancellation = guard.cancellation();

        assert!(!server.handle_cancelled_notification(
            11,
            CancelledParams {
                request_id: RequestId::Integer("1.5".to_string()),
                reason: None,
                meta: None,
            },
        ));
        assert!(!server.handle_cancelled_notification(
            11,
            CancelledParams {
                request_id: RequestId::Number(43),
                reason: None,
                meta: None,
            },
        ));

        assert!(!cancellation.is_cancel_requested());
        assert!(server.request_id_is_active(11, &active_request_id));
        assert_eq!(
            server
                .active_requests
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .len(),
            1,
            "ignored cancellation notifications must leave the request registry unchanged"
        );
    }

    #[test]
    fn completed_request_cancellation_is_ignored_without_registry_mutation() {
        let server = Server::new("completed-cancellation-test", "1.0.0").build();
        let request_id = RequestId::Number(44);
        let cancellation = {
            let guard = ActiveRequestGuard::try_new(
                Arc::clone(&server.active_requests),
                11,
                request_id.clone(),
                Cx::for_testing(),
            )
            .expect("active request must register");
            guard.cancellation()
        };

        assert!(!server.handle_cancelled_notification(
            11,
            CancelledParams {
                request_id,
                reason: None,
                meta: None,
            },
        ));
        assert!(!cancellation.is_cancel_requested());
        assert!(
            server
                .active_requests
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .is_empty(),
            "a completed request must remain absent after a late cancellation"
        );
    }

    #[test]
    fn request_local_cancellation_dominates_a_late_success_without_cancelling_ambient_cx() {
        let cx = Cx::for_testing();
        let cancellation = McpRequestCancellation::new();
        cancellation.cancel();

        let result = Server::enforce_post_dispatch_liveness(
            &cancellation,
            &cx,
            Budget::INFINITE,
            Ok(serde_json::json!({"late": "success"})),
        )
        .expect_err("late request cancellation must dominate a successful handler result");

        assert_eq!(result.code, McpErrorCode::RequestCancelled);
        assert!(!cx.is_cancel_requested());
    }

    #[test]
    fn post_dispatch_success_remains_cancellable_until_response_commit() {
        let cx = Cx::for_testing();
        let cancellation = McpRequestCancellation::new();
        let result = Server::enforce_post_dispatch_liveness(
            &cancellation,
            &cx,
            Budget::INFINITE,
            Ok(serde_json::json!({"committed": true})),
        )
        .expect("active request should preserve its successful result");

        assert_eq!(result, serde_json::json!({"committed": true}));
        assert!(!cancellation.is_finalizing());
        assert!(cancellation.cancel());
        assert!(cancellation.is_cancel_requested());
        assert!(!cx.is_cancel_requested());
    }

    #[test]
    fn initialize_response_middleware_failure_restores_exact_prior_state() {
        let server = Server::new("initialize-middleware-rollback-test", "1.0.0")
            .middleware(RejectResponseMiddleware)
            .build();
        let mut session = Session::new(server.info.clone(), server.capabilities.clone());
        session.initialize(
            fastmcp_protocol::ClientInfo {
                name: "original-client".to_string(),
                version: "0.9.0".to_string(),
            },
            fastmcp_protocol::ClientCapabilities {
                sampling: Some(fastmcp_protocol::SamplingCapability::default()),
                elicitation: None,
                roots: None,
                ..Default::default()
            },
            "original-protocol".to_string(),
        );
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let response = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            initialize_test_request(
                81,
                "replacement-client",
                fastmcp_protocol::ClientCapabilities {
                    sampling: None,
                    elicitation: Some(fastmcp_protocol::ElicitationCapability::form()),
                    roots: None,
                    ..Default::default()
                },
            ),
            &notification_sender,
            &test_request_sender(),
        ))
        .expect("initialize middleware failure must produce a response");

        assert!(response.error.is_some());
        assert!(session.is_initialized());
        assert_eq!(
            session.client_info().map(|info| info.name.as_str()),
            Some("original-client")
        );
        assert_eq!(session.protocol_version(), Some("original-protocol"));
        assert!(session.supports_sampling());
        assert!(!session.supports_elicitation());
    }

    #[test]
    fn late_initialize_cancellation_restores_uninitialized_state() {
        let server = Server::new("initialize-cancellation-rollback-test", "1.0.0").build();
        let mut session = Session::new(server.info.clone(), server.capabilities.clone());
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();
        let handled = block_on(server.handle_request_internal(
            &Cx::for_testing(),
            &mut session,
            initialize_test_request(
                82,
                "cancelled-client",
                fastmcp_protocol::ClientCapabilities::default(),
            ),
            &notification_sender,
            &request_sender,
            None,
            None,
        ))
        .expect("initialize must produce a provisional response");
        let cancellation = handled
            .cancellation
            .as_ref()
            .expect("initialize request must remain cancellable")
            .clone();

        assert!(session.is_initialized());
        assert!(cancellation.cancel());
        let response = handled.finalize_for_return(&mut session);

        assert_eq!(
            response
                .error
                .as_ref()
                .and_then(|error| error.code.as_i32()),
            Some(i32::from(McpErrorCode::RequestCancelled))
        );
        assert!(!session.is_initialized());
        assert!(session.client_info().is_none());
        assert!(session.client_capabilities().is_none());
        assert!(session.protocol_version().is_none());
    }

    // Exact-2024 era: legacy initialize response commit.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn initialize_encode_failure_restores_exact_prior_state() {
        let server = Server::new("initialize-encode-rollback-test", "1.0.0").build();
        let mut session = initialized_test_session(&server);
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();
        let handled = block_on(server.handle_request_internal(
            &Cx::for_testing(),
            &mut session,
            initialize_test_request(
                83,
                "unsent-replacement-client",
                fastmcp_protocol::ClientCapabilities::default(),
            ),
            &notification_sender,
            &request_sender,
            None,
            None,
        ))
        .expect("initialize must produce a provisional response");

        assert_eq!(
            session.client_info().map(|info| info.name.as_str()),
            Some("unsent-replacement-client")
        );
        let json_error = serde_json::from_str::<serde_json::Value>("{")
            .expect_err("malformed JSON must create a codec error");
        let error = handled
            .send_with(&mut session, |_response| {
                Err(TransportError::Codec(fastmcp_transport::CodecError::Json(
                    json_error,
                )))
            })
            .expect_err("encode failure must propagate");

        assert!(matches!(error, TransportError::Codec(_)));
        assert_eq!(
            session.client_info().map(|info| info.name.as_str()),
            Some("panic-containment-test-client")
        );
        assert_eq!(session.protocol_version(), Some("2024-11-05"));
    }

    // Exact-2024 era: legacy logging/setLevel response commit.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn log_level_write_failure_restores_previous_level() {
        let server = Server::new("log-level-write-rollback-test", "1.0.0")
            .log_level(Level::Debug)
            .build();
        let mut session = initialized_test_session(&server);
        session.set_log_level(LogLevel::Warning);
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();
        let request = JsonRpcRequest::new(
            "logging/setLevel",
            Some(
                serde_json::to_value(SetLogLevelParams {
                    level: LogLevel::Debug,
                })
                .expect("serialize logging/setLevel request"),
            ),
            84_i64,
        );
        let handled = block_on(server.handle_request_internal(
            &Cx::for_testing(),
            &mut session,
            request,
            &notification_sender,
            &request_sender,
            None,
            None,
        ))
        .expect("logging/setLevel must produce a provisional response");

        assert_eq!(session.log_level(), Some(LogLevel::Debug));
        let error = handled
            .send_with(&mut session, |_response| {
                Err(TransportError::Io(std::io::Error::new(
                    std::io::ErrorKind::BrokenPipe,
                    "test logging response write failure",
                )))
            })
            .expect_err("write failure must propagate");

        assert!(matches!(error, TransportError::Io(_)));
        assert_eq!(session.log_level(), Some(LogLevel::Warning));
    }

    // Exact-2024 era: legacy handled-response commit.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn handled_response_retains_active_request_until_commit_and_late_cancellation_wins() {
        let server = Server::new("commit-race-test", "1.0.0").build();
        let mut session = initialized_test_session(&server);
        let request_id = RequestId::String("commit-race".to_string());
        let request_cx = Cx::for_testing();
        let guard = ActiveRequestGuard::try_new(
            Arc::clone(&server.active_requests),
            session.id(),
            request_id.clone(),
            request_cx.clone(),
        )
        .expect("register active request");
        let cancellation = guard.cancellation();
        let handled = HandledRequest::tracked(
            JsonRpcResponse::success(request_id.clone(), serde_json::json!({"ok": true})),
            cancellation.clone(),
            Some(guard),
            None,
            request_cx,
            Budget::INFINITE,
        )
        .with_deferred_stats(DeferredRequestStats::new(
            server.stats.as_ref(),
            "tools/call",
            Instant::now(),
            DeferredRequestOutcome::Success,
        ));

        assert!(server.request_id_is_active(session.id(), &request_id));
        assert!(cancellation.cancel());
        let response = handled.finalize_for_return(&mut session);

        assert_eq!(response.id, Some(request_id.clone()));
        assert_eq!(
            response
                .error
                .as_ref()
                .and_then(|error| error.code.as_i32()),
            Some(i32::from(McpErrorCode::RequestCancelled))
        );
        assert!(!server.request_id_is_active(session.id(), &request_id));
        let stats = server.stats().expect("stats enabled by default");
        assert_eq!(stats.total_requests, 1);
        assert_eq!(stats.successful_requests, 0);
        assert_eq!(stats.cancelled_requests, 1);
    }

    #[test]
    fn ambient_cancellation_before_commit_rolls_back_and_replaces_success() {
        let mut session = Session::new(
            ServerInfo {
                name: "ambient-commit-test".to_string(),
                version: "1.0.0".to_string(),
            },
            ServerCapabilities::default(),
        );
        session.set_log_level(LogLevel::Debug);
        let cx = Cx::for_testing();
        let cancellation = McpRequestCancellation::new();
        let handled = HandledRequest::tracked(
            JsonRpcResponse::success(RequestId::Number(91), serde_json::json!({"ok": true})),
            cancellation.clone(),
            None,
            Some(SessionMutationRollback::RestoreLogLevel(Some(
                LogLevel::Warning,
            ))),
            cx.clone(),
            Budget::INFINITE,
        );

        cx.set_cancel_requested(true);
        let response = handled.finalize_for_return(&mut session);

        assert_eq!(
            response
                .error
                .as_ref()
                .and_then(|error| error.code.as_i32()),
            Some(i32::from(McpErrorCode::RequestCancelled))
        );
        assert_eq!(session.log_level(), Some(LogLevel::Warning));
        assert!(cancellation.is_cancel_requested());
    }

    #[test]
    fn deadline_expiring_while_response_is_pending_prevents_commit() {
        let mut session = Session::new(
            ServerInfo {
                name: "deadline-commit-test".to_string(),
                version: "1.0.0".to_string(),
            },
            ServerCapabilities::default(),
        );
        let cx = Cx::for_testing();
        // Keep the precondition well away from scheduler jitter. The previous
        // one-millisecond window could expire while the test thread was
        // descheduled before the assertion below.
        let budget = Budget::new().with_deadline(cx.now().saturating_add_nanos(1_000_000_000));
        assert!(Server::request_budget_error(&cx, budget).is_none());
        let handled = HandledRequest::tracked(
            JsonRpcResponse::success(RequestId::Number(92), serde_json::json!({"ok": true})),
            McpRequestCancellation::new(),
            None,
            None,
            cx,
            budget,
        );

        std::thread::sleep(Duration::from_millis(1_100));
        let response = handled.finalize_for_return(&mut session);

        assert_eq!(
            response
                .error
                .as_ref()
                .and_then(|error| error.code.as_i32()),
            Some(i32::from(McpErrorCode::RequestCancelled))
        );
        assert_eq!(
            response.error.as_ref().map(|error| error.message.as_str()),
            Some("Request timeout exceeded")
        );
    }

    // Exact-2024 era: legacy handled-response commit.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn failed_response_write_rolls_back_reversible_session_mutation() {
        let server = Server::new("commit-rollback-test", "1.0.0").build();
        let mut session = initialized_test_session(&server);
        let uri = "test://response-write-rollback".to_string();
        session.restore_resource_subscription(uri.clone());
        let handled = HandledRequest::tracked(
            JsonRpcResponse::success(RequestId::Number(9), serde_json::json!({})),
            McpRequestCancellation::new(),
            None,
            Some(SessionMutationRollback::RemoveResourceSubscription(
                uri.clone(),
            )),
            Cx::for_testing(),
            Budget::INFINITE,
        )
        .with_deferred_stats(DeferredRequestStats::new(
            server.stats.as_ref(),
            "resources/subscribe",
            Instant::now(),
            DeferredRequestOutcome::Success,
        ));

        let error = handled
            .send_with(&mut session, |_response| {
                Err(TransportError::Io(std::io::Error::new(
                    std::io::ErrorKind::BrokenPipe,
                    "test write failure",
                )))
            })
            .expect_err("failed response write must propagate");

        assert!(matches!(error, TransportError::Io(_)));
        assert!(!session.is_resource_subscribed(&uri));
        assert_eq!(
            server
                .stats()
                .expect("stats enabled by default")
                .total_requests,
            0,
            "a response that never reached the transport must not be counted as sent"
        );
    }

    /// bd-0vcz4: the runtime also cancels a Cx whose deadline passed; that
    /// cancellation is the timeout, not a plain cancellation.
    #[test]
    fn cancelled_cx_past_its_deadline_reports_request_timeout() {
        let cx = Cx::for_testing_with_budget(Budget::new().with_deadline(asupersync::Time::ZERO));
        cx.set_cancel_requested(true);

        let error = Server::request_budget_error(&cx, Budget::INFINITE)
            .expect("an expired, cancelled request is refused");
        assert_eq!(error.code, McpErrorCode::RequestCancelled);
        assert_eq!(error.message, "Request timeout exceeded");
    }

    /// Near-identical negative: the same cancelled Cx without a passed deadline
    /// is a plain cancellation.
    #[test]
    fn cancelled_cx_without_a_passed_deadline_reports_request_cancelled() {
        let cx = Cx::for_testing();
        cx.set_cancel_requested(true);

        let error = Server::request_budget_error(&cx, Budget::INFINITE)
            .expect("a cancelled request is refused");
        assert_eq!(error.code, McpErrorCode::RequestCancelled);
        assert_eq!(error.message, McpError::request_cancelled().message);
    }

    #[test]
    fn expired_ambient_deadline_is_enforced_before_and_after_dispatch() {
        let cx = Cx::for_testing_with_budget(Budget::new().with_deadline(asupersync::Time::ZERO));

        let admission = Server::request_budget_error(&cx, Budget::INFINITE)
            .expect("expired ambient deadline must fail pre-admission");
        assert_eq!(admission.code, McpErrorCode::RequestCancelled);

        let result = Server::enforce_post_dispatch_liveness(
            &McpRequestCancellation::new(),
            &cx,
            Budget::INFINITE,
            Ok(serde_json::json!({"late": "success"})),
        )
        .expect_err("expired ambient deadline must dominate a late success");
        assert_eq!(result.code, McpErrorCode::RequestCancelled);
    }

    // =========================================================================
    // Additional coverage tests (bd-cd79)
    // =========================================================================

    #[test]
    fn logging_config_debug_and_clone() {
        let config = LoggingConfig::default();
        let debug = format!("{config:?}");
        assert!(debug.contains("LoggingConfig"));
        assert!(debug.contains("Info"));

        let cloned = config.clone();
        assert_eq!(cloned.level, LevelFilter::Info);
        assert_eq!(cloned.timestamps, config.timestamps);
    }

    #[test]
    fn transport_lock_error_is_io() {
        let err = transport_lock_error();
        match err {
            TransportError::Io(io) => {
                assert!(io.to_string().contains("poisoned"));
            }
            other => panic!("expected Io variant, got: {other:?}"),
        }
    }

    fn wait_for_dispatch_worker_failure(worker_failed: &AtomicBool) -> TransportError {
        let deadline = Instant::now() + Duration::from_secs(2);
        while !worker_failed.load(Ordering::Acquire) && Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(1));
        }
        if worker_failed.load(Ordering::Acquire) {
            TransportError::Cancelled
        } else {
            // Let the pump perform its normal stop-and-join cleanup. The
            // callback-entry assertion then fails the test without detaching
            // its worker thread through an unwind from inside `recv`.
            TransportError::Timeout
        }
    }

    #[test]
    fn dispatch_worker_send_failure_returns_failure_status() {
        let emitted = Arc::new(AtomicBool::new(false));
        let emitted_for_receive = Arc::clone(&emitted);
        let send_attempted = Arc::new(AtomicBool::new(false));
        let send_attempted_by_worker = Arc::clone(&send_attempted);
        let cx = Cx::for_testing();
        let exit_code = Arc::new(Server::new("worker-send-failure-test", "1.0.0").build())
            .run_loop_pump_with_policy(
                &cx,
                &cx,
                move |_receive_cx, worker_failed| {
                    if !emitted_for_receive.swap(true, Ordering::AcqRel) {
                        return Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                            "ping", None, 701_i64,
                        )));
                    }
                    Err(wait_for_dispatch_worker_failure(worker_failed))
                },
                move |_send_cx, _message| {
                    send_attempted_by_worker.store(true, Ordering::Release);
                    Err(TransportError::Io(std::io::Error::new(
                        std::io::ErrorKind::BrokenPipe,
                        "test response send failure",
                    )))
                },
                Arc::new(|_| {}),
                "test",
                true,
                None,
                true,
                true,
                None,
                None,
                None,
                PumpIoMode::Split,
            );

        assert_eq!(exit_code, 1);
        assert!(send_attempted.load(Ordering::Acquire));
        assert!(!cx.is_cancel_requested());
    }

    #[test]
    fn reality_check_regression_worker_io_failure_wins_concurrent_clean_eof() {
        let emitted = Arc::new(AtomicBool::new(false));
        let emitted_for_receive = Arc::clone(&emitted);
        let send_entered = Arc::new(AtomicBool::new(false));
        let send_entered_for_receive = Arc::clone(&send_entered);
        let send_entered_by_worker = Arc::clone(&send_entered);

        let cx = Cx::for_testing();
        let exit_code = Arc::new(Server::new("worker-send-eof-race-test", "1.0.0").build())
            .run_loop_pump_with_policy(
                &cx,
                &cx,
                move |_receive_cx, _worker_failed| {
                    if !emitted_for_receive.swap(true, Ordering::AcqRel) {
                        return Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                            "ping", None, 706_i64,
                        )));
                    }
                    let deadline = Instant::now() + Duration::from_secs(2);
                    while !send_entered_for_receive.load(Ordering::Acquire)
                        && Instant::now() < deadline
                    {
                        std::thread::sleep(Duration::from_millis(1));
                    }
                    Err(TransportError::Closed)
                },
                move |send_cx, _message| {
                    send_entered_by_worker.store(true, Ordering::Release);
                    let deadline = Instant::now() + Duration::from_secs(2);
                    while send_cx.checkpoint().is_ok() && Instant::now() < deadline {
                        std::thread::sleep(Duration::from_millis(1));
                    }
                    Err(TransportError::Io(std::io::Error::new(
                        std::io::ErrorKind::BrokenPipe,
                        "test response failure after concurrent EOF",
                    )))
                },
                Arc::new(|_| {}),
                "test",
                true,
                None,
                true,
                true,
                None,
                None,
                None,
                PumpIoMode::Split,
            );

        assert!(send_entered.load(Ordering::Acquire));
        assert_eq!(exit_code, 1);
    }

    // Exact-2024 era: dispatches an un-negotiated ping, which only the dual-era pump admits.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn dispatch_worker_panic_trips_failure_latch_and_returns_failure_status() {
        let emitted = Arc::new(AtomicBool::new(false));
        let emitted_for_receive = Arc::clone(&emitted);
        let send_entered = Arc::new(AtomicBool::new(false));
        let send_entered_by_worker = Arc::clone(&send_entered);
        let cx = Cx::for_testing();
        let exit_code = Arc::new(Server::new("worker-panic-latch-test", "1.0.0").build())
            .run_loop_pump_with_policy(
                &cx,
                &cx,
                move |_receive_cx, worker_failed| {
                    if !emitted_for_receive.swap(true, Ordering::AcqRel) {
                        return Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                            "ping", None, 702_i64,
                        )));
                    }
                    Err(wait_for_dispatch_worker_failure(worker_failed))
                },
                move |_send_cx, _message| -> Result<(), TransportError> {
                    send_entered_by_worker.store(true, Ordering::Release);
                    panic!("dispatch worker send callback panic")
                },
                Arc::new(|_| {}),
                "test",
                true,
                None,
                true,
                true,
                None,
                None,
                None,
                PumpIoMode::Split,
            );

        assert_eq!(exit_code, 1);
        assert!(send_entered.load(Ordering::Acquire));
        assert!(!cx.is_cancel_requested());
    }

    // Exact-2024 era: the non-quiescent handler is reached through a legacy opening.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn stdio_pump_returns_failure_and_skips_hooks_for_non_quiescent_legacy_handler() {
        let control = Arc::new(NonQuiescentLegacyControl::default());
        let control_for_receive = Arc::clone(&control);
        let phase = Arc::new(AtomicUsize::new(0));
        let phase_for_receive = Arc::clone(&phase);
        let shutdown_called = Arc::new(AtomicBool::new(false));
        let shutdown_observer = Arc::clone(&shutdown_called);

        let server = Server::new("bounded-legacy-worker-shutdown-test", "1.0.0")
            .protocol_policy(ProtocolPolicy::Auto)
            .expect("Auto must be available to this test build")
            .tool(NonQuiescentLegacyTool {
                control: Arc::clone(&control),
            })
            .on_shutdown(move || shutdown_observer.store(true, Ordering::Release))
            .build();
        // The legacy dispatch worker also requires the caller-owned runtime
        // to admit its request child. A detached testing Cx rejects admission
        // before the deliberately non-cooperative handler can start.
        let runtime = RuntimeBuilder::current_thread()
            .with_reactor(create_reactor().expect("stdio pump reactor must initialize"))
            .blocking_threads(4, MAX_DISPATCH_QUEUE_DEPTH)
            .build()
            .expect("stdio pump runtime must initialize");
        let (sender, receiver) = sync_channel(1);
        runtime
            .handle()
            .try_spawn_with_cx(move |cx| async move {
                let dispatch_cx = cx.clone();
                let pump_sender = sender.clone();
                if let Err(error) = cx.spawn_blocking(move |pump_cx| {
                    let code = Arc::new(server).run_loop_pump_with_policy(
                        &pump_cx,
                        &dispatch_cx,
                        move |_receive_cx, _worker_failed| match phase_for_receive
                            .fetch_add(1, Ordering::AcqRel)
                        {
                            0 => Ok(exact_legacy_initialize_request(
                                705,
                                serde_json::json!("1.0.0"),
                            )),
                            1 => Ok(JsonRpcMessage::Request(JsonRpcRequest::notification(
                                "notifications/initialized",
                                None,
                            ))),
                            2 => Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                                "tools/call",
                                Some(serde_json::json!({
                                    "name": "non_quiescent_legacy_tool",
                                    "arguments": {},
                                })),
                                706_i64,
                            ))),
                            3 if control_for_receive.wait_for_started(Duration::from_secs(2)) => {
                                Err(TransportError::Closed)
                            }
                            3 => Err(TransportError::Timeout),
                            _ => Err(TransportError::Closed),
                        },
                        move |_send_cx, _message| Ok(()),
                        Arc::new(|_| {}),
                        "stdio-test",
                        true,
                        None,
                        true,
                        true,
                        None,
                        None,
                        None,
                        PumpIoMode::Split,
                    );
                    let _ = pump_sender.send(Ok(code));
                }) {
                    let _ = sender.send(Err(format!("stdio pump admission failed: {error}")));
                }
            })
            .expect("stdio pump task must be admitted");
        // The pump waits through bounded worker-shutdown windows before
        // detaching the non-quiescent legacy worker; poll its result without
        // joining the task while the handler is intentionally parked.
        let pump_result: Result<Result<i32, String>, String> = runtime.block_on(async {
            let cx = Cx::current().expect("the test runtime installs an ambient Cx");
            let deadline = cx.now().saturating_add_nanos(30_000_000_000);
            loop {
                match receiver.try_recv() {
                    Ok(result) => break Ok(result),
                    Err(TryRecvError::Disconnected) => {
                        break Err("stdio pump task exited without reporting its result".to_owned());
                    }
                    Err(TryRecvError::Empty) => {
                        if asupersync::time::timeout_at(
                            deadline,
                            asupersync::time::sleep(cx.now(), Duration::from_millis(5)),
                        )
                        .await
                        .is_err()
                        {
                            break Err("stdio pump did not settle within its bound".to_owned());
                        }
                    }
                }
            }
        });

        // Capture observations before releasing the parked legacy handler so
        // an assertion failure cannot strand the worker during runtime drop.
        let started = control.has_started();
        let finished_before_release = control.has_finished();
        let shutdown_before_release = shutdown_called.load(Ordering::Acquire);
        control.release();
        let finished_after_release = control.wait_for_finished(Duration::from_secs(2));

        let exit_code = pump_result
            .expect("stdio pump must report a result")
            .expect("stdio pump must complete");

        assert_eq!(exit_code, 1);
        assert!(started);
        assert!(!finished_before_release);
        assert!(!shutdown_before_release);
        assert!(finished_after_release);
    }

    // Exact-2024 era: the non-quiescent handler is reached through a legacy opening.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn returning_split_waits_for_non_quiescent_legacy_handler_before_owned_cleanup() {
        let control = Arc::new(NonQuiescentLegacyControl::default());
        let shutdown_called = Arc::new(AtomicBool::new(false));
        let shutdown_observer = Arc::clone(&shutdown_called);
        let release_control = Arc::clone(&control);
        let release_thread = std::thread::spawn(move || {
            let started = release_control.wait_for_started(Duration::from_secs(2));
            if started {
                std::thread::sleep(DISPATCH_WORKER_SHUTDOWN_TIMEOUT + Duration::from_millis(500));
            }
            // Always release before reporting a failed start observation. A
            // panic in this helper would otherwise strand the intentionally
            // non-cooperative handler and hang the entire test process.
            release_control.release();
            started
        });
        let started = Instant::now();
        let run_result = run_live_split_transport(
            Duration::from_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS),
            Server::new("returning-legacy-worker-shutdown-test", "1.0.0")
                .protocol_policy(ProtocolPolicy::Auto)
                .expect("Auto must be available to this test build")
                .tool(NonQuiescentLegacyTool {
                    control: Arc::clone(&control),
                })
                .on_shutdown(move || shutdown_observer.store(true, Ordering::Release))
                .build(),
            NonQuiescentLegacySplitRecv {
                phase: 0,
                control: Arc::clone(&control),
            },
            NonQuiescentLegacySplitSend,
        );
        let elapsed = started.elapsed();
        let release_observed_start = release_thread.join().expect("release thread must finish");

        assert!(
            release_observed_start,
            "legacy handler must start before its delayed release"
        );
        assert!(control.has_started());
        assert!(control.has_finished());
        assert!(elapsed >= DISPATCH_WORKER_SHUTDOWN_TIMEOUT);
        assert!(shutdown_called.load(Ordering::Acquire));
        assert!(run_result.is_err(), "worker timeout must remain a failure");
    }

    #[test]
    fn returning_split_waits_for_non_quiescent_modern_child_before_cleanup() {
        let control = Arc::new(NonQuiescentLegacyControl::default());
        let shutdown_called = Arc::new(AtomicBool::new(false));
        let shutdown_observer = Arc::clone(&shutdown_called);
        let release_control = Arc::clone(&control);
        // Scheduling the modern child can take longer than a couple of wall
        // seconds in a loaded full suite, so its start bound counts runnable
        // time; a child that never starts still fails.
        const START_BOUND: Duration = Duration::from_secs(5);
        let release_thread = std::thread::spawn(move || {
            let host = RunnableClock::start();
            let waiting = host.mark();
            let started = loop {
                if release_control.wait_for_started(Duration::from_millis(20)) {
                    break Ok(());
                }
                if host.expired(waiting, START_BOUND) {
                    break Err(host.describe(waiting));
                }
            };
            if started.is_ok() {
                std::thread::sleep(
                    DISPATCH_WORKER_SHUTDOWN_TIMEOUT * 2 + Duration::from_millis(500),
                );
            }
            // Preserve teardown even when the start observation misses its
            // bound. The assertion belongs after release so a failed harness
            // precondition cannot leave the runtime joining a parked child.
            release_control.release();
            started
        });
        let started = Instant::now();
        // The handler deliberately outlives both five-second product drain
        // windows. Include its start bound and two seconds for joined cleanup
        // instead of expiring the harness before release.
        let completion_timeout = DISPATCH_WORKER_SHUTDOWN_TIMEOUT * 2
            + Duration::from_millis(500)
            + START_BOUND
            + Duration::from_secs(2);
        let run_result = run_live_split_transport(
            completion_timeout,
            Server::new("returning-modern-worker-shutdown-test", "1.0.0")
                .protocol_policy(build_default_protocol_policy())
                .expect("the build's default policy must be available")
                .tool(NonQuiescentModernTool {
                    control: Arc::clone(&control),
                })
                .on_shutdown(move || shutdown_observer.store(true, Ordering::Release))
                .build(),
            NonQuiescentModernSplitRecv { phase: 0 },
            NonQuiescentLegacySplitSend,
        );
        let elapsed = started.elapsed();
        if let Err(waited) = release_thread.join().expect("release thread must finish") {
            panic!("modern child must start before its delayed release: waited {waited}");
        }
        assert!(control.has_started());
        assert!(control.has_finished());
        assert!(elapsed >= DISPATCH_WORKER_SHUTDOWN_TIMEOUT);
        assert!(shutdown_called.load(Ordering::Acquire));
        assert!(
            run_result.is_err(),
            "modern worker timeout must remain a failure"
        );
        assert_eq!(
            run_result.as_ref().map_err(String::as_str),
            Err("[-32603] Server transport loop failed"),
            "the product must report its drain failure after cleanup; a harness timeout is not that failure"
        );
    }

    #[test]
    fn stdio_pump_returns_failure_and_skips_hooks_for_non_quiescent_modern_child() {
        let control = Arc::new(NonQuiescentLegacyControl::default());
        let shutdown_called = Arc::new(AtomicBool::new(false));
        let shutdown_observer = Arc::clone(&shutdown_called);
        let phase = Arc::new(AtomicUsize::new(0));
        let phase_for_receive = Arc::clone(&phase);
        let control_for_receive = Arc::clone(&control);
        let server = Server::new("stdio-modern-worker-shutdown-test", "1.0.0")
            .protocol_policy(build_default_protocol_policy())
            .expect("the build's default policy must be available")
            .tool(NonQuiescentModernTool {
                control: Arc::clone(&control),
            })
            .on_shutdown(move || shutdown_observer.store(true, Ordering::Release))
            .build();
        // The modern dispatch arm admits requests through spawn_blocking, so
        // the pump must run under a runtime with blocking threads; a bare
        // testing Cx rejects every modern dispatch before the tool starts.
        let runtime = RuntimeBuilder::current_thread()
            .with_reactor(create_reactor().expect("stdio pump reactor must initialize"))
            .blocking_threads(4, MAX_DISPATCH_QUEUE_DEPTH)
            .build()
            .expect("stdio pump runtime must initialize");
        let (sender, receiver) = sync_channel(1);
        runtime
            .handle()
            .try_spawn_with_cx(move |cx| async move {
                let dispatch_cx = cx.clone();
                let pump_sender = sender.clone();
                // The pump reports its exit code through the channel from the
                // blocking closure itself rather than via join(): joining the
                // pump task can park forever while the deliberately
                // non-quiescent modern child still occupies its blocking
                // thread, and the harness only needs the exit code.
                if let Err(error) = cx.spawn_blocking(move |pump_cx| {
                    let code = Arc::new(server).run_loop_pump_with_policy(
                        &pump_cx,
                        &dispatch_cx,
                        move |_receive_cx, _worker_failed| match phase_for_receive
                            .fetch_add(1, Ordering::AcqRel)
                        {
                            0 => Ok(modern_discovery_opening_request()),
                            1 => Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                                "tools/call",
                                Some(serde_json::json!({
                                    "name": "non_quiescent_modern_tool",
                                    "arguments": {},
                                    "_meta": {
                                        MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                                        FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                                    },
                                })),
                                710_i64,
                            ))),
                            2 if control_for_receive.wait_for_started(Duration::from_secs(2)) => {
                                Err(TransportError::Closed)
                            }
                            2 => Err(TransportError::Timeout),
                            _ => Err(TransportError::Closed),
                        },
                        move |_send_cx, _message| Ok(()),
                        Arc::new(|_| {}),
                        "stdio-modern-test",
                        true,
                        None,
                        true,
                        true,
                        None,
                        None,
                        None,
                        PumpIoMode::Split,
                    );
                    let _ = pump_sender.send(Ok(code));
                }) {
                    let _ = sender.send(Err(format!("stdio pump admission failed: {error}")));
                }
            })
            .expect("stdio pump task must be admitted");
        // The pump legitimately holds several bounded worker-shutdown windows
        // (5s each) before detaching the non-quiescent child, so the result
        // wait must exceed their sum; the shared live-HTTP helper's 2s bound
        // is far too tight here.
        let pump_result: Result<Result<i32, String>, String> = runtime.block_on(async {
            let cx = Cx::current().expect("the test runtime installs an ambient Cx");
            let deadline = cx.now().saturating_add_nanos(30_000_000_000);
            loop {
                match receiver.try_recv() {
                    Ok(result) => break Ok(result),
                    Err(TryRecvError::Disconnected) => {
                        break Err("stdio pump task exited without reporting its result".to_owned());
                    }
                    Err(TryRecvError::Empty) => {
                        if asupersync::time::timeout_at(
                            deadline,
                            asupersync::time::sleep(cx.now(), Duration::from_millis(5)),
                        )
                        .await
                        .is_err()
                        {
                            break Err("stdio pump did not settle within its bound".to_owned());
                        }
                    }
                }
            }
        });

        // Capture the pre-release observations, then release the parked tool
        // BEFORE any panic: a failed assert (or a pump timeout) would
        // otherwise unwind into the runtime drop, which joins the
        // still-parked blocking thread forever.
        let started = control.has_started();
        let finished_before_release = control.has_finished();
        let shutdown_before_release = shutdown_called.load(Ordering::Acquire);
        control.release();
        let finished_after_release = control.wait_for_finished(Duration::from_secs(2));

        let exit_code = pump_result
            .expect("stdio pump must report a result")
            .expect("stdio pump must complete");
        assert_eq!(exit_code, 1);
        assert!(started);
        assert!(!finished_before_release);
        assert!(!shutdown_before_release);
        assert!(finished_after_release);
    }

    #[test]
    fn reality_check_regression_notification_failure_wins_concurrent_clean_eof() {
        let notification_failure = Arc::new(AtomicBool::new(false));
        let failure_from_receive = Arc::clone(&notification_failure);

        let cx = Cx::for_testing();
        let exit_code = Arc::new(Server::new("notification-eof-race-test", "1.0.0").build())
            .run_loop_pump_with_policy(
                &cx,
                &cx,
                move |_receive_cx, _worker_failed| {
                    // Model notification output failing immediately after a
                    // stop-aware receiver's final predicate check but before
                    // it returns the concurrently observed EOF.
                    failure_from_receive.store(true, Ordering::Release);
                    Err(TransportError::Closed)
                },
                move |_send_cx, _message| Ok(()),
                Arc::new(|_| {}),
                "stdio-test",
                true,
                Some(Arc::clone(&notification_failure)),
                false,
                true,
                None,
                None,
                None,
                PumpIoMode::Split,
            );

        assert!(notification_failure.load(Ordering::Acquire));
        assert_eq!(exit_code, 1);
    }

    // Exact-2024 era: dispatches an un-negotiated ping, which only the dual-era pump admits.
    #[cfg(all(unix, feature = "legacy-2024-11-05"))]
    #[test]
    fn reality_check_regression_dispatch_worker_send_failure_wakes_unix_stdio_receive() {
        use std::os::unix::net::UnixStream;

        let (mut peer, server_stream) =
            UnixStream::pair().expect("Unix stream fixture must be available");
        peer.write_all(b"{\"jsonrpc\":\"2.0\",\"method\":\"ping\",\"id\":703}\n")
            .expect("request fixture must reach the server stream");
        peer.flush().expect("request fixture must be flushed");

        let receive_calls = Arc::new(AtomicUsize::new(0));
        let receive_count = Arc::clone(&receive_calls);
        let receive_count_for_worker = Arc::clone(&receive_calls);
        let send_attempted = Arc::new(AtomicBool::new(false));
        let send_attempted_by_worker = Arc::clone(&send_attempted);
        let mut transport = StdioTransport::new(server_stream, Vec::<u8>::new());
        let cx = Cx::for_testing();
        let exit_code = cx.masked(|| {
            Arc::new(Server::new("unix-stdio-worker-failure-test", "1.0.0").build())
                .run_loop_pump_with_policy(
                    &cx,
                    &cx,
                    move |receive_cx, worker_failed| {
                        receive_count.fetch_add(1, Ordering::AcqRel);
                        transport.recv_until_or_stopped(receive_cx, None, || {
                            worker_failed.load(Ordering::Acquire)
                        })
                    },
                    move |_send_cx, _message| {
                        let deadline = Instant::now() + Duration::from_secs(2);
                        while receive_count_for_worker.load(Ordering::Acquire) < 2
                            && Instant::now() < deadline
                        {
                            std::thread::sleep(Duration::from_millis(1));
                        }
                        send_attempted_by_worker.store(true, Ordering::Release);
                        Err(TransportError::Io(std::io::Error::new(
                            std::io::ErrorKind::BrokenPipe,
                            "test response send failure",
                        )))
                    },
                    Arc::new(|_| {}),
                    "stdio-test",
                    true,
                    None,
                    true,
                    true,
                    None,
                    None,
                    None,
                    PumpIoMode::Split,
                )
        });

        assert_eq!(exit_code, 1);
        assert!(send_attempted.load(Ordering::Acquire));
        assert_eq!(receive_calls.load(Ordering::Acquire), 2);
    }

    #[derive(Clone, Copy)]
    enum ReturningProbeReceive {
        Closed,
        Cancelled,
        Timeout,
        // Exact-2024 era: an un-negotiated ping only the dual-era loop admits.
        #[cfg(feature = "legacy-2024-11-05")]
        PingThenClosed,
    }

    struct ReturningProbeTransport {
        receive: ReturningProbeReceive,
        fail_send: bool,
        fail_close: bool,
        close_calls: Arc<AtomicUsize>,
    }

    struct SharedTransportCountingTransport {
        recv_calls: Arc<AtomicUsize>,
        send_calls: Arc<AtomicUsize>,
        close_calls: Arc<AtomicUsize>,
        fail_close: bool,
    }

    struct ProtocolPolicyProbeTransport {
        next: Option<JsonRpcMessage>,
        sent: Arc<Mutex<Vec<JsonRpcMessage>>>,
        receive_calls: Arc<AtomicUsize>,
    }

    // Exact-2024 era: used only by legacy HTTP SSE lifecycle tests.
    #[cfg(feature = "legacy-2024-11-05")]
    struct LiveRuntimeListedTool;

    #[cfg(feature = "legacy-2024-11-05")]
    impl ToolHandler for LiveRuntimeListedTool {
        fn definition(&self) -> Tool {
            Tool {
                name: "live_runtime_listed_tool".to_owned(),
                description: Some("Proves legacy adapter runtime handler wiring".to_owned()),
                input_schema: serde_json::json!({"type": "object"}),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(&self, ctx: &McpContext, _arguments: serde_json::Value) -> McpResult<Vec<Content>> {
            Ok(vec![Content::text(format!(
                "live runtime legacy adapter request {}",
                ctx.request_id()
            ))])
        }
    }

    struct StdioCatalogMutatingTool;

    impl ToolHandler for StdioCatalogMutatingTool {
        fn definition(&self) -> Tool {
            Tool {
                name: "stdio_catalog_mutating_tool".to_owned(),
                description: Some(
                    "Disables itself so listen streams observe list_changed".to_owned(),
                ),
                input_schema: serde_json::json!({"type": "object"}),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(&self, ctx: &McpContext, _arguments: serde_json::Value) -> McpResult<Vec<Content>> {
            if !ctx.disable_tool("stdio_catalog_mutating_tool") {
                return Err(McpError::internal_error(
                    "stdio catalog mutation requires session state",
                ));
            }
            Ok(vec![Content::text("disabled")])
        }
    }

    // Exact-2024 era: used only by legacy runtime-context tests.
    #[cfg(feature = "legacy-2024-11-05")]
    struct LiveLegacyRuntimeConnectionTool;

    #[cfg(feature = "legacy-2024-11-05")]
    impl ToolHandler for LiveLegacyRuntimeConnectionTool {
        fn definition(&self) -> Tool {
            Tool {
                name: "live_legacy_runtime_connection_tool".to_owned(),
                description: Some(
                    "Proves legacy stdio handlers retain their connection runtime".to_owned(),
                ),
                input_schema: serde_json::json!({
                    "type": "object",
                    "required": ["sample"],
                    "properties": {"sample": {"type": "boolean"}},
                }),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(&self, ctx: &McpContext, arguments: serde_json::Value) -> McpResult<Vec<Content>> {
            let counter = ctx.get_state::<u64>("legacy-runtime-counter").unwrap_or(0) + 1;
            if !ctx.set_state("legacy-runtime-counter", counter) {
                return Err(McpError::internal_error(
                    "legacy connection state could not retain a counter",
                ));
            }
            ctx.report_progress(counter as f64, Some("legacy connection progress"));

            let sample = arguments
                .get("sample")
                .and_then(serde_json::Value::as_bool)
                .ok_or_else(|| McpError::invalid_params("sample must be a boolean"))?;
            let text = if sample {
                let response = block_on(ctx.sample("legacy runtime sample", 16))?;
                format!("legacy-runtime-{counter}-{}", response.text)
            } else {
                format!("legacy-runtime-{counter}-without-sampling")
            };
            Ok(vec![Content::text(text)])
        }
    }

    /// Same tool NAME and schema as `LiveLegacyRuntimeConnectionTool`, but
    /// declares `ToolExecutionMode::Async` and awaits `ctx.sample` directly
    /// instead of bridging it with `block_on`, so legacy HTTP dispatches it on
    /// the caller-owned path rather than the blocking pool.
    ///
    /// Note `call_async`'s trait default delegates to `call`, so declaring the
    /// mode without supplying this hook would route straight back into the
    /// `block_on` and be polled on the caller's runtime instead.
    // Exact-2024 era: used only by legacy HTTP SSE reverse-response tests.
    #[cfg(feature = "legacy-2024-11-05")]
    struct LiveLegacyReverseResponseAsyncTool;

    #[cfg(feature = "legacy-2024-11-05")]
    impl ToolHandler for LiveLegacyReverseResponseAsyncTool {
        fn definition(&self) -> Tool {
            LiveLegacyRuntimeConnectionTool.definition()
        }

        fn execution_mode(&self) -> ToolExecutionMode {
            ToolExecutionMode::Async
        }

        fn call(
            &self,
            _ctx: &McpContext,
            _arguments: serde_json::Value,
        ) -> McpResult<Vec<Content>> {
            Err(McpError::internal_error(
                "the async reverse-response tool requires asynchronous caller-owned dispatch",
            ))
        }

        fn call_async<'a>(
            &'a self,
            ctx: &'a McpContext,
            arguments: serde_json::Value,
        ) -> BoxFuture<'a, fastmcp_core::McpOutcome<Vec<Content>>> {
            Box::pin(async move {
                let counter = ctx.get_state::<u64>("legacy-runtime-counter").unwrap_or(0) + 1;
                if !ctx.set_state("legacy-runtime-counter", counter) {
                    return asupersync::Outcome::Err(McpError::internal_error(
                        "legacy connection state could not retain a counter",
                    ));
                }
                ctx.report_progress(counter as f64, Some("legacy connection progress"));
                let Some(sample) = arguments.get("sample").and_then(serde_json::Value::as_bool)
                else {
                    return asupersync::Outcome::Err(McpError::invalid_params(
                        "sample must be a boolean",
                    ));
                };
                let text = if sample {
                    match ctx.sample("legacy runtime sample", 16).await {
                        Ok(response) => format!("legacy-runtime-{counter}-{}", response.text),
                        Err(error) => return asupersync::Outcome::Err(error),
                    }
                } else {
                    format!("legacy-runtime-{counter}-without-sampling")
                };
                asupersync::Outcome::Ok(vec![Content::text(text)])
            })
        }
    }

    // Exact-2024 era: used only by legacy runtime-context tests.
    #[cfg(feature = "legacy-2024-11-05")]
    struct LegacyRootsContextTool;

    #[cfg(feature = "legacy-2024-11-05")]
    impl ToolHandler for LegacyRootsContextTool {
        fn definition(&self) -> Tool {
            Tool {
                name: "legacy_roots_context_tool".to_owned(),
                description: Some(
                    "Proves exact-2024 handlers receive only negotiated roots authority".to_owned(),
                ),
                input_schema: serde_json::json!({"type": "object"}),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(&self, ctx: &McpContext, _arguments: serde_json::Value) -> McpResult<Vec<Content>> {
            let text = if ctx.can_list_roots() {
                let roots = block_on(ctx.list_roots())?;
                format!(
                    "negotiated roots: {}",
                    roots.first().map_or("<none>", |root| root.uri.as_str())
                )
            } else {
                "roots authority unavailable".to_owned()
            };
            Ok(vec![Content::text(text)])
        }
    }

    fn final_progress_probe_number(source: &str) -> serde_json::Number {
        serde_json::from_str(source).expect("final progress probe number must parse")
    }

    fn report_final_progress_probe_updates(ctx: &McpContext) {
        // Signed values and values beyond total are valid final progress. The
        // final update differs only by a regressive progress value, so it
        // must not replace the latest monotonic pending notification.
        ctx.report_progress_exact(
            final_progress_probe_number("-2"),
            Some(final_progress_probe_number("-3")),
            Some("negative"),
        );
        ctx.report_progress_exact(
            final_progress_probe_number("12000"),
            Some(final_progress_probe_number("11999")),
            Some("latest"),
        );
        ctx.report_progress_exact(
            final_progress_probe_number("11999"),
            Some(final_progress_probe_number("11000")),
            Some("regressive"),
        );
    }

    struct HttpRequestScopedProgressTool {
        calls: Arc<AtomicUsize>,
    }

    impl ToolHandler for HttpRequestScopedProgressTool {
        fn definition(&self) -> Tool {
            Tool {
                name: "http_request_scoped_progress".to_owned(),
                description: Some(
                    "Proves final HTTP notifications remain request-scoped".to_owned(),
                ),
                input_schema: serde_json::json!({"type": "object"}),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(&self, ctx: &McpContext, _arguments: serde_json::Value) -> McpResult<Vec<Content>> {
            self.calls.fetch_add(1, Ordering::AcqRel);
            report_final_progress_probe_updates(ctx);
            Ok(vec![Content::text("HTTP progress completed")])
        }
    }

    struct HttpFinalProgressCancellationTool;

    impl ToolHandler for HttpFinalProgressCancellationTool {
        fn definition(&self) -> Tool {
            Tool {
                name: "http_final_progress_cancellation".to_owned(),
                description: Some(
                    "Proves cancellation discards staged final HTTP progress".to_owned(),
                ),
                input_schema: serde_json::json!({"type": "object"}),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(&self, ctx: &McpContext, _arguments: serde_json::Value) -> McpResult<Vec<Content>> {
            report_final_progress_probe_updates(ctx);
            Ok(vec![Content::text("cancellation requested")])
        }

        fn call_final_outcome_async_in_request<'a>(
            &'a self,
            ctx: &'a McpContext,
            _request_cx: &'a Cx,
            _arguments: serde_json::Value,
        ) -> BoxFuture<'a, fastmcp_core::McpOutcome<FinalToolOutcome>> {
            Box::pin(async move {
                report_final_progress_probe_updates(ctx);
                fastmcp_core::Outcome::Cancelled(asupersync::CancelReason::user(
                    "final HTTP progress cancellation probe",
                ))
            })
        }
    }

    fn live_http_mrtr_input_required() -> fastmcp_protocol::InputRequiredResult {
        let encoded = serde_json::json!({
            "resultType": "input_required",
            "inputRequests": {"roots": {"method": "roots/list"}},
            "requestState": "handler-forged-state",
        })
        .to_string();
        let (decoded, diagnostic) = decode_peer_result(
            &encoded,
            ResultPeerEra::Modern,
            &CoreResultDiscriminatorPolicy,
        )
        .expect("test input-required result must decode");
        assert!(diagnostic.is_none());
        let DecodedResult::InputRequired(result) = decoded else {
            panic!("test result must be input_required");
        };
        result
    }

    struct LiveHttpMrtrTool {
        name: &'static str,
        calls: Arc<AtomicUsize>,
    }

    #[derive(Clone, Copy)]
    enum PublicFinalElicitationMode {
        Form,
        Url,
    }

    struct PublicFinalElicitationTool {
        name: &'static str,
        mode: PublicFinalElicitationMode,
        calls: Arc<AtomicUsize>,
    }

    impl ToolHandler for PublicFinalElicitationTool {
        fn definition(&self) -> Tool {
            Tool {
                name: self.name.to_owned(),
                description: Some(
                    "Proves public final elicitation capability propagation".to_owned(),
                ),
                input_schema: serde_json::json!({"type": "object"}),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(
            &self,
            _ctx: &McpContext,
            _arguments: serde_json::Value,
        ) -> McpResult<Vec<Content>> {
            Ok(vec![Content::text("exact legacy result")])
        }

        fn declares_final_mrtr(&self) -> bool {
            true
        }

        fn call_final_outcome(
            &self,
            ctx: &McpContext,
            _arguments: serde_json::Value,
        ) -> McpResult<FinalToolOutcome> {
            self.calls.fetch_add(1, Ordering::AcqRel);
            let elicitation = match self.mode {
                PublicFinalElicitationMode::Form => ctx.final_elicitation_form(
                    "approval",
                    "Approve this operation",
                    serde_json::json!({
                        "type": "object",
                        "properties": {"approved": {"type": "boolean"}},
                        "required": ["approved"],
                    }),
                )?,
                PublicFinalElicitationMode::Url => ctx.final_elicitation_url(
                    "approval",
                    "Approve this operation",
                    "https://example.com/approve",
                )?,
            };
            Ok(FinalToolOutcome::InputRequired(
                elicitation.into_input_required()?,
            ))
        }
    }

    struct PublicFinalSamplingTool {
        calls: Arc<AtomicUsize>,
    }

    impl ToolHandler for PublicFinalSamplingTool {
        fn definition(&self) -> Tool {
            Tool {
                name: "public-final-sampling".to_owned(),
                description: Some("Proves public final sampling capability propagation".to_owned()),
                input_schema: serde_json::json!({"type": "object"}),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(
            &self,
            _ctx: &McpContext,
            _arguments: serde_json::Value,
        ) -> McpResult<Vec<Content>> {
            Ok(vec![Content::text("exact legacy result")])
        }

        fn declares_final_mrtr(&self) -> bool {
            true
        }

        fn call_final_outcome(
            &self,
            ctx: &McpContext,
            _arguments: serde_json::Value,
        ) -> McpResult<FinalToolOutcome> {
            let sampling = ctx.final_sampling(
                "sample",
                serde_json::from_value(serde_json::json!({
                    "messages": [{
                        "role": "assistant",
                        "content": {
                            "type": "tool_use",
                            "id": "weather-request",
                            "name": "weather",
                            "input": {"city": "Boston"},
                        },
                    }],
                    "maxTokens": 16,
                    "tools": [{
                        "name": "weather",
                        "inputSchema": {"type": "object"},
                    }],
                    "toolChoice": {"mode": "required"},
                }))
                .map_err(|error| McpError::internal_error(error.to_string()))?,
            )?;
            self.calls.fetch_add(1, Ordering::AcqRel);
            Ok(FinalToolOutcome::InputRequired(
                sampling.into_input_required()?,
            ))
        }

        fn call_final_outcome_async_resuming_in_request<'a>(
            &'a self,
            ctx: &'a McpContext,
            _request_cx: &'a Cx,
            arguments: serde_json::Value,
            resume_inputs: Option<&'a bidirectional::MrtrCompletedInputs>,
        ) -> BoxFuture<'a, fastmcp_core::McpOutcome<FinalToolOutcome>> {
            Box::pin(async move {
                let Some(inputs) = resume_inputs else {
                    return self
                        .call_final_outcome(ctx, arguments)
                        .map_or_else(fastmcp_core::Outcome::Err, fastmcp_core::Outcome::Ok);
                };
                match inputs.sampling("sample") {
                    Ok(Some(fastmcp_protocol::FinalCreateMessageResult {
                        content:
                            fastmcp_protocol::FinalSamplingMessageContent::Block(
                                fastmcp_protocol::FinalSamplingMessageContentBlock::ToolUse {
                                    ..
                                },
                            ),
                        ..
                    })) => {
                        self.calls.fetch_add(1, Ordering::AcqRel);
                        crate::handler::promote_legacy_tool_content(vec![Content::text(
                            "final sampling resumed with tool use",
                        )])
                        .map(FinalToolOutcome::Complete)
                        .map_or_else(fastmcp_core::Outcome::Err, fastmcp_core::Outcome::Ok)
                    }
                    Ok(Some(_)) => fastmcp_core::Outcome::Err(McpError::invalid_params(
                        "public final sampling test requires a tool-use result",
                    )),
                    Ok(None) => fastmcp_core::Outcome::Err(McpError::invalid_params(
                        "public final sampling retry lost its admitted input",
                    )),
                    Err(error) => fastmcp_core::Outcome::Err(error),
                }
            })
        }
    }

    impl ToolHandler for LiveHttpMrtrTool {
        fn definition(&self) -> Tool {
            Tool {
                name: self.name.to_owned(),
                description: Some(
                    "Proves bound MRTR resume across stateless HTTP POSTs".to_owned(),
                ),
                input_schema: serde_json::json!({"type": "object"}),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(
            &self,
            _ctx: &McpContext,
            _arguments: serde_json::Value,
        ) -> McpResult<Vec<Content>> {
            Ok(vec![Content::text("live HTTP MRTR resumed")])
        }

        fn call_final_outcome_async_resuming_in_request<'a>(
            &'a self,
            ctx: &'a McpContext,
            _request_cx: &'a Cx,
            arguments: serde_json::Value,
            resume_inputs: Option<&'a bidirectional::MrtrCompletedInputs>,
        ) -> BoxFuture<'a, fastmcp_core::McpOutcome<FinalToolOutcome>> {
            Box::pin(async move {
                self.calls.fetch_add(1, Ordering::AcqRel);
                match resume_inputs {
                    None => asupersync::Outcome::Ok(FinalToolOutcome::InputRequired(
                        live_http_mrtr_input_required(),
                    )),
                    Some(inputs) => match inputs.roots("roots") {
                        Ok(Some(_)) => self
                            .call_final(ctx, arguments)
                            .map(FinalToolOutcome::Complete)
                            .map_or_else(asupersync::Outcome::Err, asupersync::Outcome::Ok),
                        Ok(None) => asupersync::Outcome::Err(McpError::internal_error(
                            "live HTTP MRTR retry lost its roots input",
                        )),
                        Err(error) => asupersync::Outcome::Err(error),
                    },
                }
            })
        }
    }

    struct HttpSessionDisablingTool {
        calls: Arc<AtomicUsize>,
    }

    impl ToolHandler for HttpSessionDisablingTool {
        fn definition(&self) -> Tool {
            Tool {
                name: "http_session_disabling_tool".to_owned(),
                description: None,
                input_schema: serde_json::json!({"type": "object"}),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(&self, ctx: &McpContext, _arguments: serde_json::Value) -> McpResult<Vec<Content>> {
            self.calls.fetch_add(1, Ordering::AcqRel);
            if !ctx.disable_tool("http_session_disabling_tool") {
                return Err(McpError::internal_error(
                    "modern HTTP tool dispatch must have session state",
                ));
            }
            Ok(vec![Content::text("disabled for this HTTP session")])
        }
    }

    struct ModernHttpAuthCounterTool {
        calls: Arc<AtomicUsize>,
    }

    impl ToolHandler for ModernHttpAuthCounterTool {
        fn definition(&self) -> Tool {
            Tool {
                name: "modern_http_auth_counter".to_owned(),
                description: Some("Counts authenticated modern HTTP dispatches".to_owned()),
                input_schema: serde_json::json!({"type": "object"}),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(
            &self,
            _ctx: &McpContext,
            _arguments: serde_json::Value,
        ) -> McpResult<Vec<Content>> {
            self.calls.fetch_add(1, Ordering::AcqRel);
            Ok(vec![Content::text("authenticated modern HTTP dispatch")])
        }
    }

    #[derive(Clone)]
    struct ModernHttpAuthMiddleware {
        calls: Arc<AtomicUsize>,
        saw_credential: Arc<AtomicBool>,
    }

    impl Middleware for ModernHttpAuthMiddleware {
        fn on_request(
            &self,
            _ctx: &McpContext,
            request: &JsonRpcRequest,
        ) -> McpResult<MiddlewareDecision> {
            self.calls.fetch_add(1, Ordering::AcqRel);
            let serialized = serde_json::to_string(request)
                .map_err(|error| McpError::internal_error(error.to_string()))?;
            if serialized.contains("Bearer alpha") || serialized.contains("Bearer beta") {
                self.saw_credential.store(true, Ordering::Release);
            }
            Ok(MiddlewareDecision::Continue)
        }
    }

    struct ModernHttpAuthProvider;

    impl AuthProvider for ModernHttpAuthProvider {
        fn authenticate(
            &self,
            _ctx: &McpContext,
            request: AuthRequest<'_>,
        ) -> McpResult<AuthContext> {
            let access = request
                .access_token()
                .ok_or_else(|| McpError::new(McpErrorCode::ResourceForbidden, "missing bearer"))?;
            match access.token.as_str() {
                "alpha" | "beta" => Ok(AuthContext::with_subject(access.token)),
                _ => Err(McpError::new(
                    McpErrorCode::ResourceForbidden,
                    "unrecognized bearer",
                )),
            }
        }
    }

    #[derive(Clone)]
    struct OneShotNativeAuthProvider {
        calls: Arc<AtomicUsize>,
    }

    impl AuthProvider for OneShotNativeAuthProvider {
        fn authenticate(
            &self,
            _ctx: &McpContext,
            request: AuthRequest<'_>,
        ) -> McpResult<AuthContext> {
            // This is deliberately an attempt counter, not an accepted-token
            // counter: receipt custody must prove every provider evaluation.
            let call = self.calls.fetch_add(1, Ordering::AcqRel) + 1;
            let access = request
                .access_token()
                .ok_or_else(|| McpError::new(McpErrorCode::ResourceForbidden, "missing bearer"))?;
            if call == 1 && access.token.as_str() == "alpha" {
                Ok(AuthContext::with_subject("one-shot-alpha"))
            } else {
                Err(McpError::new(
                    McpErrorCode::ResourceForbidden,
                    "provider must not be evaluated twice",
                ))
            }
        }
    }

    // Exact-2024 era: used only by legacy HTTP SSE auth tests.
    #[cfg(feature = "legacy-2024-11-05")]
    #[derive(Clone)]
    struct CountingLegacyHttpAuthProvider {
        calls: Arc<AtomicUsize>,
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl AuthProvider for CountingLegacyHttpAuthProvider {
        fn authenticate(
            &self,
            _ctx: &McpContext,
            request: AuthRequest<'_>,
        ) -> McpResult<AuthContext> {
            self.calls.fetch_add(1, Ordering::AcqRel);
            let access = request
                .access_token()
                .ok_or_else(|| McpError::new(McpErrorCode::ResourceForbidden, "missing bearer"))?;
            if access.token.as_str() == "alpha" {
                Ok(AuthContext::with_subject("alice"))
            } else {
                Err(McpError::new(
                    McpErrorCode::ResourceForbidden,
                    "unrecognized bearer",
                ))
            }
        }
    }

    fn modern_http_json_tool_request(name: &str, id: i64) -> HttpRequest {
        let request = JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({
                "name": name,
                "arguments": {},
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                },
            })),
            id,
        );
        HttpRequest::new(HttpMethod::Post, "/mcp")
            .with_header("content-type", "application/json")
            .with_header("accept", "application/json")
            .with_header("mcp-protocol-version", MODERN_PROTOCOL_VERSION)
            .with_header("mcp-method", "tools/call")
            .with_header("mcp-name", name)
            .with_body(serde_json::to_vec(&request).expect("modern tool request must encode"))
    }

    fn auth_00_mrtr_provider(stable_owner: bool) -> TokenAuthProvider {
        let contexts = ["alpha", "beta"].map(|token| {
            let mut auth = AuthContext::with_subject(token);
            if stable_owner {
                auth = auth.with_session_owner(
                    fastmcp_core::sha256_bounded(token.as_bytes(), 32)
                        .expect("bounded configured owner"),
                );
            }
            (token, auth)
        });
        TokenAuthProvider::new(
            StaticTokenVerifier::new(contexts).expect("valid static token registration"),
        )
    }

    async fn auth_00_mrtr_http_call(
        cx: &Cx,
        endpoint: &ServerHttpEndpoint,
        state: Option<&str>,
        id: i64,
    ) -> JsonRpcResponse {
        let mut request = modern_http_json_tool_request("live_http_mrtr", id)
            .with_header("authorization", "Bearer alpha");
        if let Some(state) = state {
            let mut rpc: JsonRpcRequest = serde_json::from_slice(&request.body).unwrap();
            let params = rpc.params.as_mut().unwrap();
            params["requestState"] = serde_json::json!(state);
            params["inputResponses"] = serde_json::json!({
                "roots": bidirectional::MrtrInputResponse::roots(
                    fastmcp_protocol::ListRootsResult::empty(),
                ).expect("valid roots response"),
            });
            request.body = serde_json::to_vec(&rpc).unwrap();
        }
        let mut session = endpoint.open_session(cx).expect("fresh HTTP session");
        let response = asupersync::time::timeout(
            cx.now(),
            Duration::from_secs(5),
            Box::pin(session.handle_async(cx, request)),
        )
        .await
        .expect("MRTR HTTP handling must finish before the harness deadline")
        .expect("HTTP handling result");
        session.close(cx).await;
        let ServerHttpEndpointResponse::Immediate(response) = response else {
            panic!("ordinary MRTR request must return an immediate JSON response");
        };
        assert_eq!(response.status, HttpStatus::OK);
        let response: JsonRpcResponse = serde_json::from_slice(&response.body).unwrap();
        assert_eq!(response.id, Some(id.into()));
        response
    }

    /// How the MRTR test server's provider supplies the session owner.
    #[derive(Clone, Copy)]
    enum Auth00Owner {
        /// The verifier configures an explicit provider-scoped owner.
        Configured,
        /// A subject-only verified context. `TokenAuthProvider` derives its
        /// owner in a process-local namespace (756719c3).
        Derived,
        /// The same verified subject-only context, with no owner at all.
        Absent,
    }

    /// Verifies the same credentials through `TokenAuthProvider`, then
    /// rebuilds the admitted context without the owner that provider
    /// derives. Owner admission therefore sees a verified subject that
    /// really has no stable owner.
    struct OwnerlessAuthProvider(TokenAuthProvider);

    impl AuthProvider for OwnerlessAuthProvider {
        fn authenticate(
            &self,
            ctx: &McpContext,
            request: AuthRequest<'_>,
        ) -> McpResult<AuthContext> {
            let admitted = self.0.authenticate(ctx, request)?;
            let subject = admitted
                .subject
                .clone()
                .ok_or_else(|| McpError::internal_error("admitted context has no subject"))?;
            let mut ownerless = AuthContext::with_subject(subject);
            ownerless.scopes = admitted.scopes;
            ownerless.claims = admitted.claims;
            Ok(ownerless)
        }
    }

    fn auth_00_mrtr_server(owner: Auth00Owner, calls: &Arc<AtomicUsize>) -> Server {
        let builder = Server::new("auth-00-mrtr-owner", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("modern policy");
        let builder = match owner {
            Auth00Owner::Configured => builder.auth_provider(auth_00_mrtr_provider(true)),
            Auth00Owner::Derived => builder.auth_provider(auth_00_mrtr_provider(false)),
            Auth00Owner::Absent => {
                builder.auth_provider(OwnerlessAuthProvider(auth_00_mrtr_provider(false)))
            }
        };
        builder
            .tool(LiveHttpMrtrTool {
                name: "live_http_mrtr",
                calls: Arc::clone(calls),
            })
            .build()
    }

    fn assert_auth_00_mrtr_complete(response: &JsonRpcResponse) {
        assert!(response.error.is_none());
        let result = response.result.as_ref().expect("completed MRTR result");
        assert_eq!(result["resultType"], "complete");
        assert_eq!(
            result["content"],
            serde_json::json!([{"type": "text", "text": "live HTTP MRTR resumed"}]),
        );
    }

    #[test]
    fn auth_00_http_mrtr_stable_owner_completes_two_rounds() {
        assert_auth_00_http_mrtr_completes_two_rounds(Auth00Owner::Configured);
    }

    /// Pins 756719c3: `TokenAuthProvider` derives an owner for a subject-only
    /// verified context, so the same two rounds complete without a
    /// verifier-configured owner.
    #[test]
    fn auth_00_http_mrtr_derived_owner_completes_two_rounds() {
        assert_auth_00_http_mrtr_completes_two_rounds(Auth00Owner::Derived);
    }

    fn assert_auth_00_http_mrtr_completes_two_rounds(owner: Auth00Owner) {
        run_live_http_test(move |cx| async move {
            let calls = Arc::new(AtomicUsize::new(0));
            let endpoint = auth_00_mrtr_server(owner, &calls)
                .test_http_endpoint("http://auth-owner.test")
                .unwrap();
            let initial = auth_00_mrtr_http_call(&cx, &endpoint, None, 981).await;
            assert!(initial.error.is_none());
            let result = initial.result.as_ref().unwrap();
            assert_eq!(result["resultType"], "input_required");
            assert_eq!(result["inputRequests"]["roots"]["method"], "roots/list");
            let state = result["requestState"].as_str().unwrap();
            assert!(!state.is_empty());
            assert_ne!(state, "handler-forged-state");
            assert_eq!(endpoint.server.router.test_active_mrtr_exchange_count(), 1);
            assert_eq!(calls.load(Ordering::Acquire), 1);
            let retry = auth_00_mrtr_http_call(&cx, &endpoint, Some(state), 982).await;
            assert_auth_00_mrtr_complete(&retry);
            assert_eq!(calls.load(Ordering::Acquire), 2);
            assert_eq!(endpoint.server.router.test_active_mrtr_exchange_count(), 0);
            Ok(())
        });
    }

    #[test]
    fn auth_00_http_mrtr_subject_without_owner_rejects_without_allocating() {
        run_live_http_test(|cx| async move {
            let calls = Arc::new(AtomicUsize::new(0));
            // Same valid credential, subject, request and handler as the
            // positive; only the provider's stable owner is absent.
            let endpoint = auth_00_mrtr_server(Auth00Owner::Absent, &calls)
                .test_http_endpoint("http://auth-owner.test")
                .unwrap();
            let response = auth_00_mrtr_http_call(&cx, &endpoint, None, 981).await;
            assert!(response.result.is_none());
            let error = response.error.as_ref().expect("owner admission rejection");
            assert_eq!(error.code, McpErrorCode::InvalidParams.into());
            assert_eq!(calls.load(Ordering::Acquire), 1);
            assert_eq!(endpoint.server.router.test_active_mrtr_exchange_count(), 0);
            Ok(())
        });
    }

    #[test]
    fn auth_00_http_mrtr_ownerless_leaked_handle_preserves_owner_state() {
        run_live_http_test(|cx| async move {
            let calls = Arc::new(AtomicUsize::new(0));
            let owner_server = auth_00_mrtr_server(Auth00Owner::Configured, &calls);
            let mut ownerless_server = auth_00_mrtr_server(Auth00Owner::Absent, &calls);
            // Both public endpoints use the same real exchange registry.
            // Independent registries would reject even without owner checks.
            ownerless_server.router = Arc::clone(&owner_server.router);
            let owner = owner_server
                .test_http_endpoint("http://auth-owner.test")
                .unwrap();
            let ownerless = ownerless_server
                .test_http_endpoint("http://auth-owner.test")
                .unwrap();
            let initial = auth_00_mrtr_http_call(&cx, &owner, None, 991).await;
            assert!(initial.error.is_none());
            let state = initial.result.as_ref().unwrap()["requestState"]
                .as_str()
                .unwrap();
            assert_eq!(owner.server.router.test_active_mrtr_exchange_count(), 1);
            let denied = auth_00_mrtr_http_call(&cx, &ownerless, Some(state), 992).await;
            let unknown = auth_00_mrtr_http_call(&cx, &ownerless, Some("unknown"), 993).await;
            assert!(denied.result.is_none());
            assert!(unknown.result.is_none());
            let denied_error = denied.error.as_ref().unwrap();
            assert_eq!(denied_error.code, McpErrorCode::InvalidParams.into());
            assert_eq!(denied_error, unknown.error.as_ref().unwrap());
            assert_eq!(calls.load(Ordering::Acquire), 1);
            assert_eq!(owner.server.router.test_active_mrtr_exchange_count(), 1);
            let retry = auth_00_mrtr_http_call(&cx, &owner, Some(state), 994).await;
            assert_auth_00_mrtr_complete(&retry);
            assert_eq!(calls.load(Ordering::Acquire), 2);
            assert_eq!(owner.server.router.test_active_mrtr_exchange_count(), 0);
            Ok(())
        });
    }

    #[test]
    fn auth_00_http_mrtr_anonymous_complete_remains_available() {
        run_live_http_test(|cx| async move {
            let calls = Arc::new(AtomicUsize::new(0));
            let endpoint = Server::new("auth-00-anonymous-complete", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .unwrap()
                .tool(ModernHttpAuthCounterTool {
                    calls: Arc::clone(&calls),
                })
                .test_http_endpoint("http://auth-owner.test")
                .unwrap();
            let request = modern_http_json_tool_request("modern_http_auth_counter", 995);
            let mut session = endpoint.open_session(&cx).unwrap();
            let response = asupersync::time::timeout(
                cx.now(),
                Duration::from_secs(5),
                Box::pin(session.handle_async(&cx, request)),
            )
            .await
            .expect("anonymous complete call must finish before the harness deadline")
            .unwrap();
            session.close(&cx).await;
            let ServerHttpEndpointResponse::Immediate(response) = response else {
                panic!("anonymous complete call must return JSON");
            };
            assert_eq!(response.status, HttpStatus::OK);
            let rpc: JsonRpcResponse = serde_json::from_slice(&response.body).unwrap();
            assert_eq!(rpc.id, Some(995_i64.into()));
            assert!(rpc.error.is_none());
            let result = rpc.result.as_ref().unwrap();
            assert_eq!(result["resultType"], "complete");
            assert_eq!(
                result["content"],
                serde_json::json!([{
                    "type": "text",
                    "text": "authenticated modern HTTP dispatch",
                }]),
            );
            assert_eq!(calls.load(Ordering::Acquire), 1);
            assert_eq!(endpoint.server.router.test_active_mrtr_exchange_count(), 0);
            Ok(())
        });
    }

    async fn auth_00_handle_mrtr_http_request(
        cx: &Cx,
        session: &mut ServerHttpSession,
        request: HttpRequest,
    ) -> JsonRpcResponse {
        let response = asupersync::time::timeout(
            cx.now(),
            Duration::from_secs(5),
            Box::pin(session.handle_async(cx, request)),
        )
        .await
        .expect("MRTR owner lookup must finish before the harness deadline")
        .expect("MRTR HTTP handling must succeed");
        let ServerHttpEndpointResponse::Immediate(response) = response else {
            panic!("MRTR owner lookup must return immediate JSON");
        };
        assert_eq!(response.status, HttpStatus::OK);
        serde_json::from_slice(&response.body).expect("MRTR response must be JSON-RPC")
    }

    fn auth_00_http_mrtr_cancelled_state_probe(foreign_owner: bool) {
        run_live_http_test(move |cx| async move {
            for state_only in [false, true] {
                let calls = Arc::new(AtomicUsize::new(0));
                let endpoint = auth_00_mrtr_server(Auth00Owner::Configured, &calls)
                    .test_http_endpoint("http://auth-owner.test")
                    .unwrap();
                let mut issuer = endpoint.open_session(&cx).unwrap();
                let initial = auth_00_handle_mrtr_http_request(
                    &cx,
                    &mut issuer,
                    modern_http_json_tool_request("live_http_mrtr", 1001)
                        .with_header("authorization", "Bearer alpha"),
                )
                .await;
                assert_eq!(initial.id, Some(1001_i64.into()));
                assert!(initial.error.is_none());
                let result = initial.result.as_ref().unwrap();
                assert_eq!(result["resultType"], "input_required");
                assert_eq!(result["inputRequests"]["roots"]["method"], "roots/list");
                let state = result["requestState"].as_str().unwrap();
                assert!(!state.is_empty());
                assert_ne!(state, "handler-forged-state");
                assert_eq!(calls.load(Ordering::Acquire), 1);

                // Cancel the real continuation owner, which is distinct from
                // the already-finalized JSON-RPC request cancellation token.
                issuer.modern_connection.disconnect();
                let retry = |request_state: &str, bearer: &str, id: i64| {
                    let mut request = modern_http_json_tool_request("live_http_mrtr", id)
                        .with_header("authorization", format!("Bearer {bearer}"));
                    let mut rpc: JsonRpcRequest = serde_json::from_slice(&request.body).unwrap();
                    let params = rpc.params.as_mut().unwrap();
                    params["requestState"] = serde_json::json!(request_state);
                    if !state_only {
                        params["inputResponses"] = serde_json::json!({
                            "roots": bidirectional::MrtrInputResponse::roots(
                                fastmcp_protocol::ListRootsResult::empty(),
                            ).unwrap(),
                        });
                    }
                    request.body = serde_json::to_vec(&rpc).unwrap();
                    request
                };
                let bearer = if foreign_owner { "beta" } else { "alpha" };
                let mut caller = endpoint.open_session(&cx).unwrap();
                let observed =
                    auth_00_handle_mrtr_http_request(&cx, &mut caller, retry(state, bearer, 1002))
                        .await;
                assert_eq!(observed.id, Some(1002_i64.into()));
                assert!(observed.result.is_none());
                let observed_error = observed.error.as_ref().unwrap();
                assert_eq!(
                    observed_error.code,
                    if foreign_owner {
                        McpErrorCode::InvalidParams.into()
                    } else {
                        McpErrorCode::RequestCancelled.into()
                    }
                );
                let unknown = auth_00_handle_mrtr_http_request(
                    &cx,
                    &mut caller,
                    retry("unknown", bearer, 1003),
                )
                .await;
                assert_eq!(unknown.id, Some(1003_i64.into()));
                assert!(unknown.result.is_none());
                let unknown_error = unknown.error.as_ref().unwrap();
                assert_eq!(unknown_error.code, McpErrorCode::InvalidParams.into());
                if foreign_owner {
                    assert_eq!(observed_error, unknown_error);
                }
                assert_eq!(calls.load(Ordering::Acquire), 1);

                let mut owner = endpoint.open_session(&cx).unwrap();
                let retirement =
                    auth_00_handle_mrtr_http_request(&cx, &mut owner, retry(state, "alpha", 1004))
                        .await;
                assert_eq!(retirement.id, Some(1004_i64.into()));
                assert!(retirement.result.is_none());
                assert_eq!(
                    retirement.error.as_ref().unwrap().code,
                    if foreign_owner {
                        // The foreign lookup must not erase the cancelled
                        // record before its rightful owner observes it.
                        McpErrorCode::RequestCancelled.into()
                    } else {
                        McpErrorCode::InvalidParams.into()
                    }
                );
                let repeated =
                    auth_00_handle_mrtr_http_request(&cx, &mut owner, retry(state, "alpha", 1005))
                        .await;
                assert_eq!(repeated.id, Some(1005_i64.into()));
                assert!(repeated.result.is_none());
                assert_eq!(repeated.error.as_ref().unwrap(), unknown_error);
                assert_eq!(calls.load(Ordering::Acquire), 1);
                assert!(cx.checkpoint().is_ok());
                // Do not use active_len() here: it purges cancelled records
                // and would erase the evidence before the authorized retry.
                owner.close(&cx).await;
                caller.close(&cx).await;
                issuer.close(&cx).await;
            }
            Ok(())
        });
    }

    #[test]
    fn auth_00_http_mrtr_cancelled_state_owner_retires_positive() {
        auth_00_http_mrtr_cancelled_state_probe(false);
    }

    #[test]
    fn auth_00_http_mrtr_cancelled_state_foreign_owner_preserves_negative() {
        auth_00_http_mrtr_cancelled_state_probe(true);
    }

    struct Auth00GrantMrtrTool {
        calls: Arc<AtomicUsize>,
        state_only: bool,
    }

    impl ToolHandler for Auth00GrantMrtrTool {
        fn definition(&self) -> Tool {
            Tool {
                name: "auth_00_grant_mrtr".to_owned(),
                description: None,
                input_schema: serde_json::json!({"type": "object"}),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(&self, ctx: &McpContext, arguments: serde_json::Value) -> McpResult<Vec<Content>> {
            if !ctx
                .auth()
                .is_some_and(|auth| auth.scopes.iter().any(|scope| scope == "private:read"))
            {
                return Err(McpError::new(
                    McpErrorCode::ResourceForbidden,
                    "The private read grant is required",
                ));
            }
            let subject = arguments["subject"]
                .as_str()
                .ok_or_else(|| McpError::invalid_params("A subject is required"))?;
            Ok(vec![Content::text(subject)])
        }

        fn declares_final_mrtr(&self) -> bool {
            true
        }

        fn call_final_outcome_async_resuming_in_request<'a>(
            &'a self,
            ctx: &'a McpContext,
            _request_cx: &'a Cx,
            arguments: serde_json::Value,
            resume_inputs: Option<&'a bidirectional::MrtrCompletedInputs>,
        ) -> BoxFuture<'a, fastmcp_core::McpOutcome<FinalToolOutcome>> {
            Box::pin(async move {
                self.calls.fetch_add(1, Ordering::AcqRel);
                let result = (|| {
                    let content = self.call(ctx, arguments)?;
                    let Some(inputs) = resume_inputs else {
                        let requests = if self.state_only {
                            None
                        } else {
                            live_http_mrtr_input_required().input_requests().cloned()
                        };
                        return Ok(FinalToolOutcome::InputRequired(
                            fastmcp_protocol::InputRequiredResult::new(
                                requests,
                                Some("grant-bound-private-state".to_owned()),
                                fastmcp_protocol::ResultMeta::empty(),
                            )
                            .expect("real state-only or roots continuation"),
                        ));
                    };
                    assert_eq!(
                        inputs.handler_request_state(),
                        Some("grant-bound-private-state"),
                    );
                    if self.state_only {
                        assert!(inputs.responses().is_empty());
                    } else {
                        assert_eq!(inputs.responses().len(), 1);
                        assert_eq!(
                            serde_json::to_value(
                                inputs.roots("roots")?.expect("admitted roots input"),
                            )
                            .expect("roots response serializes"),
                            serde_json::json!({"roots": []}),
                        );
                    }
                    crate::handler::promote_legacy_tool_content(content)
                        .map(FinalToolOutcome::Complete)
                })();
                result.map_or_else(asupersync::Outcome::Err, asupersync::Outcome::Ok)
            })
        }
    }

    fn auth_00_http_mrtr_grant_snapshot_probe(reduced_grants: bool) {
        run_live_http_test(move |cx| async move {
            for state_only in [false, true] {
                let calls = Arc::new(AtomicUsize::new(0));
                let owner = fastmcp_core::sha256_bounded(b"grant-snapshot-owner", 32).unwrap();
                let mut initial_auth =
                    AuthContext::with_subject("same-owner").with_session_owner(owner);
                initial_auth.scopes = vec!["private:read".to_owned(), "public:list".to_owned()];
                let mut retry_auth = initial_auth.clone();
                // Both tests rotate alpha to beta. Only the required grant
                // differs; reordering and duplicate grants remain equivalent.
                retry_auth.scopes = vec!["public:list".to_owned(), "public:list".to_owned()];
                if !reduced_grants {
                    retry_auth.scopes.push("private:read".to_owned());
                }
                let provider = TokenAuthProvider::new(
                    StaticTokenVerifier::new([("alpha", initial_auth), ("beta", retry_auth)])
                        .expect("real same-owner token registrations"),
                );
                let endpoint = Server::new("auth-00-grants", "1.0.0")
                    .protocol_policy(ProtocolPolicy::ModernOnly)
                    .unwrap()
                    .auth_provider(provider)
                    .tool(Auth00GrantMrtrTool {
                        calls: Arc::clone(&calls),
                        state_only,
                    })
                    .test_http_endpoint("http://auth-grants.test")
                    .unwrap();
                let subject = format!("private-result-{}-{state_only}", cx.now().as_nanos());
                let request = |request_state: Option<&str>, bearer: &str, id: i64| {
                    let mut request = modern_http_json_tool_request("auth_00_grant_mrtr", id)
                        .with_header("authorization", format!("Bearer {bearer}"));
                    let mut rpc: JsonRpcRequest = serde_json::from_slice(&request.body).unwrap();
                    let params = rpc.params.as_mut().unwrap();
                    params["arguments"] = serde_json::json!({"subject": subject});
                    if let Some(state) = request_state {
                        params["requestState"] = serde_json::json!(state);
                        if !state_only {
                            params["inputResponses"] = serde_json::json!({
                                "roots": bidirectional::MrtrInputResponse::roots(
                                    fastmcp_protocol::ListRootsResult::empty(),
                                ).unwrap(),
                            });
                        }
                    }
                    request.body = serde_json::to_vec(&rpc).unwrap();
                    request
                };
                let mut issuer = endpoint.open_session(&cx).unwrap();
                let initial = auth_00_handle_mrtr_http_request(
                    &cx,
                    &mut issuer,
                    request(None, "alpha", 1011),
                )
                .await;
                assert_eq!(initial.id, Some(1011_i64.into()));
                assert!(initial.error.is_none());
                let initial_result = initial.result.as_ref().unwrap();
                assert_eq!(initial_result["resultType"], "input_required");
                if state_only {
                    assert!(initial_result.get("inputRequests").is_none());
                } else {
                    assert_eq!(
                        initial_result["inputRequests"],
                        serde_json::json!({"roots": {"method": "roots/list"}}),
                    );
                }
                let state = initial_result["requestState"].as_str().unwrap();
                assert!(!state.is_empty());
                assert_ne!(state, "grant-bound-private-state");
                assert_eq!(calls.load(Ordering::Acquire), 1);
                issuer.close(&cx).await;

                let mut caller = endpoint.open_session(&cx).unwrap();
                let retry = auth_00_handle_mrtr_http_request(
                    &cx,
                    &mut caller,
                    request(Some(state), "beta", 1012),
                )
                .await;
                assert_eq!(retry.id, Some(1012_i64.into()));
                let unknown = auth_00_handle_mrtr_http_request(
                    &cx,
                    &mut caller,
                    request(Some("unknown"), "beta", 1013),
                )
                .await;
                assert_eq!(unknown.id, Some(1013_i64.into()));
                assert!(unknown.result.is_none());
                let unknown_error = unknown.error.as_ref().unwrap();
                assert_eq!(unknown_error.code, McpErrorCode::InvalidParams.into());
                let completed = if reduced_grants {
                    assert!(retry.result.is_none());
                    assert_eq!(retry.error.as_ref().unwrap(), unknown_error);
                    assert_eq!(calls.load(Ordering::Acquire), 1);
                    let mut rightful = endpoint.open_session(&cx).unwrap();
                    let response = auth_00_handle_mrtr_http_request(
                        &cx,
                        &mut rightful,
                        request(Some(state), "alpha", 1014),
                    )
                    .await;
                    assert_eq!(response.id, Some(1014_i64.into()));
                    rightful.close(&cx).await;
                    response
                } else {
                    retry
                };
                assert!(completed.error.is_none());
                let result = completed.result.as_ref().unwrap();
                assert_eq!(result["resultType"], "complete");
                assert_eq!(
                    result["content"],
                    serde_json::json!([{"type": "text", "text": subject}]),
                );
                assert_eq!(calls.load(Ordering::Acquire), 2);
                let replay = auth_00_handle_mrtr_http_request(
                    &cx,
                    &mut caller,
                    request(Some(state), "beta", 1015),
                )
                .await;
                assert_eq!(replay.id, Some(1015_i64.into()));
                assert!(replay.result.is_none());
                assert_eq!(replay.error.as_ref().unwrap(), unknown_error);
                assert_eq!(calls.load(Ordering::Acquire), 2);
                assert!(cx.checkpoint().is_ok());
                caller.close(&cx).await;
            }
            Ok(())
        });
    }

    #[test]
    fn auth_00_http_mrtr_unchanged_grants_rotation_completes_positive() {
        auth_00_http_mrtr_grant_snapshot_probe(false);
    }

    #[test]
    fn auth_00_http_mrtr_reduced_grants_preserve_state_negative() {
        auth_00_http_mrtr_grant_snapshot_probe(true);
    }

    async fn run_live_http_mrtr_retry(
        cx: &Cx,
        request_state_suffix: &str,
    ) -> Result<(JsonRpcResponse, JsonRpcResponse, usize), String> {
        let calls = Arc::new(AtomicUsize::new(0));
        let bound = Server::new("live-http-mrtr-retry", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .auth_provider(auth_00_mrtr_provider(true))
            .tool(LiveHttpMrtrTool {
                name: "live_http_mrtr",
                calls: Arc::clone(&calls),
            })
            .build()
            .bind_http(cx, "127.0.0.1:0")
            .await
            .map_err(|error| format!("live HTTP MRTR retry bind failed: {error}"))?;
        let address = bound
            .local_addr()
            .map_err(|error| format!("live HTTP MRTR retry address failed: {error}"))?;
        let request_state_suffix = request_state_suffix.to_owned();
        let caller_cx = cx.clone();
        let mut client = cx
            .spawn(move |_client_cx| async move {
                let result = async {
                    let initial = JsonRpcRequest::new(
                        "tools/call",
                        Some(serde_json::json!({
                            "name": "live_http_mrtr",
                            "arguments": {},
                            "_meta": {
                                MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                                FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                                "progressToken": "live-http-mrtr-sse",
                            },
                        })),
                        922_i64,
                    );
                    let initial_body = serde_json::to_vec(&initial).map_err(|error| {
                        format!("MRTR initial request did not serialize: {error}")
                    })?;
                    let initial = live_http_exchange(
                        address,
                        live_http_post(
                            "/mcp",
                            &initial_body,
                            &[
                                ("Accept", "text/event-stream"),
                                ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                ("Mcp-Method", "tools/call"),
                                ("Mcp-Name", "live_http_mrtr"),
                                ("Authorization", "Bearer alpha"),
                            ],
                        ),
                    )
                    .await?;
                    let initial = live_http_sse_jsonrpc_response(&initial)?;
                    let request_state = initial
                        .result
                        .as_ref()
                        .and_then(|result| result.get("requestState"))
                        .and_then(serde_json::Value::as_str)
                        .ok_or_else(|| {
                            "MRTR input-required response omitted requestState".to_owned()
                        })?;
                    let roots = serde_json::to_value(
                        bidirectional::MrtrInputResponse::roots(
                            fastmcp_protocol::ListRootsResult::empty(),
                        )
                        .map_err(|error| format!("MRTR roots response failed: {error}"))?,
                    )
                    .map_err(|error| format!("MRTR roots response did not serialize: {error}"))?;
                    // The retry leg reads its result from an ordinary JSON
                    // response; a progress token would demand an owned SSE
                    // body and turn this Accept into a 406.
                    let retry = JsonRpcRequest::new(
                        "tools/call",
                        Some(serde_json::json!({
                            "name": "live_http_mrtr",
                            "arguments": {},
                            "inputResponses": {"roots": roots},
                            "requestState": format!("{request_state}{request_state_suffix}"),
                            "_meta": {
                                MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                                FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                            },
                        })),
                        923_i64,
                    );
                    let retry_body = serde_json::to_vec(&retry).map_err(|error| {
                        format!("MRTR retry request did not serialize: {error}")
                    })?;
                    let retry = live_http_exchange(
                        address,
                        live_http_post(
                            "/mcp",
                            &retry_body,
                            &[
                                ("Accept", "application/json"),
                                ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                ("Mcp-Method", "tools/call"),
                                ("Mcp-Name", "live_http_mrtr"),
                                ("Authorization", "Bearer alpha"),
                            ],
                        ),
                    )
                    .await?;
                    let retry = serde_json::from_slice(live_http_response_body(&retry)?).map_err(
                        |error| format!("MRTR retry response was not valid JSON-RPC: {error}"),
                    )?;
                    Ok::<_, String>((initial, retry))
                }
                .await;
                caller_cx.cancel_with(
                    CancelKind::User,
                    Some("live HTTP cross-POST MRTR retry complete"),
                );
                result
            })
            .map_err(|error| format!("live HTTP MRTR retry client admission failed: {error}"))?;

        let serve = bound.serve(cx).await;
        let (initial, retry) = client
            .join(cx)
            .await
            .map_err(|error| format!("live HTTP MRTR retry client failed: {error:?}"))??;
        let shutdown =
            serve.map_err(|error| format!("live HTTP MRTR retry server failed: {error}"))?;
        require_quiescent_http_shutdown(shutdown, "live HTTP MRTR retry").await?;
        Ok((initial, retry, calls.load(Ordering::Acquire)))
    }

    async fn run_live_http_public_final_sampling_json(
        cx: &Cx,
    ) -> Result<(JsonRpcResponse, usize), String> {
        let calls = Arc::new(AtomicUsize::new(0));
        let bound = Server::new("live-http-public-final-sampling", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .auth_provider(auth_00_mrtr_provider(true))
            .tool(PublicFinalSamplingTool {
                calls: Arc::clone(&calls),
            })
            .build()
            .bind_http(cx, "127.0.0.1:0")
            .await
            .map_err(|error| format!("live HTTP public final sampling bind failed: {error}"))?;
        let address = bound
            .local_addr()
            .map_err(|error| format!("live HTTP public final sampling address failed: {error}"))?;
        let caller_cx = cx.clone();
        let mut client = cx
            .spawn(move |_client_cx| async move {
                let result = async {
                    let request = JsonRpcRequest::new(
                        "tools/call",
                        Some(serde_json::json!({
                            "name": "public-final-sampling",
                            "arguments": {},
                            "_meta": {
                                MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                                FINAL_CLIENT_CAPABILITIES_META_KEY: {"sampling": {}},
                            },
                        })),
                        940_i64,
                    );
                    let body = serde_json::to_vec(&request).map_err(|error| {
                        format!("public final sampling request did not serialize: {error}")
                    })?;
                    let response = live_http_exchange(
                        address,
                        live_http_post(
                            "/mcp",
                            &body,
                            &[
                                ("Accept", "application/json"),
                                ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                ("Mcp-Method", "tools/call"),
                                ("Mcp-Name", "public-final-sampling"),
                                ("Authorization", "Bearer alpha"),
                            ],
                        ),
                    )
                    .await?;
                    let response = serde_json::from_slice(live_http_response_body(&response)?)
                        .map_err(|error| {
                            format!(
                                "public final sampling response was not valid JSON-RPC: {error}"
                            )
                        })?;
                    Ok::<_, String>(response)
                }
                .await;
                caller_cx.cancel_with(
                    CancelKind::User,
                    Some("live HTTP public final sampling complete"),
                );
                result
            })
            .map_err(|error| {
                format!("live HTTP public final sampling client admission failed: {error}")
            })?;

        let serve = bound.serve(cx).await;
        let response = client.join(cx).await.map_err(|error| {
            format!("live HTTP public final sampling client failed: {error:?}")
        })??;
        let shutdown = serve
            .map_err(|error| format!("live HTTP public final sampling server failed: {error}"))?;
        require_quiescent_http_shutdown(shutdown, "live HTTP public final sampling").await?;
        Ok((response, calls.load(Ordering::Acquire)))
    }

    struct LiveLegacyCompletionHandler;

    impl CompletionHandler for LiveLegacyCompletionHandler {
        fn complete_legacy(
            &self,
            _ctx: &McpContext,
            params: LegacyCompletionParams,
        ) -> McpResult<CompletionValues> {
            Ok(CompletionValues {
                values: vec![format!("legacy:{}", params.argument.value)],
                total: Some(1),
                has_more: Some(false),
            })
        }

        fn complete_final(
            &self,
            _ctx: &McpContext,
            _params: FinalCompletionParams,
        ) -> McpResult<fastmcp_protocol::FinalCompletionValues> {
            Err(McpError::method_not_found("completion/complete"))
        }
    }

    // Exact-2024 era: used only by legacy completion tests.
    #[cfg(feature = "legacy-2024-11-05")]
    struct CountingLegacyCompletionHandler {
        calls: Arc<AtomicUsize>,
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl CompletionHandler for CountingLegacyCompletionHandler {
        fn complete_legacy(
            &self,
            _ctx: &McpContext,
            params: LegacyCompletionParams,
        ) -> McpResult<CompletionValues> {
            self.calls.fetch_add(1, Ordering::AcqRel);
            Ok(CompletionValues {
                values: vec![format!("legacy:{}", params.argument.value)],
                total: Some(1),
                has_more: Some(false),
            })
        }

        fn complete_final(
            &self,
            _ctx: &McpContext,
            _params: FinalCompletionParams,
        ) -> McpResult<fastmcp_protocol::FinalCompletionValues> {
            Err(McpError::method_not_found("completion/complete"))
        }
    }

    // Exact-2024 era: used only by legacy HTTP SSE cancellation tests.
    #[cfg(feature = "legacy-2024-11-05")]
    struct LiveLegacyCancellationTool {
        started: Arc<AtomicBool>,
        observed_cancellation: Arc<AtomicBool>,
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl ToolHandler for LiveLegacyCancellationTool {
        fn definition(&self) -> Tool {
            Tool {
                name: "live_legacy_cancellation_tool".to_owned(),
                description: Some(
                    "Proves exact legacy cancellation reaches the live handler".to_owned(),
                ),
                input_schema: serde_json::json!({"type": "object"}),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(&self, ctx: &McpContext, _arguments: serde_json::Value) -> McpResult<Vec<Content>> {
            self.started.store(true, Ordering::Release);
            let deadline = Instant::now() + Duration::from_nanos(LIVE_HTTP_STEP_TIMEOUT_NANOS);
            while !ctx.is_cancelled() && Instant::now() < deadline {
                std::thread::yield_now();
            }
            if ctx.is_cancelled() {
                self.observed_cancellation.store(true, Ordering::Release);
                return Err(McpError::request_cancelled());
            }
            Err(McpError::internal_error(
                "exact legacy cancellation did not reach the live handler",
            ))
        }
    }

    struct LiveModernHttpPeerCancellationTool {
        started: Arc<AtomicBool>,
        release: Arc<AtomicBool>,
        observed_cancellation: Arc<AtomicBool>,
    }

    impl ToolHandler for LiveModernHttpPeerCancellationTool {
        fn definition(&self) -> Tool {
            Tool {
                name: "live_modern_http_peer_cancellation_tool".to_owned(),
                description: Some(
                    "Proves ordinary modern JSON peer close reaches only its handler".to_owned(),
                ),
                input_schema: serde_json::json!({"type": "object"}),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(&self, ctx: &McpContext, _arguments: serde_json::Value) -> McpResult<Vec<Content>> {
            self.started.store(true, Ordering::Release);
            let deadline = Instant::now() + Duration::from_nanos(LIVE_HTTP_STEP_TIMEOUT_NANOS);
            while !self.release.load(Ordering::Acquire)
                && !ctx.is_cancelled()
                && Instant::now() < deadline
            {
                std::thread::yield_now();
            }
            if ctx.is_cancelled() {
                self.observed_cancellation.store(true, Ordering::Release);
                return Err(McpError::request_cancelled());
            }
            if !self.release.load(Ordering::Acquire) {
                return Err(McpError::internal_error(
                    "ordinary modern JSON peer cancellation did not reach the handler",
                ));
            }
            Ok(vec![Content::text(
                "ordinary modern JSON request completed",
            )])
        }
    }

    // Exact-2024 era: used only by the legacy HTTP SSE shutdown probe.
    #[cfg(feature = "legacy-2024-11-05")]
    struct LiveHttpShutdownTool {
        name: &'static str,
        cooperate_with_cancellation: bool,
        started: Arc<AtomicBool>,
        cancellation_observed: Arc<AtomicBool>,
        release: Arc<AtomicBool>,
        finished: Arc<AtomicBool>,
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl ToolHandler for LiveHttpShutdownTool {
        fn definition(&self) -> Tool {
            Tool {
                name: self.name.to_owned(),
                description: Some(
                    "Proves live HTTP shutdown ownership for a synchronous handler".to_owned(),
                ),
                input_schema: serde_json::json!({"type": "object"}),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(&self, ctx: &McpContext, _arguments: serde_json::Value) -> McpResult<Vec<Content>> {
            self.started.store(true, Ordering::Release);
            loop {
                if ctx.is_cancelled() {
                    self.cancellation_observed.store(true, Ordering::Release);
                    if self.cooperate_with_cancellation {
                        self.finished.store(true, Ordering::Release);
                        return Err(McpError::request_cancelled());
                    }
                }
                if self.release.load(Ordering::Acquire) {
                    self.finished.store(true, Ordering::Release);
                    return Ok(Vec::new());
                }
                thread::yield_now();
                thread::sleep(Duration::from_millis(1));
            }
        }
    }

    // Exact-2024 era: gates legacy HTTP request handlers.
    #[cfg(feature = "legacy-2024-11-05")]
    #[derive(Default)]
    struct LiveLegacyRequestGate {
        entered: AtomicBool,
        released: AtomicBool,
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl LiveLegacyRequestGate {
        fn enter(&self, ctx: &McpContext) -> McpResult<()> {
            self.entered.store(true, Ordering::Release);
            let deadline = Instant::now() + Duration::from_nanos(LIVE_HTTP_STEP_TIMEOUT_NANOS);
            while !self.released.load(Ordering::Acquire) && Instant::now() < deadline {
                if ctx.is_cancelled() {
                    return Err(McpError::request_cancelled());
                }
                thread::yield_now();
                thread::sleep(Duration::from_millis(1));
            }
            if self.released.load(Ordering::Acquire) {
                Ok(())
            } else {
                Err(McpError::internal_error(
                    "bounded legacy HTTP request gate was not released",
                ))
            }
        }

        fn release(&self) {
            self.released.store(true, Ordering::Release);
        }
    }

    #[cfg(feature = "legacy-2024-11-05")]
    struct LiveLegacyRequestGateRelease {
        gate: Arc<LiveLegacyRequestGate>,
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl Drop for LiveLegacyRequestGateRelease {
        fn drop(&mut self) {
            self.gate.release();
        }
    }

    // Exact-2024 era: holds a legacy HTTP session's mutex.
    #[cfg(feature = "legacy-2024-11-05")]
    struct LiveHttpSessionMutexHold {
        release: Option<std::sync::mpsc::SyncSender<()>>,
        worker: Option<thread::JoinHandle<Result<(), String>>>,
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl LiveHttpSessionMutexHold {
        fn new(session: Arc<LiveHttpSession>) -> Result<Self, String> {
            let (started_sender, started_receiver) = sync_channel(1);
            let (release_sender, release_receiver) = sync_channel(1);
            let worker = thread::spawn(move || {
                let _session = session
                    .session
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                started_sender
                    .send(())
                    .map_err(|_| "legacy HTTP session holder lost its test owner".to_string())?;
                release_receiver
                    .recv_timeout(Duration::from_nanos(LIVE_HTTP_STEP_TIMEOUT_NANOS))
                    .map_err(|_| "legacy HTTP session holder release timed out".to_string())?;
                Ok(())
            });
            let mut hold = Self {
                release: Some(release_sender),
                worker: Some(worker),
            };
            if started_receiver
                .recv_timeout(Duration::from_nanos(LIVE_HTTP_STEP_TIMEOUT_NANOS))
                .is_err()
            {
                let _ = hold.release();
                return Err("legacy HTTP session holder did not acquire the mutex".to_string());
            }
            Ok(hold)
        }

        fn release(&mut self) -> Result<(), String> {
            if let Some(sender) = self.release.take() {
                sender.send(()).map_err(|_| {
                    "legacy HTTP session holder release was disconnected".to_string()
                })?;
            }
            let Some(worker) = self.worker.take() else {
                return Ok(());
            };
            worker
                .join()
                .map_err(|_| "legacy HTTP session holder panicked".to_string())?
        }
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl Drop for LiveHttpSessionMutexHold {
        fn drop(&mut self) {
            let _ = self.release();
        }
    }

    // Exact-2024 era: used only by legacy HTTP admission tests.
    #[cfg(feature = "legacy-2024-11-05")]
    struct LiveLegacyAdmissionBlocker {
        gate: Arc<LiveLegacyRequestGate>,
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl ToolHandler for LiveLegacyAdmissionBlocker {
        fn definition(&self) -> Tool {
            Tool {
                name: "live_legacy_admission_blocker".to_owned(),
                description: Some(
                    "Holds the exact legacy HTTP session mutex at a bounded test gate".to_owned(),
                ),
                input_schema: serde_json::json!({"type": "object"}),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(&self, ctx: &McpContext, _arguments: serde_json::Value) -> McpResult<Vec<Content>> {
            self.gate.enter(ctx)?;
            Ok(vec![Content::text("legacy admission blocker released")])
        }
    }

    // Exact-2024 era: used only by legacy HTTP admission tests.
    #[cfg(feature = "legacy-2024-11-05")]
    struct LiveLegacyAdmissionTarget {
        calls: Arc<AtomicUsize>,
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl ToolHandler for LiveLegacyAdmissionTarget {
        fn definition(&self) -> Tool {
            Tool {
                name: "live_legacy_admission_target".to_owned(),
                description: Some(
                    "Records whether a queued exact legacy HTTP request entered its handler"
                        .to_owned(),
                ),
                input_schema: serde_json::json!({"type": "object"}),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(&self, ctx: &McpContext, _arguments: serde_json::Value) -> McpResult<Vec<Content>> {
            self.calls.fetch_add(1, Ordering::AcqRel);
            ctx.checkpoint()
                .map_err(|_| McpError::request_cancelled())?;
            Ok(vec![Content::text("legacy admission target entered")])
        }
    }

    #[derive(Default)]
    struct NonQuiescentLegacyState {
        started: bool,
        released: bool,
        finished: bool,
    }

    #[derive(Default)]
    struct NonQuiescentLegacyControl {
        state: Mutex<NonQuiescentLegacyState>,
        changed: Condvar,
    }

    impl NonQuiescentLegacyControl {
        /// How long a deliberately non-cooperative handler waits for its test
        /// to release it. A test that fails before releasing would otherwise
        /// leave the handler thread blocked and hang the process.
        const RELEASE_BOUND: Duration = Duration::from_secs(60);

        fn wait_until_released(&self) {
            let state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let mut state = state;
            state.started = true;
            self.changed.notify_all();
            let (mut state, waited) = self
                .changed
                .wait_timeout_while(state, Self::RELEASE_BOUND, |state| !state.released)
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            assert!(
                !waited.timed_out(),
                "non-quiescent test handler was not released within {:?}; its test stopped before releasing it",
                Self::RELEASE_BOUND
            );
            state.finished = true;
            self.changed.notify_all();
        }

        fn wait_for_started(&self, timeout: Duration) -> bool {
            let state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let (state, _) = self
                .changed
                .wait_timeout_while(state, timeout, |state| !state.started)
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            state.started
        }

        fn has_started(&self) -> bool {
            self.state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .started
        }

        fn has_finished(&self) -> bool {
            self.state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .finished
        }

        fn release(&self) {
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            state.released = true;
            self.changed.notify_all();
        }

        fn wait_for_finished(&self, timeout: Duration) -> bool {
            let state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let (state, _) = self
                .changed
                .wait_timeout_while(state, timeout, |state| !state.finished)
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            state.finished
        }
    }

    // Exact-2024 era: reached only through a legacy opening.
    #[cfg(feature = "legacy-2024-11-05")]
    struct NonQuiescentLegacyTool {
        control: Arc<NonQuiescentLegacyControl>,
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl ToolHandler for NonQuiescentLegacyTool {
        fn definition(&self) -> Tool {
            Tool {
                name: "non_quiescent_legacy_tool".to_owned(),
                description: Some(
                    "Test-only legacy handler that deliberately ignores cancellation".to_owned(),
                ),
                input_schema: serde_json::json!({"type": "object"}),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(
            &self,
            _ctx: &McpContext,
            _arguments: serde_json::Value,
        ) -> McpResult<Vec<Content>> {
            self.control.wait_until_released();
            Ok(vec![Content::text("non-quiescent legacy handler released")])
        }
    }

    struct NonQuiescentModernTool {
        control: Arc<NonQuiescentLegacyControl>,
    }

    impl ToolHandler for NonQuiescentModernTool {
        fn definition(&self) -> Tool {
            Tool {
                name: "non_quiescent_modern_tool".to_owned(),
                description: Some("Test-only non-cooperative modern handler".to_owned()),
                input_schema: serde_json::json!({"type": "object"}),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(
            &self,
            _ctx: &McpContext,
            _arguments: serde_json::Value,
        ) -> McpResult<Vec<Content>> {
            self.control.wait_until_released();
            Ok(vec![Content::text("non-quiescent modern child released")])
        }
    }

    // Exact-2024 era: scripts a legacy opening.
    #[cfg(feature = "legacy-2024-11-05")]
    struct NonQuiescentLegacySplitRecv {
        phase: usize,
        control: Arc<NonQuiescentLegacyControl>,
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl TransportRecvHalf for NonQuiescentLegacySplitRecv {
        fn recv(&mut self, _cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
            let phase = self.phase;
            self.phase = self.phase.saturating_add(1);
            match phase {
                0 => Ok(exact_legacy_initialize_request(
                    707,
                    serde_json::json!("1.0.0"),
                )),
                1 => Ok(JsonRpcMessage::Request(JsonRpcRequest::notification(
                    "notifications/initialized",
                    None,
                ))),
                2 => Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                    "tools/call",
                    Some(serde_json::json!({
                        "name": "non_quiescent_legacy_tool",
                        "arguments": {},
                    })),
                    708_i64,
                ))),
                3 if self.control.wait_for_started(Duration::from_secs(2)) => {
                    Err(TransportError::Closed)
                }
                3 => Err(TransportError::Timeout),
                _ => Err(TransportError::Closed),
            }
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            Ok(())
        }
    }

    struct NonQuiescentLegacySplitSend;

    impl TransportSendHalf for NonQuiescentLegacySplitSend {
        fn send(&mut self, _cx: &Cx, _message: &JsonRpcMessage) -> Result<(), TransportError> {
            Ok(())
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            Ok(())
        }
    }

    struct NonQuiescentModernSplitRecv {
        phase: usize,
    }

    impl TransportRecvHalf for NonQuiescentModernSplitRecv {
        fn recv(&mut self, _cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
            let phase = self.phase;
            self.phase = self.phase.saturating_add(1);
            match phase {
                0 => Ok(modern_discovery_opening_request()),
                1 => Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                    "tools/call",
                    Some(serde_json::json!({
                        "name": "non_quiescent_modern_tool",
                        "arguments": {},
                        "_meta": {
                            MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                            FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                        },
                    })),
                    709_i64,
                ))),
                _ => Err(TransportError::Closed),
            }
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            Ok(())
        }
    }

    #[derive(Default)]
    struct LiveModernControlState {
        active: usize,
        max_active: usize,
        started: HashSet<u64>,
        cancelled: HashSet<u64>,
        released: HashSet<u64>,
        release_all: bool,
    }

    #[derive(Default)]
    struct LiveModernControl {
        state: Mutex<LiveModernControlState>,
        changed: Condvar,
        shutdown_requested: AtomicBool,
        shutdown_cx: Mutex<Option<Cx>>,
    }

    impl LiveModernControl {
        fn call(&self, ctx: &McpContext) -> McpResult<Vec<Content>> {
            let request_id = ctx.request_id();
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            state.active += 1;
            state.max_active = state.max_active.max(state.active);
            state.started.insert(request_id);
            self.changed.notify_all();

            loop {
                if ctx.is_cancelled() {
                    state.active = state.active.saturating_sub(1);
                    state.cancelled.insert(request_id);
                    self.changed.notify_all();
                    return Err(McpError::request_cancelled());
                }
                if state.release_all || state.released.contains(&request_id) {
                    state.active = state.active.saturating_sub(1);
                    self.changed.notify_all();
                    return Ok(vec![Content::text(format!("modern request {request_id}"))]);
                }
                let (next, _) = self
                    .changed
                    .wait_timeout(state, Duration::from_millis(1))
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                state = next;
            }
        }

        fn wait_for_started(&self, count: usize, timeout: Duration) -> bool {
            let state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let (state, _) = self
                .changed
                .wait_timeout_while(state, timeout, |state| state.started.len() < count)
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            state.started.len() >= count
        }

        fn has_started(&self, request_id: u64) -> bool {
            self.state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .started
                .contains(&request_id)
        }

        fn wait_for_cancellation(&self, request_id: u64, timeout: Duration) -> bool {
            let state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let (state, _) = self
                .changed
                .wait_timeout_while(state, timeout, |state| {
                    !state.cancelled.contains(&request_id)
                })
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            state.cancelled.contains(&request_id)
        }

        fn release(&self, request_id: u64) {
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            state.released.insert(request_id);
            self.changed.notify_all();
        }

        fn request_shutdown(&self) {
            self.shutdown_requested.store(true, Ordering::Release);
            self.changed.notify_all();
        }

        fn install_shutdown_cx(&self, cx: Cx) {
            *self
                .shutdown_cx
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(cx);
        }

        fn apply_shutdown(&self) {
            if let Some(cx) = self
                .shutdown_cx
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .as_ref()
                .cloned()
            {
                cx.cancel_with(
                    CancelKind::Shutdown,
                    Some("controlled modern tool requested server shutdown"),
                );
            }
        }

        fn release_all(&self) {
            let mut state = self
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            state.release_all = true;
            self.changed.notify_all();
        }

        fn max_active(&self) -> usize {
            self.state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .max_active
        }

        fn was_cancelled(&self, request_id: u64) -> bool {
            self.state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .cancelled
                .contains(&request_id)
        }
    }

    struct LiveModernControlledTool {
        control: Arc<LiveModernControl>,
    }

    impl ToolHandler for LiveModernControlledTool {
        fn definition(&self) -> Tool {
            Tool {
                name: "live_modern_controlled_tool".to_owned(),
                description: Some("Deterministic live modern dispatcher probe".to_owned()),
                input_schema: serde_json::json!({"type": "object"}),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(&self, ctx: &McpContext, _arguments: serde_json::Value) -> McpResult<Vec<Content>> {
            report_final_progress_probe_updates(ctx);
            self.control.call(ctx)
        }

        // The request-owned modern dispatch polls this handler on the
        // runtime's async worker, so a controlled tool that parks must be
        // COOPERATIVE: a synchronous condvar wait inside poll would
        // monopolize the single current_thread worker and starve every other
        // request-owned task (the exact strand the overlap tests then
        // misreport as lost dispatches).
        fn call_final_outcome_async_in_request<'a>(
            &'a self,
            ctx: &'a McpContext,
            request_cx: &'a Cx,
            _arguments: serde_json::Value,
        ) -> BoxFuture<'a, fastmcp_core::McpOutcome<FinalToolOutcome>> {
            // Cancellation may drop the pending future before another body poll.
            struct ActiveCallGuard<'ctx> {
                control: &'ctx LiveModernControl,
                ctx: &'ctx McpContext,
                request_cx: &'ctx Cx,
                request_id: u64,
                cancellation_observed: bool,
            }

            impl Drop for ActiveCallGuard<'_> {
                fn drop(&mut self) {
                    let mut state = self
                        .control
                        .state
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    state.active = state.active.saturating_sub(1);
                    if self.cancellation_observed
                        || self.ctx.request_cancellation().is_cancel_requested()
                        || self.request_cx.is_cancel_requested()
                        || self.control.shutdown_requested.load(Ordering::Acquire)
                    {
                        state.cancelled.insert(self.request_id);
                    }
                    self.control.changed.notify_all();
                }
            }

            Box::pin(async move {
                report_final_progress_probe_updates(ctx);
                let request_id = ctx.request_id();
                {
                    let mut state = self
                        .control
                        .state
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                    state.active += 1;
                    state.max_active = state.max_active.max(state.active);
                    state.started.insert(request_id);
                    self.control.changed.notify_all();
                }
                let mut active_call = ActiveCallGuard {
                    control: &self.control,
                    ctx,
                    request_cx,
                    request_id,
                    cancellation_observed: false,
                };
                loop {
                    if self.control.shutdown_requested.load(Ordering::Acquire) {
                        self.control.apply_shutdown();
                        return fastmcp_core::Outcome::Cancelled(asupersync::CancelReason::user(
                            "controlled modern tool released for server shutdown",
                        ));
                    }
                    if ctx.checkpoint().is_err() || request_cx.is_cancel_requested() {
                        active_call.cancellation_observed = true;
                        return fastmcp_core::Outcome::Cancelled(asupersync::CancelReason::user(
                            "request cancellation observed by controlled modern tool",
                        ));
                    }
                    {
                        let state = self
                            .control
                            .state
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner);
                        if state.release_all || state.released.contains(&request_id) {
                            drop(state);
                            return match crate::handler::promote_legacy_tool_content(vec![
                                Content::text(format!("modern request {request_id}")),
                            ]) {
                                Ok(result) => {
                                    fastmcp_core::Outcome::Ok(FinalToolOutcome::Complete(result))
                                }
                                Err(error) => fastmcp_core::Outcome::Err(error),
                            };
                        }
                    }
                    // A fair yield keeps this cooperative: spawned task
                    // timers do not fire while the harness main thread owns
                    // block_on (a timer park would freeze the tool forever),
                    // and a hand-rolled immediate self-wake can starve
                    // sibling tasks of the runtime.
                    asupersync::runtime::yield_now().await;
                }
            })
        }
    }

    #[derive(Default)]
    struct LiveModernNotificationControl {
        started: Mutex<bool>,
        cancelled: AtomicBool,
        changed: Condvar,
    }

    impl LiveModernNotificationControl {
        fn wait_for_started(&self, timeout: Duration) -> bool {
            let started = self
                .started
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let (started, _) = self
                .changed
                .wait_timeout_while(started, timeout, |started| !*started)
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            *started
        }

        fn was_cancelled(&self) -> bool {
            self.cancelled.load(Ordering::Acquire)
        }
    }

    struct LiveModernBlockingNotificationMiddleware {
        control: Arc<LiveModernNotificationControl>,
    }

    impl Middleware for LiveModernBlockingNotificationMiddleware {
        fn on_request(
            &self,
            ctx: &McpContext,
            request: &JsonRpcRequest,
        ) -> McpResult<MiddlewareDecision> {
            if request.method != "notifications/initialized" {
                return Ok(MiddlewareDecision::Continue);
            }
            {
                let mut started = self
                    .control
                    .started
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                *started = true;
                self.control.changed.notify_all();
            }
            let deadline = Instant::now() + Duration::from_secs(1);
            while !ctx.is_cancelled() && Instant::now() < deadline {
                std::thread::yield_now();
            }
            if ctx.is_cancelled() {
                self.control.cancelled.store(true, Ordering::Release);
                return Err(McpError::request_cancelled());
            }
            Err(McpError::internal_error(
                "modern notification did not receive shutdown cancellation",
            ))
        }
    }

    #[derive(Default)]
    struct LiveModernResponses {
        messages: Mutex<Vec<JsonRpcMessage>>,
        changed: Condvar,
    }

    impl LiveModernResponses {
        fn record(&self, message: JsonRpcMessage) {
            let mut messages = self
                .messages
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            messages.push(message);
            self.changed.notify_all();
        }

        fn response_count(&self, id: i64) -> usize {
            self.messages
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .iter()
                .filter(|message| {
                    matches!(message, JsonRpcMessage::Response(response) if response.id == Some(id.into()))
                })
                .count()
        }

        fn response(&self, id: i64) -> Option<JsonRpcResponse> {
            self.messages
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .iter()
                .find_map(|message| match message {
                    JsonRpcMessage::Response(response) if response.id == Some(id.into()) => {
                        Some(response.clone())
                    }
                    _ => None,
                })
        }

        fn messages(&self) -> Vec<JsonRpcMessage> {
            self.messages
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .clone()
        }

        fn wait_for_notification(&self, method: &str, timeout: Duration) -> bool {
            let messages = self
                .messages
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let (messages, _) = self
                .changed
                .wait_timeout_while(messages, timeout, |messages| {
                    !messages.iter().any(|message| {
                        matches!(message, JsonRpcMessage::Request(request) if request.method == method)
                    })
                })
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            messages.iter().any(|message| {
                matches!(message, JsonRpcMessage::Request(request) if request.method == method)
            })
        }

        fn wait_for_responses(&self, ids: &[i64], timeout: Duration) -> bool {
            let messages = self
                .messages
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let (messages, _) = self
                .changed
                .wait_timeout_while(messages, timeout, |messages| {
                    ids.iter().any(|id| {
                        !messages.iter().any(|message| {
                            matches!(message, JsonRpcMessage::Response(response) if response.id == Some((*id).into()))
                        })
                    })
                })
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            ids.iter().all(|id| {
                messages.iter().any(|message| {
                    matches!(message, JsonRpcMessage::Response(response) if response.id == Some((*id).into()))
                })
            })
        }
    }

    #[derive(Default)]
    struct BoundedTestSignal {
        raised: Mutex<bool>,
        changed: Condvar,
    }

    impl BoundedTestSignal {
        fn raise(&self) {
            let mut raised = self
                .raised
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            *raised = true;
            self.changed.notify_all();
        }

        fn wait(&self, timeout: Duration) -> bool {
            let raised = self
                .raised
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            let (raised, _) = self
                .changed
                .wait_timeout_while(raised, timeout, |raised| !*raised)
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            *raised
        }
    }

    struct LiveModernSplitRecv {
        phase: usize,
        control: Arc<LiveModernControl>,
        responses: Arc<LiveModernResponses>,
    }

    impl TransportRecvHalf for LiveModernSplitRecv {
        fn recv(&mut self, _cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
            let phase = self.phase;
            self.phase = self.phase.saturating_add(1);
            match phase {
                0 => Ok(modern_discovery_opening_request()),
                1 => Ok(modern_controlled_tool_request(1200)),
                2 => {
                    if self.control.wait_for_started(1, Duration::from_secs(2)) {
                        Ok(modern_controlled_tool_request(1201))
                    } else {
                        Err(TransportError::Timeout)
                    }
                }
                3 => {
                    if !self.control.wait_for_started(2, Duration::from_secs(2)) {
                        return Err(TransportError::Timeout);
                    }
                    self.control.release(1200);
                    self.control.release(1201);
                    if self
                        .responses
                        .wait_for_responses(&[1200, 1201], Duration::from_secs(2))
                    {
                        Err(TransportError::Closed)
                    } else {
                        Err(TransportError::Timeout)
                    }
                }
                _ => Err(TransportError::Closed),
            }
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            Ok(())
        }
    }

    struct LiveModernSplitSend {
        responses: Arc<LiveModernResponses>,
    }

    impl TransportSendHalf for LiveModernSplitSend {
        fn send(&mut self, _cx: &Cx, message: &JsonRpcMessage) -> Result<(), TransportError> {
            self.responses.record(message.clone());
            Ok(())
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            Ok(())
        }
    }

    // Exact-2024 era: scripts a legacy runtime connection.
    #[cfg(feature = "legacy-2024-11-05")]
    struct LiveLegacyRuntimeSplitRecv {
        phase: u8,
        supports_sampling: bool,
        outbound: Receiver<JsonRpcMessage>,
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl LiveLegacyRuntimeSplitRecv {
        fn wait_for_response(&self, id: i64) -> Result<(), TransportError> {
            loop {
                match self.outbound.recv_timeout(Duration::from_secs(2)) {
                    Ok(JsonRpcMessage::Response(response)) if response.id == Some(id.into()) => {
                        return Ok(());
                    }
                    Ok(_) => {}
                    Err(_) => return Err(TransportError::Timeout),
                }
            }
        }

        fn sampling_response(&self) -> Result<JsonRpcMessage, TransportError> {
            loop {
                match self.outbound.recv_timeout(Duration::from_secs(2)) {
                    Ok(JsonRpcMessage::Request(request))
                        if request.method == "sampling/createMessage" =>
                    {
                        let id = request.id.expect("sampling request must carry an id");
                        let result =
                            serde_json::to_value(fastmcp_protocol::CreateMessageResult::text(
                                "sampled-value",
                                "legacy-test-model",
                            ))
                            .expect("sampling result must serialize");
                        return Ok(JsonRpcMessage::Response(JsonRpcResponse::success(
                            id, result,
                        )));
                    }
                    Ok(_) => {}
                    Err(_) => return Err(TransportError::Timeout),
                }
            }
        }
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl TransportRecvHalf for LiveLegacyRuntimeSplitRecv {
        fn recv(&mut self, _cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
            let phase = self.phase;
            self.phase = self.phase.saturating_add(1);
            match phase {
                0 => Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                    "initialize",
                    Some(serde_json::json!({
                        "protocolVersion": LEGACY_PROTOCOL_VERSION,
                        "capabilities": if self.supports_sampling {
                            serde_json::json!({"sampling": {}})
                        } else {
                            serde_json::json!({})
                        },
                        "clientInfo": {"name": "legacy-runtime-client", "version": "1.0.0"},
                    })),
                    701_i64,
                ))),
                1 => Ok(JsonRpcMessage::Request(JsonRpcRequest::notification(
                    "notifications/initialized",
                    None,
                ))),
                2 => Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                    "logging/setLevel",
                    Some(serde_json::json!({"level": "debug"})),
                    702_i64,
                ))),
                3 => Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                    "tools/call",
                    Some(serde_json::json!({
                        "name": "live_legacy_runtime_connection_tool",
                        "arguments": {"sample": true},
                        "_meta": {"progressToken": "legacy-runtime-progress"},
                    })),
                    703_i64,
                ))),
                4 if self.supports_sampling => self.sampling_response(),
                4 => {
                    self.wait_for_response(703)?;
                    Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                        "tools/call",
                        Some(serde_json::json!({
                            "name": "live_legacy_runtime_connection_tool",
                            "arguments": {"sample": false},
                            "_meta": {"progressToken": "legacy-runtime-progress"},
                        })),
                        704_i64,
                    )))
                }
                5 if self.supports_sampling => {
                    self.wait_for_response(703)?;
                    Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                        "tools/call",
                        Some(serde_json::json!({
                            "name": "live_legacy_runtime_connection_tool",
                            "arguments": {"sample": false},
                            "_meta": {"progressToken": "legacy-runtime-progress"},
                        })),
                        704_i64,
                    )))
                }
                5 | 6 => {
                    self.wait_for_response(704)?;
                    Err(TransportError::Closed)
                }
                _ => Err(TransportError::Closed),
            }
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            Ok(())
        }
    }

    // Exact-2024 era: scripts a legacy runtime connection.
    #[cfg(feature = "legacy-2024-11-05")]
    struct LegacyRootsContextSplitRecv {
        phase: u8,
        supports_roots: bool,
        outbound: Receiver<JsonRpcMessage>,
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl LegacyRootsContextSplitRecv {
        fn wait_for_response(&self, id: i64) -> Result<(), TransportError> {
            loop {
                match self.outbound.recv_timeout(Duration::from_secs(2)) {
                    Ok(JsonRpcMessage::Response(response)) if response.id == Some(id.into()) => {
                        return Ok(());
                    }
                    Ok(_) => {}
                    Err(_) => return Err(TransportError::Timeout),
                }
            }
        }

        fn roots_response(&self) -> Result<JsonRpcMessage, TransportError> {
            loop {
                match self.outbound.recv_timeout(Duration::from_secs(2)) {
                    Ok(JsonRpcMessage::Request(request)) if request.method == "roots/list" => {
                        let id = request.id.expect("roots request must carry an id");
                        return Ok(JsonRpcMessage::Response(JsonRpcResponse::success(
                            id,
                            serde_json::json!({
                                "roots": [{"uri": "file:///workspace", "name": "workspace"}],
                            }),
                        )));
                    }
                    Ok(_) => {}
                    Err(_) => return Err(TransportError::Timeout),
                }
            }
        }
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl TransportRecvHalf for LegacyRootsContextSplitRecv {
        fn recv(&mut self, _cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
            let phase = self.phase;
            self.phase = self.phase.saturating_add(1);
            match phase {
                0 => Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                    "initialize",
                    Some(serde_json::json!({
                        "protocolVersion": LEGACY_PROTOCOL_VERSION,
                        "capabilities": if self.supports_roots {
                            serde_json::json!({"roots": {}})
                        } else {
                            serde_json::json!({})
                        },
                        "clientInfo": {"name": "legacy-roots-context", "version": "1.0.0"},
                    })),
                    731_i64,
                ))),
                1 => Ok(JsonRpcMessage::Request(JsonRpcRequest::notification(
                    "notifications/initialized",
                    None,
                ))),
                2 => Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                    "tools/call",
                    Some(serde_json::json!({
                        "name": "legacy_roots_context_tool",
                        "arguments": {},
                    })),
                    732_i64,
                ))),
                3 if self.supports_roots => self.roots_response(),
                3 => {
                    self.wait_for_response(732)?;
                    Err(TransportError::Closed)
                }
                4 if self.supports_roots => {
                    self.wait_for_response(732)?;
                    Err(TransportError::Closed)
                }
                _ => Err(TransportError::Closed),
            }
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            Ok(())
        }
    }

    // Exact-2024 era: scripts legacy server-to-client sampling.
    #[cfg(feature = "legacy-2024-11-05")]
    struct LegacyCancelLateRecv {
        phase: u8,
        outbound: Receiver<JsonRpcMessage>,
        reverse_id: Option<RequestId>,
        stale_offset: i64,
        cancellation_request_id: RequestId,
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl TransportRecvHalf for LegacyCancelLateRecv {
        fn recv(&mut self, _cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
            let phase = self.phase;
            self.phase = self.phase.saturating_add(1);
            match phase {
                0 => Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                    "initialize",
                    Some(serde_json::json!({
                        "protocolVersion": LEGACY_PROTOCOL_VERSION,
                        "capabilities": {"sampling": {}},
                        "clientInfo": {"name": "cancel-late", "version": "1.0.0"},
                    })),
                    801_i64,
                ))),
                1 => Ok(JsonRpcMessage::Request(JsonRpcRequest::notification(
                    "notifications/initialized",
                    None,
                ))),
                2 => Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                    "tools/call",
                    Some(
                        serde_json::json!({"name": "live_legacy_runtime_connection_tool", "arguments": {"sample": true}}),
                    ),
                    802_i64,
                ))),
                3 => loop {
                    match self.outbound.recv_timeout(Duration::from_secs(2)) {
                        Ok(JsonRpcMessage::Request(request))
                            if request.method == "sampling/createMessage" =>
                        {
                            let id = request.id.expect("sampling request id");
                            assert_eq!(id, RequestId::Number(-1));
                            self.reverse_id = Some(id.clone());
                            return Ok(JsonRpcMessage::Request(JsonRpcRequest::notification(
                                "notifications/cancelled",
                                Some(serde_json::json!({
                                    "requestId": self.cancellation_request_id.clone(),
                                    "reason": "test cancellation",
                                })),
                            )));
                        }
                        Ok(_) => {}
                        Err(_) => return Err(TransportError::Timeout),
                    }
                },
                4 => {
                    let id = self.reverse_id.clone().expect("captured reverse id");
                    let id = match id {
                        RequestId::Number(value) => RequestId::Number(value + self.stale_offset),
                        other => other,
                    };
                    Ok(JsonRpcMessage::Response(JsonRpcResponse::success(
                        id,
                        serde_json::json!({"text": "late"}),
                    )))
                }
                5 => Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                    "tools/call",
                    Some(
                        serde_json::json!({"name": "live_legacy_runtime_connection_tool", "arguments": {"sample": false}}),
                    ),
                    803_i64,
                ))),
                6 => loop {
                    match self.outbound.recv_timeout(Duration::from_secs(2)) {
                        Ok(JsonRpcMessage::Response(response))
                            if response.id == Some(803_i64.into()) =>
                        {
                            return Err(TransportError::Closed);
                        }
                        Ok(_) => {}
                        Err(_) => return Err(TransportError::Timeout),
                    }
                },
                _ => Err(TransportError::Closed),
            }
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            Ok(())
        }
    }

    // Exact-2024 era: records a legacy runtime connection's output.
    #[cfg(feature = "legacy-2024-11-05")]
    struct LiveLegacyRuntimeSplitSend {
        sent: Arc<Mutex<Vec<JsonRpcMessage>>>,
        outbound: std::sync::mpsc::SyncSender<JsonRpcMessage>,
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl TransportSendHalf for LiveLegacyRuntimeSplitSend {
        fn send(&mut self, _cx: &Cx, message: &JsonRpcMessage) -> Result<(), TransportError> {
            self.sent
                .lock()
                .expect("legacy runtime sent-message mutex must not be poisoned")
                .push(message.clone());
            self.outbound
                .send(message.clone())
                .map_err(|_| TransportError::Closed)
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            Ok(())
        }
    }

    // Exact-2024 era: scripts a legacy runtime connection.
    #[cfg(feature = "legacy-2024-11-05")]
    fn live_legacy_runtime_connection_transcript(supports_sampling: bool) -> Vec<JsonRpcMessage> {
        let sent = Arc::new(Mutex::new(Vec::new()));
        let (outbound, inbound) = sync_channel(32);
        run_live_split_transport(
            Duration::from_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS),
            Server::new("live-legacy-runtime-connection", "1.0.0")
                .protocol_policy(ProtocolPolicy::Auto)
                .expect("Auto must be available to this test build")
                .tool(LiveLegacyRuntimeConnectionTool)
                .build(),
            LiveLegacyRuntimeSplitRecv {
                phase: 0,
                supports_sampling,
                outbound: inbound,
            },
            LiveLegacyRuntimeSplitSend {
                sent: Arc::clone(&sent),
                outbound,
            },
        )
        .expect("public split transport must complete the legacy runtime script");
        sent.lock()
            .expect("legacy runtime sent-message mutex must not be poisoned")
            .clone()
    }

    // Exact-2024 era: scripts a legacy runtime connection.
    #[cfg(feature = "legacy-2024-11-05")]
    fn legacy_roots_context_transcript(supports_roots: bool) -> Vec<JsonRpcMessage> {
        let sent = Arc::new(Mutex::new(Vec::new()));
        let (outbound, inbound) = sync_channel(16);
        run_live_split_transport(
            Duration::from_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS),
            Server::new("legacy-roots-context", "1.0.0")
                .protocol_policy(ProtocolPolicy::Auto)
                .expect("Auto must be available to this test build")
                .tool(LegacyRootsContextTool)
                .build(),
            LegacyRootsContextSplitRecv {
                phase: 0,
                supports_roots,
                outbound: inbound,
            },
            LiveLegacyRuntimeSplitSend {
                sent: Arc::clone(&sent),
                outbound,
            },
        )
        .expect("public split transport must complete the legacy roots context script");
        sent.lock()
            .expect("legacy roots context sent-message mutex must not be poisoned")
            .clone()
    }

    // Exact-2024 era: scripts legacy progress over a legacy opening.
    #[cfg(feature = "legacy-2024-11-05")]
    fn legacy_stdio_progress_transcript(include_progress_token: bool) -> Vec<JsonRpcMessage> {
        let sent = Arc::new(Mutex::new(Vec::new()));
        let receive_calls = Arc::new(AtomicUsize::new(0));
        let mut params = serde_json::json!({
            "name": "live_legacy_runtime_connection_tool",
            "arguments": {"sample": false},
        });
        if include_progress_token {
            params
                .as_object_mut()
                .expect("legacy tool parameters must be an object")
                .insert(
                    "_meta".to_owned(),
                    serde_json::json!({"progressToken": "legacy-stdio-progress"}),
                );
        }
        run_returning_transport_with_test_runtime(
            Server::new("legacy-stdio-progress", "1.0.0")
                .protocol_policy(ProtocolPolicy::Auto)
                .expect("Auto must be available to this test build")
                .tool(LiveLegacyRuntimeConnectionTool)
                .build(),
            ProtocolPolicyScriptTransport {
                inbound: std::collections::VecDeque::from([
                    exact_legacy_initialize_request(711, serde_json::json!("1.0.0")),
                    JsonRpcMessage::Request(JsonRpcRequest::notification(
                        "notifications/initialized",
                        None,
                    )),
                    JsonRpcMessage::Request(JsonRpcRequest::new(
                        "tools/call",
                        Some(params),
                        712_i64,
                    )),
                ]),
                sent: Arc::clone(&sent),
                receive_calls,
            },
        )
        .expect("public stdio transport must complete the legacy progress script");
        sent.lock()
            .expect("legacy stdio sent-message mutex must not be poisoned")
            .clone()
    }

    #[cfg(feature = "websocket")]
    fn masked_websocket_frame(opcode: u8, payload: &[u8]) -> Vec<u8> {
        let mask = [0x41, 0x73, 0x19, 0xC7];
        let mut frame = Vec::with_capacity(payload.len() + 14);
        frame.push(0x80 | opcode);
        match payload.len() {
            length @ 0..=125 => frame.push(0x80 | length as u8),
            length @ 126..=65_535 => {
                frame.push(0x80 | 126);
                frame.extend_from_slice(&(length as u16).to_be_bytes());
            }
            length => {
                frame.push(0x80 | 127);
                frame.extend_from_slice(&(length as u64).to_be_bytes());
            }
        }
        frame.extend_from_slice(&mask);
        frame.extend(
            payload
                .iter()
                .enumerate()
                .map(|(index, byte)| byte ^ mask[index % mask.len()]),
        );
        frame
    }

    #[cfg(feature = "websocket")]
    fn masked_websocket_message(message: JsonRpcMessage) -> Vec<u8> {
        let payload = serde_json::to_vec(&message)
            .expect("live WebSocket request fixture must serialize to JSON-RPC");
        masked_websocket_frame(0x01, &payload)
    }

    /// The policy a server of this build selects by default: `Auto` with the
    /// exact legacy adapter, `ModernOnly` without it. A test of modern
    /// behaviour that does not depend on era classification selects it, so
    /// each feature lane exercises the loop its own shipped build runs.
    const fn build_default_protocol_policy() -> ProtocolPolicy {
        if cfg!(feature = "legacy-2024-11-05") {
            ProtocolPolicy::Auto
        } else {
            ProtocolPolicy::ModernOnly
        }
    }

    struct ProtocolPolicyScriptTransport {
        inbound: std::collections::VecDeque<JsonRpcMessage>,
        sent: Arc<Mutex<Vec<JsonRpcMessage>>>,
        receive_calls: Arc<AtomicUsize>,
    }

    fn modern_discovery_request(id: i64) -> JsonRpcMessage {
        JsonRpcMessage::Request(JsonRpcRequest::new(
            SERVER_DISCOVER_METHOD,
            Some(serde_json::json!({
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                },
            })),
            id,
        ))
    }

    fn modern_discovery_opening_request() -> JsonRpcMessage {
        modern_discovery_request(905)
    }

    fn modern_controlled_tool_request(id: i64) -> JsonRpcMessage {
        JsonRpcMessage::Request(JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({
                "name": "live_modern_controlled_tool",
                "arguments": {},
                // Modern REQUESTS must carry clientCapabilities alongside
                // protocolVersion or reserved-value validation rejects them
                // with -32602 before dispatch (notifications stay
                // protocolVersion-only by contract).
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                },
            })),
            id,
        ))
    }

    fn modern_controlled_tool_progress_request(id: i64) -> JsonRpcMessage {
        JsonRpcMessage::Request(JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({
                "name": "live_modern_controlled_tool",
                "arguments": {},
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                    "progressToken": "public-stdio-final-progress",
                    "io.modelcontextprotocol/logLevel": "info",
                },
            })),
            id,
        ))
    }

    // Exact-2024 era: builds a legacy tools/call request.
    #[cfg(feature = "legacy-2024-11-05")]
    fn legacy_controlled_tool_request(id: i64) -> JsonRpcMessage {
        JsonRpcMessage::Request(JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({
                "name": "live_modern_controlled_tool",
                "arguments": {},
            })),
            id,
        ))
    }

    fn modern_initialized_notification() -> JsonRpcMessage {
        JsonRpcMessage::Request(JsonRpcRequest::notification(
            "notifications/initialized",
            Some(serde_json::json!({
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                },
            })),
        ))
    }

    fn modern_cancelled_notification(request_id: u64) -> JsonRpcMessage {
        JsonRpcMessage::Request(JsonRpcRequest::notification(
            "notifications/cancelled",
            Some(serde_json::json!({
                "requestId": request_id,
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                },
            })),
        ))
    }

    fn modern_catalog_mutating_tool_request(id: i64) -> JsonRpcMessage {
        JsonRpcMessage::Request(JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({
                "name": "stdio_catalog_mutating_tool",
                "arguments": {},
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                },
            })),
            id,
        ))
    }

    fn modern_subscriptions_listen_request(id: i64) -> JsonRpcMessage {
        JsonRpcMessage::Request(JsonRpcRequest::new(
            SUBSCRIPTIONS_LISTEN,
            Some(serde_json::json!({
                "notifications": {
                    "toolsListChanged": true,
                },
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                },
            })),
            id,
        ))
    }

    struct PublicStdioSubscriptionRecv {
        inbound: std::collections::VecDeque<JsonRpcMessage>,
        sent: Arc<Mutex<Vec<JsonRpcMessage>>>,
        receive_calls: Arc<AtomicUsize>,
        termination_attempted: Arc<AtomicBool>,
    }

    impl TransportRecvHalf for PublicStdioSubscriptionRecv {
        fn recv(&mut self, _cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
            self.receive_calls.fetch_add(1, Ordering::AcqRel);
            if let Some(message) = self.inbound.pop_front() {
                return Ok(message);
            }
            let deadline = Instant::now() + Duration::from_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
            while Instant::now() < deadline {
                let acknowledged = self
                    .sent
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .iter()
                    .any(|message| {
                        matches!(
                            message,
                            JsonRpcMessage::Request(request)
                                if request.method
                                    == "notifications/subscriptions/acknowledged"
                        )
                    });
                if acknowledged {
                    while Instant::now() < deadline {
                        let completion_committed = self
                            .sent
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner)
                            .iter()
                            .any(|message| {
                                matches!(
                                    message,
                                    JsonRpcMessage::Response(response)
                                        if response.id == Some(906_i64.into())
                                            && final_subscription_completion_response(response)
                                )
                            });
                        if self.termination_attempted.load(Ordering::Acquire)
                            && completion_committed
                        {
                            return Err(TransportError::Closed);
                        }
                        thread::sleep(Duration::from_millis(1));
                    }
                    return Err(TransportError::Timeout);
                }
                thread::sleep(Duration::from_millis(1));
            }
            Err(TransportError::Timeout)
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            Ok(())
        }
    }

    fn public_stdio_final_subscription_transcript(
        cancellation: Option<JsonRpcMessage>,
    ) -> Vec<JsonRpcMessage> {
        const DISCOVERY_ID: i64 = 905;
        const SUBSCRIPTION_ID: i64 = 906;

        let sent = Arc::new(Mutex::new(Vec::new()));
        let receive_calls = Arc::new(AtomicUsize::new(0));
        let termination_attempted = Arc::new(AtomicBool::new(false));
        let server = Server::new("public-stdio-final-subscription", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .build();
        let subscriptions = Arc::clone(&server.final_subscriptions);
        let sent_for_terminator = Arc::clone(&sent);
        let termination_attempted_by_terminator = Arc::clone(&termination_attempted);
        let terminator = thread::spawn(move || {
            let deadline = Instant::now() + Duration::from_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
            while Instant::now() < deadline {
                let acknowledged = sent_for_terminator
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .iter()
                    .any(|message| {
                        matches!(
                            message,
                            JsonRpcMessage::Request(request)
                                if request.method == "notifications/subscriptions/acknowledged"
                        )
                    });
                if acknowledged {
                    let terminated = subscriptions.terminate() == 1;
                    termination_attempted_by_terminator.store(true, Ordering::Release);
                    return terminated;
                }
                thread::sleep(Duration::from_millis(1));
            }
            termination_attempted_by_terminator.store(true, Ordering::Release);
            false
        });

        let mut inbound =
            std::collections::VecDeque::from([modern_discovery_request(DISCOVERY_ID)]);
        if let Some(cancellation) = cancellation {
            inbound.push_back(cancellation);
        }
        inbound.push_back(modern_subscriptions_listen_request(SUBSCRIPTION_ID));
        run_live_split_transport(
            Duration::from_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS),
            server,
            PublicStdioSubscriptionRecv {
                inbound,
                sent: Arc::clone(&sent),
                receive_calls,
                termination_attempted,
            },
            PublicSplitSubscriptionSend {
                sent: Arc::clone(&sent),
            },
        )
        .expect("public modern stdio transport must settle the subscription stream");
        assert!(
            terminator
                .join()
                .expect("subscription terminator must not panic"),
            "the public listener must acknowledge before server termination"
        );
        sent.lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone()
    }

    fn public_stdio_listen_observes_handler_catalog_mutation() -> Vec<JsonRpcMessage> {
        const DISCOVERY_ID: i64 = 925;
        const SUBSCRIPTION_ID: i64 = 926;
        const TOOL_ID: i64 = 927;

        let sent = Arc::new(Mutex::new(Vec::new()));
        let receive_calls = Arc::new(AtomicUsize::new(0));
        let termination_attempted = Arc::new(AtomicBool::new(false));
        let server = Server::new("public-stdio-listen-catalog", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .tool(StdioCatalogMutatingTool)
            .build();
        let subscriptions = Arc::clone(&server.final_subscriptions);
        let sent_for_terminator = Arc::clone(&sent);
        let termination_attempted_by_terminator = Arc::clone(&termination_attempted);
        let terminator = thread::spawn(move || {
            let deadline = Instant::now() + Duration::from_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
            while Instant::now() < deadline {
                let saw_list_changed = sent_for_terminator
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .iter()
                    .any(|message| {
                        matches!(
                            message,
                            JsonRpcMessage::Request(request)
                                if request.method == "notifications/tools/list_changed"
                        )
                    });
                if saw_list_changed {
                    let terminated = subscriptions.terminate() == 1;
                    termination_attempted_by_terminator.store(true, Ordering::Release);
                    return terminated;
                }
                thread::sleep(Duration::from_millis(1));
            }
            termination_attempted_by_terminator.store(true, Ordering::Release);
            false
        });

        struct WaitForAckThenMutate {
            phase: u8,
            sent: Arc<Mutex<Vec<JsonRpcMessage>>>,
            termination_attempted: Arc<AtomicBool>,
        }
        impl TransportRecvHalf for WaitForAckThenMutate {
            fn recv(&mut self, _cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
                let phase = self.phase;
                self.phase = self.phase.saturating_add(1);
                match phase {
                    0 => Ok(modern_discovery_request(DISCOVERY_ID)),
                    1 => Ok(modern_subscriptions_listen_request(SUBSCRIPTION_ID)),
                    2 => {
                        let deadline =
                            Instant::now() + Duration::from_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
                        while Instant::now() < deadline {
                            let acknowledged = self
                                .sent
                                .lock()
                                .unwrap_or_else(std::sync::PoisonError::into_inner)
                                .iter()
                                .any(|message| {
                                    matches!(
                                        message,
                                        JsonRpcMessage::Request(request)
                                            if request.method
                                                == "notifications/subscriptions/acknowledged"
                                    )
                                });
                            if acknowledged {
                                return Ok(modern_catalog_mutating_tool_request(TOOL_ID));
                            }
                            thread::sleep(Duration::from_millis(1));
                        }
                        Err(TransportError::Timeout)
                    }
                    _ => {
                        let deadline =
                            Instant::now() + Duration::from_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
                        while Instant::now() < deadline {
                            let completion_committed = self
                                .sent
                                .lock()
                                .unwrap_or_else(std::sync::PoisonError::into_inner)
                                .iter()
                                .any(|message| {
                                    matches!(
                                        message,
                                        JsonRpcMessage::Response(response)
                                            if response.id == Some(SUBSCRIPTION_ID.into())
                                                && final_subscription_completion_response(response)
                                    )
                                });
                            if self.termination_attempted.load(Ordering::Acquire)
                                && completion_committed
                            {
                                return Err(TransportError::Closed);
                            }
                            thread::sleep(Duration::from_millis(1));
                        }
                        Err(TransportError::Timeout)
                    }
                }
            }

            fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
                Ok(())
            }
        }

        let _ = receive_calls;
        run_live_split_transport(
            Duration::from_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS),
            server,
            WaitForAckThenMutate {
                phase: 0,
                sent: Arc::clone(&sent),
                termination_attempted,
            },
            PublicSplitSubscriptionSend {
                sent: Arc::clone(&sent),
            },
        )
        .expect("public modern stdio transport must settle listen plus catalog mutation");
        assert!(
            terminator
                .join()
                .expect("catalog-mutation terminator must not panic"),
            "the public listener must observe handler-driven tools/list_changed"
        );
        sent.lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone()
    }

    #[test]
    fn dispatch_stateless_listen_is_not_method_not_found() {
        let server = Server::new("stateless-listen-error", "1.0.0").build();
        let inbound =
            InboundRequestContext::new(Cx::for_testing(), 926, InboundRequestTransport::Memory);
        let JsonRpcMessage::Request(request) = modern_subscriptions_listen_request(926) else {
            panic!("listen fixture must be a request");
        };
        let response = block_on(server.dispatch_stateless(&inbound, &request))
            .expect("listen with an id must produce a JSON-RPC response");
        let error = response
            .error
            .expect("sync dispatch_stateless cannot own a listen stream");
        assert_ne!(
            error.code,
            i32::from(McpErrorCode::MethodNotFound).into(),
            "listen must not look unimplemented: {error:?}"
        );
        assert!(
            error.message.contains("open_subscription_listen"),
            "error must name the in-process listen API: {error:?}"
        );
    }

    #[test]
    fn open_subscription_listen_receives_stateless_catalog_mutation() {
        let server = Server::new("in-process-listen", "1.0.0")
            .tool(StdioCatalogMutatingTool)
            .build();
        let sent = Arc::new(Mutex::new(Vec::<JsonRpcRequest>::new()));
        let sent_for_sender = Arc::clone(&sent);
        let sender: NotificationSender = Arc::new(move |notification| {
            sent_for_sender
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(notification);
        });
        let _listen = server
            .open_subscription_listen(
                RequestId::String("in-process-listen".to_owned()),
                SubscriptionFilter {
                    tools_list_changed: Some(true),
                    ..SubscriptionFilter::default()
                },
                sender,
            )
            .expect("in-process listen must open");
        assert!(
            sent.lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .iter()
                .any(|request| request.method == "notifications/subscriptions/acknowledged"),
            "open_subscription_listen must acknowledge immediately"
        );

        let connection = ModernConnection::new();
        let inbound = InboundRequestContext::with_modern_connection(
            Cx::for_testing(),
            927,
            InboundRequestTransport::Memory,
            &connection,
        );
        let JsonRpcMessage::Request(request) = modern_catalog_mutating_tool_request(927) else {
            panic!("catalog mutation fixture must be a request");
        };
        let response = block_on(server.dispatch_stateless(&inbound, &request))
            .expect("stateless tools/call must respond");
        assert!(
            response.error.is_none(),
            "catalog mutation tool must succeed: {response:?}"
        );
        assert!(
            sent.lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .iter()
                .any(|request| request.method == "notifications/tools/list_changed"),
            "in-process listen must observe handler-driven list_changed"
        );
    }

    #[test]
    fn dropped_in_process_listen_does_not_receive_later_catalog_events() {
        let server = Server::new("dropped-in-process-listen", "1.0.0")
            .tool(StdioCatalogMutatingTool)
            .build();
        let sent = Arc::new(Mutex::new(Vec::<JsonRpcRequest>::new()));
        let sent_for_sender = Arc::clone(&sent);
        let sender: NotificationSender = Arc::new(move |notification| {
            sent_for_sender
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(notification);
        });
        let listen = server
            .open_subscription_listen(
                RequestId::String("dropped-listen".to_owned()),
                SubscriptionFilter {
                    tools_list_changed: Some(true),
                    ..SubscriptionFilter::default()
                },
                sender,
            )
            .expect("in-process listen must open");
        drop(listen);
        sent.lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clear();

        let connection = ModernConnection::new();
        let inbound = InboundRequestContext::with_modern_connection(
            Cx::for_testing(),
            928,
            InboundRequestTransport::Memory,
            &connection,
        );
        let JsonRpcMessage::Request(request) = modern_catalog_mutating_tool_request(928) else {
            panic!("catalog mutation fixture must be a request");
        };
        let _ = block_on(server.dispatch_stateless(&inbound, &request))
            .expect("stateless tools/call must respond");
        assert!(
            sent.lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .iter()
                .all(|request| request.method != "notifications/tools/list_changed"),
            "a dropped listen handle must not receive later catalog events"
        );
    }

    #[test]
    fn public_stdio_listen_receives_handler_driven_list_changed() {
        let transcript = public_stdio_listen_observes_handler_catalog_mutation();
        assert!(
            transcript.iter().any(|message| {
                matches!(
                    message,
                    JsonRpcMessage::Request(request)
                        if request.method == "notifications/subscriptions/acknowledged"
                )
            }),
            "listen must acknowledge before catalog events: {transcript:?}"
        );
        assert!(
            transcript.iter().any(|message| {
                matches!(
                    message,
                    JsonRpcMessage::Request(request)
                        if request.method == "notifications/tools/list_changed"
                )
            }),
            "detached stdio listen must receive handler-driven list_changed: {transcript:?}"
        );
    }

    #[derive(Clone, Copy)]
    enum PublicSplitSubscriptionTerminal {
        Eof,
        Shutdown,
    }

    struct PublicSplitSubscriptionRecv {
        phase: u8,
        sent: Arc<Mutex<Vec<JsonRpcMessage>>>,
        terminal: PublicSplitSubscriptionTerminal,
    }

    impl TransportRecvHalf for PublicSplitSubscriptionRecv {
        fn recv(&mut self, _cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
            let phase = self.phase;
            self.phase = self.phase.saturating_add(1);
            match phase {
                0 => Ok(modern_discovery_request(915)),
                1 => Ok(modern_subscriptions_listen_request(916)),
                2 => {
                    let deadline = Instant::now() + Duration::from_secs(2);
                    while Instant::now() < deadline {
                        let acknowledged = self
                            .sent
                            .lock()
                            .unwrap_or_else(std::sync::PoisonError::into_inner)
                            .iter()
                            .any(|message| {
                                matches!(
                                    message,
                                    JsonRpcMessage::Request(request)
                                        if request.method
                                            == "notifications/subscriptions/acknowledged"
                                )
                            });
                        if acknowledged {
                            return Err(match self.terminal {
                                PublicSplitSubscriptionTerminal::Eof => TransportError::Closed,
                                PublicSplitSubscriptionTerminal::Shutdown => {
                                    TransportError::Cancelled
                                }
                            });
                        }
                        thread::sleep(Duration::from_millis(1));
                    }
                    Err(TransportError::Timeout)
                }
                _ => Err(TransportError::Closed),
            }
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            Ok(())
        }
    }

    struct PublicSplitSubscriptionSend {
        sent: Arc<Mutex<Vec<JsonRpcMessage>>>,
    }

    impl TransportSendHalf for PublicSplitSubscriptionSend {
        fn send(&mut self, _cx: &Cx, message: &JsonRpcMessage) -> Result<(), TransportError> {
            self.sent
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(message.clone());
            Ok(())
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            Ok(())
        }
    }

    fn public_split_stdio_final_subscription_transcript(
        terminal: PublicSplitSubscriptionTerminal,
    ) -> Result<Vec<JsonRpcMessage>, String> {
        let sent = Arc::new(Mutex::new(Vec::new()));
        run_live_split_transport(
            Duration::from_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS),
            Server::new("public-split-stdio-final-subscription", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .build(),
            PublicSplitSubscriptionRecv {
                phase: 0,
                sent: Arc::clone(&sent),
                terminal,
            },
            PublicSplitSubscriptionSend {
                sent: Arc::clone(&sent),
            },
        )?;
        Ok(sent
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone())
    }

    fn assert_public_split_stdio_subscription_shutdown(terminal: PublicSplitSubscriptionTerminal) {
        let sent = public_split_stdio_final_subscription_transcript(terminal)
            .expect("public split stdio shutdown must preserve the listener completion");

        assert_eq!(
            sent.len(),
            4,
            "the public split transport must emit only discovery, acknowledgement, cancellation, and completion: {sent:?}"
        );
        assert!(sent.iter().any(|message| {
            matches!(
                message,
                JsonRpcMessage::Response(response) if response.id == Some(915_i64.into())
            )
        }));

        let acknowledgement = sent
            .iter()
            .position(|message| {
                matches!(
                    message,
                    JsonRpcMessage::Request(request)
                        if matches!(
                            ServerNotification::decode(request),
                            Ok(ServerNotification::SubscriptionsAcknowledged(_))
                        )
                )
            })
            .expect("public split transport must acknowledge subscriptions/listen");
        let cancellation = sent
            .iter()
            .position(|message| {
                matches!(
                    message,
                    JsonRpcMessage::Request(request)
                        if matches!(
                            ServerNotification::decode(request),
                            Ok(ServerNotification::Cancelled(params))
                                if params.request_id == RequestId::Number(916)
                        )
                )
            })
            .expect("public split transport must cancel the final subscription");
        let completion = sent
            .iter()
            .position(|message| {
                matches!(
                    message,
                    JsonRpcMessage::Response(response)
                        if response.id == Some(916_i64.into())
                            && final_subscription_completion_response(response)
                )
            })
            .expect("public split transport must preserve graceful subscription completion");
        assert!(
            acknowledgement < cancellation && cancellation < completion,
            "subscription acknowledgement, cancellation, and completion must retain their graceful order: {sent:?}"
        );
    }

    #[test]
    fn public_split_stdio_eof_elects_subscription_completion_before_cancellation_drain() {
        assert_public_split_stdio_subscription_shutdown(PublicSplitSubscriptionTerminal::Eof);
    }

    #[test]
    fn public_split_stdio_shutdown_elects_subscription_completion_before_cancellation_drain() {
        assert_public_split_stdio_subscription_shutdown(PublicSplitSubscriptionTerminal::Shutdown);
    }

    /// Runs a two-message stdio script against a server built with the
    /// no-legacy default policy.
    #[cfg(not(feature = "legacy-2024-11-05"))]
    fn no_legacy_stdio_script(
        opening: JsonRpcMessage,
        follow_up: JsonRpcMessage,
    ) -> (McpResult<()>, usize, Vec<JsonRpcMessage>) {
        let sent = Arc::new(Mutex::new(Vec::new()));
        let receive_calls = Arc::new(AtomicUsize::new(0));
        let server = Server::new("no-legacy-stdio-route", "1.0.0").build();
        assert_eq!(server.protocol_policy(), ProtocolPolicy::ModernOnly);
        let result = server.run_transport_returning_with_cx(
            &Cx::for_testing(),
            ProtocolPolicyScriptTransport {
                inbound: std::collections::VecDeque::from([opening, follow_up]),
                sent: Arc::clone(&sent),
                receive_calls: Arc::clone(&receive_calls),
            },
        );
        let sent = sent
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone();
        (result, receive_calls.load(Ordering::Acquire), sent)
    }

    #[cfg(not(feature = "legacy-2024-11-05"))]
    #[test]
    fn no_legacy_stdio_refuses_the_opening_envelope_before_a_second_request_or_dispatch() {
        // A no-legacy build cannot select Auto, so the legacy opening below
        // meets the ModernOnly default rather than a dual-era classifier.
        assert!(matches!(
            Server::new("no-legacy-stdio-route", "1.0.0").protocol_policy(ProtocolPolicy::Auto),
            Err(ServerLaunchPolicyError::FeatureUnavailable)
        ));
        let (result, receive_calls, sent) = no_legacy_stdio_script(
            exact_legacy_initialize_request(917, serde_json::json!("1.0.0")),
            JsonRpcMessage::Request(JsonRpcRequest::new(
                "tools/list",
                Some(serde_json::json!({})),
                918_i64,
            )),
        );

        assert!(
            result.is_err(),
            "a no-legacy stdio opening must be terminal"
        );
        assert_eq!(
            receive_calls, 1,
            "the legacy opening must not admit a follow-up request into dispatch"
        );
        assert!(
            sent.iter().all(|message| !matches!(
                message,
                JsonRpcMessage::Response(response)
                    if response.id == Some(917_i64.into()) && response.error.is_none()
            )),
            "the exact legacy initialize response proves adapter admission and must never be emitted"
        );
    }

    #[cfg(not(feature = "legacy-2024-11-05"))]
    #[test]
    fn no_legacy_stdio_admits_a_modern_opening_and_its_follow_up_request() {
        // Differs from the refusal above only in the era of the opening.
        let (result, receive_calls, sent) =
            no_legacy_stdio_script(modern_discovery_request(917), modern_discovery_request(918));

        result.expect("a modern opening must keep the no-legacy stdio connection open");
        assert_eq!(
            receive_calls, 3,
            "both requests and the closing receive must reach the loop"
        );
        for id in [917_i64, 918] {
            assert!(
                sent.iter().any(|message| matches!(
                    message,
                    JsonRpcMessage::Response(response)
                        if response.id == Some(id.into()) && response.error.is_none()
                )),
                "request {id} must be dispatched and answered: {sent:?}"
            );
        }
    }

    #[cfg(not(feature = "legacy-2024-11-05"))]
    #[test]
    fn no_legacy_source_gates_standalone_sse_and_keeps_modern_sse_framing() {
        let source = include_str!("lib.rs").replace("\r\n", "\n");

        assert!(source.contains(
            "#[cfg(feature = \"legacy-2024-11-05\")]\nuse fastmcp_transport::sse::SseServerTransport;"
        ));
        assert!(!source.contains("#[cfg(feature = \"legacy-2024-11-05\")]\n    pub fn run_sse"));
        assert!(
            source.contains(
                "#[cfg(feature = \"legacy-2024-11-05\")]\n    pub async fn run_sse_with_cx"
            )
        );
        assert!(source.contains("fn sse_response_head(response: &HttpResponse)"));
        // Split so this assertion's own text cannot satisfy the scan.
        assert!(!source.contains(concat!("legacy_", "sse_response_head")));
    }

    #[test]
    fn no_context_transport_and_sse_runtime_wrappers_are_absent() {
        let source = include_str!("lib.rs");
        let has_public_signature = |signature: &str| {
            source
                .lines()
                .any(|line| line.trim_start().starts_with(signature))
        };

        assert!(!has_public_signature("pub fn run_transport<T>"));
        assert!(!has_public_signature("pub fn run_transport_returning<T>"));
        assert!(!has_public_signature("pub fn run_sse<W, R>"));
        assert!(has_public_signature("pub fn run_transport_with_cx<T>"));
        assert!(has_public_signature(
            "pub fn run_transport_returning_with_cx<T>"
        ));
        assert!(has_public_signature("pub async fn run_sse_with_cx<W, R>"));
    }

    #[cfg(not(feature = "legacy-2024-11-05"))]
    #[test]
    fn no_legacy_source_exposes_only_the_public_modern_http_contract() {
        let source = include_str!("lib.rs").replace("\r\n", "\n");

        assert!(source.contains("pub enum ServerHttpEndpointError"));
        assert!(source.contains(
            "pub fn into_http_endpoint(self) -> Result<ServerHttpEndpoint, ServerHttpEndpointError>"
        ));
        assert!(source.contains(
            "pub fn open_session(&self, cx: &Cx) -> Result<ServerHttpSession, ServerHttpEndpointError>"
        ));
        assert!(
            source.contains(") -> Result<ServerHttpEndpointResponse, ServerHttpEndpointError>")
        );
        assert!(source.contains(
            "pub fn pop_event(&self) -> Result<Option<SseEvent>, ServerHttpEndpointError>"
        ));
        assert!(source.contains("pub request_capacity: usize,"));
        assert!(
            source.contains(
                "#[cfg(feature = \"legacy-2024-11-05\")]\n    pub legacy_sse_path: String,"
            )
        );
        assert!(source.contains(
            "#[cfg(feature = \"legacy-2024-11-05\")]\n    pub legacy_message_path: String,"
        ));
        // Split so this assertion's own text cannot satisfy the scan.
        assert!(!source.contains(concat!("pub legacy_", "request_capacity")));
    }

    #[cfg(not(feature = "legacy-2024-11-05"))]
    fn no_legacy_http_session(name: &str) -> (Cx, ServerHttpEndpoint, ServerHttpSession) {
        let cx = Cx::for_testing();
        let endpoint = Server::new(name, "1.0.0")
            .build()
            .into_http_endpoint()
            .expect("modern-only HTTP endpoint must construct without legacy transport support");
        let session = endpoint
            .open_session(&cx)
            .expect("modern-only HTTP session must open");
        (cx, endpoint, session)
    }

    #[cfg(not(feature = "legacy-2024-11-05"))]
    #[test]
    fn no_legacy_http_routes_are_not_found_without_pinning_or_adapter_admission() {
        // A no-legacy build cannot select Auto, so the legacy routes below
        // meet the ModernOnly default rather than a dual-era classifier.
        assert!(matches!(
            Server::new("no-legacy-http-routes", "1.0.0").protocol_policy(ProtocolPolicy::Auto),
            Err(ServerLaunchPolicyError::FeatureUnavailable)
        ));
        // This build has no legacy adapter field to populate, so the former
        // `legacy_adapter.is_none()` check now holds at compile time.
        let (cx, endpoint, mut session) = no_legacy_http_session("no-legacy-http-routes");

        for request in [
            HttpRequest::new(HttpMethod::Get, "/sse"),
            HttpRequest::new(HttpMethod::Post, "/messages"),
        ] {
            let response = block_on(session.handle_async(&cx, request))
                .expect("a disabled legacy route is an ordinary zero-route response");
            assert!(matches!(
                response,
                ServerHttpEndpointResponse::Immediate(HttpResponse {
                    status: HttpStatus::NOT_FOUND,
                    ..
                })
            ));
            assert_eq!(session.selected_era, None);
        }
        assert!(
            endpoint
                .server
                .active_requests
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .is_empty(),
            "zero-route HTTP rejection must not create request authority"
        );
    }

    #[cfg(not(feature = "legacy-2024-11-05"))]
    #[test]
    fn no_legacy_http_modern_route_is_admitted_and_pins_the_modern_era() {
        // Differs from the refusal above only in the route and era of the request.
        let (cx, _endpoint, mut session) = no_legacy_http_session("no-legacy-http-routes");
        let request = JsonRpcRequest::new(
            SERVER_DISCOVER_METHOD,
            Some(serde_json::json!({
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                },
            })),
            919_i64,
        );

        let response = block_on(
            session.handle_async(
                &cx,
                HttpRequest::new(HttpMethod::Post, "/mcp")
                    .with_header("content-type", "application/json")
                    .with_header("accept", "application/json")
                    .with_header("mcp-protocol-version", MODERN_PROTOCOL_VERSION)
                    .with_header("mcp-method", SERVER_DISCOVER_METHOD)
                    .with_body(
                        serde_json::to_vec(&request)
                            .expect("modern discovery request must serialize"),
                    ),
            ),
        )
        .expect("a modern request must be admitted by the no-legacy endpoint");
        let ServerHttpEndpointResponse::Immediate(response) = response else {
            panic!("modern JSON negotiation must produce an immediate HTTP response");
        };
        assert_eq!(response.status, HttpStatus::OK);
        let response: JsonRpcResponse =
            serde_json::from_slice(&response.body).expect("modern response must be JSON-RPC");
        assert_eq!(response.id, Some(919_i64.into()));
        assert!(response.error.is_none());
        assert_eq!(session.selected_era, Some(ProtocolEra::Modern2026));
    }

    #[test]
    fn public_stdio_final_subscription_listener_acknowledges_then_cancels_and_completes() {
        let sent = public_stdio_final_subscription_transcript(None);
        assert_public_stdio_final_subscription_transcript(&sent);
    }

    #[test]
    fn public_stdio_final_subscription_wrong_cancellation_id_preserves_listener_correlation() {
        let sent =
            public_stdio_final_subscription_transcript(Some(modern_cancelled_notification(907)));

        assert_public_stdio_final_subscription_transcript(&sent);
    }

    fn assert_public_stdio_final_subscription_transcript(sent: &[JsonRpcMessage]) {
        assert_eq!(
            sent.len(),
            4,
            "discovery plus one acknowledgement, cancellation, and completion are exact: {sent:?}"
        );
        assert!(sent.iter().any(|message| {
            matches!(
                message,
                JsonRpcMessage::Response(response) if response.id == Some(905_i64.into())
            )
        }));
        let acknowledgement = sent
            .iter()
            .position(|message| {
                matches!(
                    message,
                    JsonRpcMessage::Request(request)
                        if matches!(
                            ServerNotification::decode(request),
                            Ok(ServerNotification::SubscriptionsAcknowledged(_))
                        )
                )
            })
            .expect("the listener must emit one acknowledgement");
        let cancellation = sent
            .iter()
            .position(|message| {
                matches!(
                    message,
                    JsonRpcMessage::Request(request)
                        if matches!(
                            ServerNotification::decode(request),
                            Ok(ServerNotification::Cancelled(params))
                                if params.request_id == RequestId::Number(906)
                        )
                )
            })
            .expect("server termination must cancel the exact listener");
        let completion = sent
            .iter()
            .position(|message| {
                matches!(
                    message,
                    JsonRpcMessage::Response(response)
                        if response.id == Some(906_i64.into())
                            && final_subscription_completion_response(response)
                )
            })
            .expect("server termination must complete the exact listener");
        assert!(
            acknowledgement < cancellation && cancellation < completion,
            "the listener must acknowledge, cancel, and complete in causal order: {sent:?}"
        );
    }

    fn exact_legacy_initialize_request(
        id: i64,
        client_version: serde_json::Value,
    ) -> JsonRpcMessage {
        JsonRpcMessage::Request(JsonRpcRequest::new(
            "initialize",
            Some(serde_json::json!({
                "protocolVersion": LEGACY_PROTOCOL_VERSION,
                "capabilities": {},
                "clientInfo": {
                    "name": "live-legacy-client",
                    "version": client_version,
                },
            })),
            id,
        ))
    }

    struct CancelledNotificationTransport;

    impl Transport for CancelledNotificationTransport {
        fn send(&mut self, _cx: &Cx, _message: &JsonRpcMessage) -> Result<(), TransportError> {
            Err(TransportError::Cancelled)
        }

        fn recv(&mut self, _cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
            Err(TransportError::Closed)
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            Ok(())
        }
    }

    #[test]
    fn reality_check_regression_transport_notification_sender_latches_send_failure() {
        let failure = Arc::new(AtomicBool::new(false));
        let sender = create_transport_notification_sender(
            SharedTransport::new(ReturningProbeTransport {
                receive: ReturningProbeReceive::Closed,
                fail_send: true,
                fail_close: false,
                close_calls: Arc::new(AtomicUsize::new(0)),
            }),
            Cx::for_testing(),
            Arc::clone(&failure),
        );

        sender(JsonRpcRequest::notification("notifications/progress", None));

        assert!(failure.load(Ordering::Acquire));
    }

    #[test]
    fn reality_check_regression_notification_sender_does_not_promote_cancellation() {
        let failure = Arc::new(AtomicBool::new(false));
        let sender = create_transport_notification_sender(
            SharedTransport::new(CancelledNotificationTransport),
            Cx::for_testing(),
            Arc::clone(&failure),
        );

        sender(JsonRpcRequest::notification("notifications/progress", None));

        assert!(!failure.load(Ordering::Acquire));
    }

    #[test]
    fn reality_check_regression_returning_loop_preserves_notification_failure() {
        let failure = Arc::new(AtomicBool::new(false));
        let failure_from_receive = Arc::clone(&failure);
        let error = Server::new("returning-notification-failure-test", "1.0.0")
            .build()
            .run_loop_returning(
                &Cx::for_testing(),
                move |_receive_cx| {
                    failure_from_receive.store(true, Ordering::Release);
                    Err(TransportError::Closed)
                },
                move |_send_cx, _message| Ok(()),
                Arc::new(|_| {}),
                Some(failure),
                "custom-test",
            )
            .expect_err("notification failure must dominate concurrent clean EOF");

        assert_eq!(error.code, McpErrorCode::InternalError);
        assert_eq!(
            error.data.as_ref().and_then(|data| data["stage"].as_str()),
            Some("notification")
        );
        assert_eq!(
            error.data.as_ref().and_then(|data| data["kind"].as_str()),
            Some("send_failure")
        );
    }

    #[test]
    fn reality_check_regression_notification_failure_wins_cancelled_response_send() {
        let failure = Arc::new(AtomicBool::new(false));
        let failure_from_send = Arc::clone(&failure);
        let emitted = Arc::new(AtomicBool::new(false));
        let emitted_from_receive = Arc::clone(&emitted);
        let error = Server::new("returning-notification-send-race-test", "1.0.0")
            .build()
            .run_loop_returning(
                &Cx::for_testing(),
                move |_receive_cx| {
                    if emitted_from_receive.swap(true, Ordering::AcqRel) {
                        Err(TransportError::Closed)
                    } else {
                        Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                            "ping", None, 707_i64,
                        )))
                    }
                },
                move |_send_cx, _message| {
                    failure_from_send.store(true, Ordering::Release);
                    Err(TransportError::Cancelled)
                },
                Arc::new(|_| {}),
                Some(failure),
                "custom-test",
            )
            .expect_err("latched notification I/O failure must win cancelled response send");

        assert_eq!(
            error.data.as_ref().and_then(|data| data["stage"].as_str()),
            Some("notification")
        );
        assert_eq!(
            error.data.as_ref().and_then(|data| data["kind"].as_str()),
            Some("send_failure")
        );
    }

    #[test]
    fn reality_check_regression_parse_error_send_preserves_notification_failure() {
        let failure = Arc::new(AtomicBool::new(false));
        let failure_from_send = Arc::clone(&failure);
        let error = Server::new("returning-notification-parse-error-race-test", "1.0.0")
            .build()
            .run_loop_returning(
                &Cx::for_testing(),
                move |_receive_cx| {
                    Err(TransportError::Codec(fastmcp_transport::CodecError::Json(
                        serde_json::from_str::<serde_json::Value>("{")
                            .expect_err("fixture must be invalid JSON"),
                    )))
                },
                move |_send_cx, message| {
                    let JsonRpcMessage::Response(response) = message else {
                        panic!("recoverable JSON syntax failure must emit a response");
                    };
                    assert!(response.id.is_none());
                    assert_eq!(
                        response
                            .error
                            .as_ref()
                            .and_then(|response_error| response_error.code.as_i32()),
                        Some(-32700)
                    );
                    failure_from_send.store(true, Ordering::Release);
                    Err(TransportError::Cancelled)
                },
                Arc::new(|_| {}),
                Some(failure),
                "custom-test",
            )
            .expect_err("latched notification failure must win cancelled parse-error reply");

        assert_eq!(
            error.data.as_ref().and_then(|data| data["stage"].as_str()),
            Some("notification")
        );
        assert_eq!(
            error.data.as_ref().and_then(|data| data["kind"].as_str()),
            Some("send_failure")
        );
    }

    impl Transport for ReturningProbeTransport {
        fn send(&mut self, _cx: &Cx, _message: &JsonRpcMessage) -> Result<(), TransportError> {
            if self.fail_send {
                Err(TransportError::Io(std::io::Error::new(
                    std::io::ErrorKind::BrokenPipe,
                    "test returning-transport send failure",
                )))
            } else {
                Ok(())
            }
        }

        fn recv(&mut self, _cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
            match self.receive {
                ReturningProbeReceive::Closed => Err(TransportError::Closed),
                ReturningProbeReceive::Cancelled => Err(TransportError::Cancelled),
                ReturningProbeReceive::Timeout => Err(TransportError::Timeout),
                #[cfg(feature = "legacy-2024-11-05")]
                ReturningProbeReceive::PingThenClosed => {
                    self.receive = ReturningProbeReceive::Closed;
                    Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                        "ping", None, 704_i64,
                    )))
                }
            }
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            self.close_calls.fetch_add(1, Ordering::AcqRel);
            if self.fail_close {
                Err(TransportError::Io(std::io::Error::new(
                    std::io::ErrorKind::BrokenPipe,
                    "test returning-transport close failure",
                )))
            } else {
                Ok(())
            }
        }
    }

    impl Transport for SharedTransportCountingTransport {
        fn send(&mut self, _cx: &Cx, _message: &JsonRpcMessage) -> Result<(), TransportError> {
            self.send_calls.fetch_add(1, Ordering::AcqRel);
            Ok(())
        }

        fn recv(&mut self, _cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
            self.recv_calls.fetch_add(1, Ordering::AcqRel);
            Err(TransportError::Closed)
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            self.close_calls.fetch_add(1, Ordering::AcqRel);
            if self.fail_close {
                Err(TransportError::Io(std::io::Error::other(
                    "counting transport close failure",
                )))
            } else {
                Ok(())
            }
        }
    }

    impl Transport for ProtocolPolicyProbeTransport {
        fn send(&mut self, _cx: &Cx, message: &JsonRpcMessage) -> Result<(), TransportError> {
            self.sent
                .lock()
                .expect("protocol-policy test sent-message mutex must not be poisoned")
                .push(message.clone());
            Ok(())
        }

        fn recv(&mut self, _cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
            self.receive_calls.fetch_add(1, Ordering::AcqRel);
            self.next.take().ok_or(TransportError::Closed)
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            Ok(())
        }
    }

    impl Transport for ProtocolPolicyScriptTransport {
        fn send(&mut self, _cx: &Cx, message: &JsonRpcMessage) -> Result<(), TransportError> {
            self.sent
                .lock()
                .expect("protocol-policy test sent-message mutex must not be poisoned")
                .push(message.clone());
            Ok(())
        }

        fn recv(&mut self, _cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
            self.receive_calls.fetch_add(1, Ordering::AcqRel);
            self.inbound.pop_front().ok_or(TransportError::Closed)
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            Ok(())
        }
    }

    #[test]
    fn invalid_launch_policy_rejects_server_builder_before_transport_setup() {
        let builder = ServerBuilder::from_launch_protocol_policy(
            "invalid-launch-policy",
            "1.0.0",
            Err(ServerLaunchPolicyError::InvalidValue),
        );

        assert!(matches!(
            builder,
            Err(ServerLaunchPolicyError::InvalidValue)
        ));
    }

    #[test]
    fn server_builder_policy_admits_selected_modern_runtime_era() {
        let sent = Arc::new(Mutex::new(Vec::new()));
        let receive_calls = Arc::new(AtomicUsize::new(0));
        let server = Server::new("selected-modern-runtime-policy", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .build();

        assert_eq!(server.protocol_policy(), ProtocolPolicy::ModernOnly);
        server
            .run_transport_returning_with_cx(
                &Cx::for_testing(),
                ProtocolPolicyProbeTransport {
                    next: Some(modern_discovery_opening_request()),
                    sent: Arc::clone(&sent),
                    receive_calls: Arc::clone(&receive_calls),
                },
            )
            .expect("the selected modern policy must admit a modern discovery opener");

        assert_eq!(receive_calls.load(Ordering::Acquire), 2);
        let sent = sent
            .lock()
            .expect("protocol-policy test sent-message mutex must not be poisoned");
        let [JsonRpcMessage::Response(response)] = sent.as_slice() else {
            panic!("admitted modern discovery must emit exactly one response");
        };
        assert_eq!(response.id, Some(905_i64.into()));
        assert!(response.error.is_none());
        assert!(response.result.is_some());
    }

    // Exact-2024 era: selects LegacyOnly, which a no-legacy build refuses.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn server_builder_policy_rejects_same_modern_runtime_era_when_legacy_only() {
        let sent = Arc::new(Mutex::new(Vec::new()));
        let receive_calls = Arc::new(AtomicUsize::new(0));
        let server = Server::new("selected-modern-runtime-policy", "1.0.0")
            .protocol_policy(ProtocolPolicy::LegacyOnly)
            .expect("LegacyOnly must be available to this test build")
            .build();

        assert_eq!(server.protocol_policy(), ProtocolPolicy::LegacyOnly);
        let error = server
            .run_transport_returning_with_cx(
                &Cx::for_testing(),
                ProtocolPolicyProbeTransport {
                    next: Some(modern_discovery_opening_request()),
                    sent: Arc::clone(&sent),
                    receive_calls: Arc::clone(&receive_calls),
                },
            )
            .expect_err("changing only the policy must reject the modern opener");

        assert_eq!(
            error.data.as_ref().and_then(|data| data["stage"].as_str()),
            Some("protocol")
        );
        assert_eq!(
            error.data.as_ref().and_then(|data| data["kind"].as_str()),
            Some("era_admission")
        );
        assert_eq!(receive_calls.load(Ordering::Acquire), 1);
        let sent = sent
            .lock()
            .expect("protocol-policy test sent-message mutex must not be poisoned");
        let [JsonRpcMessage::Response(response)] = sent.as_slice() else {
            panic!("rejected modern discovery must emit exactly one refusal");
        };
        assert_eq!(response.id, Some(905_i64.into()));
        assert!(response.result.is_none());
        assert_eq!(
            response
                .error
                .as_ref()
                .and_then(|response_error| response_error.code.as_i32()),
            Some(-32600)
        );
    }

    // Exact-2024 era: tests Auto classification, which a no-legacy build refuses.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn auto_runtime_keeps_a_modern_opening_on_the_modern_dispatch_path() {
        let sent = Arc::new(Mutex::new(Vec::new()));
        let receive_calls = Arc::new(AtomicUsize::new(0));

        Server::new("auto-modern-runtime-policy", "1.0.0")
            .protocol_policy(ProtocolPolicy::Auto)
            .expect("Auto must be available to this test build")
            .build()
            .run_transport_returning_with_cx(
                &Cx::for_testing(),
                ProtocolPolicyProbeTransport {
                    next: Some(modern_discovery_opening_request()),
                    sent: Arc::clone(&sent),
                    receive_calls: Arc::clone(&receive_calls),
                },
            )
            .expect("Auto must keep a supported modern opener on the modern path");

        assert_eq!(receive_calls.load(Ordering::Acquire), 2);
        let sent = sent
            .lock()
            .expect("protocol-policy test sent-message mutex must not be poisoned");
        let [JsonRpcMessage::Response(response)] = sent.as_slice() else {
            panic!("modern Auto selection must emit exactly one discovery response");
        };
        assert_eq!(response.id, Some(905_i64.into()));
        assert!(response.error.is_none());
        assert!(response.result.is_some());
    }

    // Exact-2024 era: negotiates a legacy initialize.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn returning_transport_negotiates_initialize_proposals_before_tools_list() {
        for proposal in ["2024-11-05", "2025-03-26", "2025-06-18", "2099-01-01"] {
            let sent = Arc::new(Mutex::new(Vec::new()));
            let mut initialize = exact_legacy_initialize_request(711, serde_json::json!("1.0.0"));
            let JsonRpcMessage::Request(request) = &mut initialize else {
                panic!("initialize fixture must be a request");
            };
            request.params.as_mut().expect("initialize params")["protocolVersion"] =
                serde_json::json!(proposal);
            run_returning_transport_with_test_runtime(
                Server::new("proposal-negotiation", "1.0.0")
                    .protocol_policy(ProtocolPolicy::Auto)
                    .expect("Auto policy")
                    .tool(LiveLegacyRuntimeConnectionTool)
                    .build(),
                ProtocolPolicyScriptTransport {
                    inbound: std::collections::VecDeque::from([
                        initialize,
                        JsonRpcMessage::Request(JsonRpcRequest::notification(
                            "notifications/initialized",
                            None,
                        )),
                        JsonRpcMessage::Request(JsonRpcRequest::new("tools/list", None, 712_i64)),
                    ]),
                    sent: Arc::clone(&sent),
                    receive_calls: Arc::new(AtomicUsize::new(0)),
                },
            )
            .expect("proposal must negotiate and retain a usable session");
            let sent = sent.lock().expect("sent messages");
            let responses: Vec<_> = sent
                .iter()
                .filter_map(|message| match message {
                    JsonRpcMessage::Response(response) => Some(response),
                    JsonRpcMessage::Request(_) => None,
                })
                .collect();
            assert_eq!(responses.len(), 2, "{proposal}");
            assert!(
                responses.iter().all(|response| response.error.is_none()),
                "{responses:?}"
            );
            assert_eq!(
                responses[0].result.as_ref().expect("initialize result")["protocolVersion"],
                "2024-11-05"
            );
            let tools = responses[1].result.as_ref().expect("tools result")["tools"]
                .as_array()
                .expect("tools array");
            assert!(
                tools
                    .iter()
                    .any(|tool| tool["name"] == "live_legacy_runtime_connection_tool")
            );
        }
    }

    // Exact-2024 era: tests Auto classification, which a no-legacy build refuses.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn stdio_initialize_proposals_select_legacy_negotiation() {
        for proposal in ["2024-11-05", "2025-03-26", "2025-06-18", "2099-01-01"] {
            let request: JsonRpcRequest = serde_json::from_value(serde_json::json!({
                "jsonrpc": "2.0", "id": 1, "method": "initialize",
                "params": {"protocolVersion": proposal, "capabilities": {},
                    "clientInfo": {"name": "negotiation-test", "version": "1"}}
            }))
            .expect("valid initialize envelope");
            let mut classifier = StdioEraClassifier::new(ProtocolPolicy::Auto);
            assert_eq!(
                classify_initial_stdio_envelope(&mut classifier, &JsonRpcMessage::Request(request)),
                Ok(ProtocolEra::Legacy2024),
                "{proposal} must reach initialize negotiation"
            );
        }
    }

    // Exact-2024 era: tests Auto classification, which a no-legacy build refuses.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn stdio_auto_classifies_the_first_envelope_before_legacy_fallback() {
        let mut accepted = StdioEraClassifier::new(ProtocolPolicy::Auto);
        assert_eq!(
            classify_initial_stdio_envelope(&mut accepted, &modern_discovery_opening_request()),
            Ok(ProtocolEra::Modern2026),
            "the exact modern opening selects modern exactly once"
        );

        let mut rejected = StdioEraClassifier::new(ProtocolPolicy::Auto);
        let response = JsonRpcMessage::Response(JsonRpcResponse::success(
            906_i64.into(),
            serde_json::json!({}),
        ));
        assert!(matches!(
            classify_initial_stdio_envelope(&mut rejected, &response),
            Err(StdioEraDecision::RejectedAndClosed {
                reason:
                    fastmcp_protocol::protocol_policy::StdioEraRejection::ResponseCannotClassify,
            })
        ));
        assert!(matches!(
            rejected.state(),
            fastmcp_protocol::protocol_policy::StdioEraState::TerminalWithoutEra
        ));
        assert!(matches!(
            rejected.classify_opening(StdioOpeningFrame::LegacyInitialize),
            StdioEraDecision::AlreadyTerminal
        ));

        let mut malformed = StdioEraClassifier::new(ProtocolPolicy::Auto);
        assert!(matches!(
            reject_initial_stdio_malformed(&mut malformed),
            StdioEraDecision::RejectedAndClosed {
                reason: fastmcp_protocol::protocol_policy::StdioEraRejection::MalformedOpeningFrame,
            }
        ));
        assert!(matches!(
            malformed.state(),
            fastmcp_protocol::protocol_policy::StdioEraState::TerminalWithoutEra
        ));
    }

    #[test]
    fn cancellation_codec_uses_negotiated_era_and_modern_metadata_is_optional() {
        let metadata_free = JsonRpcRequest::notification(
            "notifications/cancelled",
            Some(serde_json::json!({
                "requestId": 907,
            })),
        );
        assert!(matches!(
            CancellationWireMessage::decode(
                ProtocolEra::Legacy2024,
                CancellationSender::Client,
                &metadata_free,
            ),
            Ok(CancellationWireMessage::Legacy2024 { .. })
        ));
        assert!(matches!(
            CancellationWireMessage::decode(
                ProtocolEra::Modern2026,
                CancellationSender::Client,
                &metadata_free,
            ),
            Ok(CancellationWireMessage::Modern2026 { .. })
        ));

        let with_metadata = JsonRpcRequest::notification(
            "notifications/cancelled",
            Some(serde_json::json!({
                "requestId": 907,
                "_meta": {
                    "trace": "optional-final-metadata",
                },
            })),
        );
        assert!(matches!(
            CancellationWireMessage::decode(
                ProtocolEra::Modern2026,
                CancellationSender::Client,
                &with_metadata,
            ),
            Ok(CancellationWireMessage::Modern2026 { .. })
        ));
        assert!(
            CancellationWireMessage::decode(
                ProtocolEra::Legacy2024,
                CancellationSender::Client,
                &with_metadata,
            )
            .is_ok()
        );

        let with_final_reserved_metadata = JsonRpcRequest::notification(
            "notifications/cancelled",
            Some(serde_json::json!({
                "requestId": 907,
                "_meta": {
                    "io.modelcontextprotocol/subscriptionId": 907,
                },
            })),
        );
        assert!(
            CancellationWireMessage::decode(
                ProtocolEra::Legacy2024,
                CancellationSender::Client,
                &with_final_reserved_metadata,
            )
            .is_err()
        );
    }

    // Exact-2024 era: used only by legacy application content tests.
    #[cfg(feature = "legacy-2024-11-05")]
    struct ApplicationContentTool {
        content: Vec<Content>,
        calls: Arc<AtomicUsize>,
        fail: bool,
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl ToolHandler for ApplicationContentTool {
        fn definition(&self) -> Tool {
            let mut definition = LiveRuntimeListedTool.definition();
            definition.name = "application_content".to_owned();
            definition
        }

        fn call(&self, ctx: &McpContext, _arguments: serde_json::Value) -> McpResult<Vec<Content>> {
            ctx.checkpoint()?;
            self.calls.fetch_add(1, Ordering::SeqCst);
            if self.fail {
                Err(McpError::tool_error("application tool failed"))
            } else {
                Ok(self.content.clone())
            }
        }
    }

    // Exact-2024 era: used only by legacy application content tests.
    #[cfg(feature = "legacy-2024-11-05")]
    struct ApplicationContentResultMiddleware(serde_json::Value);

    #[cfg(feature = "legacy-2024-11-05")]
    impl Middleware for ApplicationContentResultMiddleware {
        fn on_response(
            &self,
            _ctx: &McpContext,
            request: &JsonRpcRequest,
            response: serde_json::Value,
        ) -> McpResult<serde_json::Value> {
            Ok(if request.method == "tools/call" {
                self.0.clone()
            } else {
                response
            })
        }
    }

    // Exact-2024 era: used only by legacy application content tests.
    #[cfg(feature = "legacy-2024-11-05")]
    fn application_content_transcript(builder: ServerBuilder) -> Vec<JsonRpcMessage> {
        let sent = Arc::new(Mutex::new(Vec::new()));
        let call = |id| {
            JsonRpcMessage::Request(JsonRpcRequest::new(
                "tools/call",
                Some(serde_json::json!({"name": "application_content", "arguments": {}})),
                id,
            ))
        };
        // Finite transport fixture; all parsing, lifecycle admission,
        // middleware, request-owned handler execution, and result validation
        // use the actual returning server entry point.
        run_returning_transport_with_test_runtime(
            builder
                .protocol_policy(ProtocolPolicy::LegacyOnly)
                .expect("legacy test profile")
                .build(),
            ProtocolPolicyScriptTransport {
                inbound: std::collections::VecDeque::from([
                    exact_legacy_initialize_request(41, serde_json::json!("1.0.0")),
                    call(40_i64),
                    JsonRpcMessage::Request(JsonRpcRequest::notification(
                        "notifications/initialized",
                        None,
                    )),
                    call(42_i64),
                    JsonRpcMessage::Request(JsonRpcRequest::new("ping", None, 43_i64)),
                ]),
                sent: Arc::clone(&sent),
                receive_calls: Arc::new(AtomicUsize::new(0)),
            },
        )
        .expect("finite legacy transport closes cleanly");
        let messages = sent.lock().expect("captured server responses").clone();
        let response = |id: i64| {
            messages
                .iter()
                .find_map(|message| match message {
                    JsonRpcMessage::Response(response) if response.id == Some(id.into()) => {
                        Some(response)
                    }
                    _ => None,
                })
                .expect("correlated response")
        };
        assert_eq!(
            response(40_i64)
                .error
                .as_ref()
                .map(|error| error.code.clone()),
            Some((-32600).into())
        );
        assert!(response(40_i64).result.is_none());
        assert!(response(43_i64).error.is_none(), "connection stays usable");
        messages
    }

    // Exact-2024 era: used only by legacy application content tests.
    #[cfg(feature = "legacy-2024-11-05")]
    fn application_content_response(messages: &[JsonRpcMessage]) -> &JsonRpcResponse {
        messages
            .iter()
            .find_map(|message| match message {
                JsonRpcMessage::Response(response) if response.id == Some(42_i64.into()) => {
                    Some(response)
                }
                _ => None,
            })
            .expect("tool call has its original response ID")
    }

    // Exact-2024 era: legacy application tool content option.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn legacy_application_content_roundtrips_and_strict_mode_rejects_extensions() {
        for payload in [
            serde_json::json!({"type": "audio", "data": "YXVkaW8=", "mimeType": "audio/wav"}),
            serde_json::json!({"type": "resource", "resource": {"uri": "file:///empty"}}),
            serde_json::json!({"type": "resource", "resource": {
                "uri": "file:///both", "text": "text", "blob": "Ynl0ZXM="
            }}),
            serde_json::json!({"type": "text", "text": "ordinary"}),
        ] {
            for enabled in [false, true] {
                let calls = Arc::new(AtomicUsize::new(0));
                let mut builder =
                    Server::new("application-content", "1").tool(ApplicationContentTool {
                        content: vec![serde_json::from_value(payload.clone()).unwrap()],
                        calls: Arc::clone(&calls),
                        fail: false,
                    });
                if enabled {
                    builder = builder.legacy_application_tool_content(true);
                }
                let messages = application_content_transcript(builder);
                assert_eq!(
                    calls.load(Ordering::SeqCst),
                    1,
                    "uninitialized call is denied; admitted call executes once"
                );
                let response = application_content_response(&messages);
                if enabled || payload["type"] == "text" {
                    assert!(response.error.is_none(), "{response:?}");
                    assert_eq!(
                        response.result,
                        Some(serde_json::json!({"content": [payload.clone()]}))
                    );
                } else {
                    assert_eq!(
                        response.error.as_ref().map(|error| error.code.clone()),
                        Some((-32603).into())
                    );
                    assert!(response.result.is_none());
                }
            }
        }
    }

    // Exact-2024 era: legacy application tool content option.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn legacy_application_content_rejects_malformed_results_and_forbidden_envelopes() {
        let mut rejected = vec![
            serde_json::json!({"content": [{"type": "text", "text": 3}]}),
            serde_json::json!({"content": [{"type": "audio", "data": "YQ=="}]}),
            serde_json::json!({"content": [{"type": "resource", "resource": {"text": "missing URI"}}]}),
            serde_json::json!({"content": [{"type": "resource", "resource": {"uri": "file:///both", "text": "ok", "blob": 42}}]}),
            serde_json::json!({"content": [{"type": "audio", "data": "YQ==", "mimeType": "audio/wav", "extension": {"kept": true}}]}),
            serde_json::json!({"content": [{"type": "resource", "resource": {"uri": "file:///both", "text": "text", "blob": "Yg==", "extension": 7}}]}),
            serde_json::json!({"content": null}),
            serde_json::json!({"content": [], "isError": null}),
            serde_json::json!({"content": [], "_meta": null}),
            serde_json::json!({"content": [], "resultType": "complete"}),
        ];
        for key in [
            "io.modelcontextprotocol/protocolVersion",
            "io.modelcontextprotocol/clientCapabilities",
            "io.modelcontextprotocol/clientInfo",
            "io.modelcontextprotocol/logLevel",
            "io.modelcontextprotocol/serverInfo",
            "io.modelcontextprotocol/subscriptionId",
        ] {
            rejected.push(serde_json::json!({"content": [], "_meta": {key: "forbidden"}}));
        }
        for result in rejected {
            let calls = Arc::new(AtomicUsize::new(0));
            let builder = Server::new("application-invalid-content", "1")
                .legacy_application_tool_content(true)
                .tool(ApplicationContentTool {
                    content: vec![Content::text("ordinary handler result")],
                    calls: Arc::clone(&calls),
                    fail: false,
                })
                .middleware(ApplicationContentResultMiddleware(result.clone()));
            let messages = application_content_transcript(builder);
            assert_eq!(calls.load(Ordering::SeqCst), 1);
            let response = application_content_response(&messages);
            assert!(
                response.result.is_none(),
                "invalid result escaped: {result}"
            );
            assert_eq!(
                response.error.as_ref().map(|error| error.code.clone()),
                Some((-32603).into())
            );
        }
    }

    // Exact-2024 era: legacy application tool content option.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn legacy_application_content_preserves_open_metadata_and_content_fields() {
        let result = serde_json::json!({
            "content": [
                {"type": "audio", "data": "YQ==", "mimeType": "audio/wav"},
                {"type": "resource", "resource": {"uri": "file:///both", "text": "text", "blob": "Yg=="}}
            ],
            "isError": false,
            "_meta": {"caller-note": {"kept": true}}
        });
        let calls = Arc::new(AtomicUsize::new(0));
        let messages = application_content_transcript(
            Server::new("application-open-content", "1")
                .legacy_application_tool_content(true)
                .tool(ApplicationContentTool {
                    content: Vec::new(),
                    calls: Arc::clone(&calls),
                    fail: false,
                })
                .middleware(ApplicationContentResultMiddleware(result.clone())),
        );
        assert_eq!(calls.load(Ordering::SeqCst), 1);
        let response = application_content_response(&messages);
        assert!(response.error.is_none(), "{response:?}");
        assert_eq!(response.result, Some(result));
    }

    // Exact-2024 era: legacy application tool content option.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn legacy_application_content_does_not_bypass_authentication() {
        let calls = Arc::new(AtomicUsize::new(0));
        let messages = application_content_transcript(
            Server::new("application-denied-content", "1")
                .legacy_application_tool_content(true)
                .auth_provider(AlwaysFailAuthProvider)
                .tool(ApplicationContentTool {
                    content: vec![Content::text("must not execute")],
                    calls: Arc::clone(&calls),
                    fail: false,
                }),
        );
        assert_eq!(calls.load(Ordering::SeqCst), 0);
        let response = application_content_response(&messages);
        assert!(response.result.is_none());
        // Authentication admission deliberately normalizes provider errors to
        // ResourceForbidden; the provider's own invalid-request code is private.
        assert_eq!(
            response.error.as_ref().map(|error| error.code.clone()),
            Some((-32002).into())
        );
        assert_eq!(
            response.error.as_ref().map(|error| error.message.as_str()),
            Some("Authentication failed")
        );
    }

    // Exact-2024 era: legacy application tool content option.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn legacy_application_content_preserves_tool_errors() {
        let calls = Arc::new(AtomicUsize::new(0));
        let messages = application_content_transcript(
            Server::new("application-tool-error", "1")
                .legacy_application_tool_content(true)
                .tool(ApplicationContentTool {
                    content: Vec::new(),
                    calls: Arc::clone(&calls),
                    fail: true,
                }),
        );
        assert_eq!(calls.load(Ordering::SeqCst), 1);
        let response = application_content_response(&messages);
        assert!(response.error.is_none());
        assert_eq!(
            response.result,
            Some(serde_json::json!({
                "content": [{"type": "text", "text": "application tool failed"}], "isError": true
            }))
        );
    }

    // Exact-2024 era: routes legacy frames through the 2024 adapter.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_runtime_routes_exact_legacy_frames_through_the_2024_adapter() {
        let sent = Arc::new(Mutex::new(Vec::new()));
        let receive_calls = Arc::new(AtomicUsize::new(0));

        run_returning_transport_with_test_runtime(
            Server::new("live-legacy-runtime", "1.0.0")
                .protocol_policy(ProtocolPolicy::Auto)
                .expect("Auto must be available to this test build")
                .tool(LiveRuntimeListedTool)
                .build(),
            ProtocolPolicyScriptTransport {
                inbound: std::collections::VecDeque::from([
                    exact_legacy_initialize_request(41, serde_json::json!("1.0.0")),
                    JsonRpcMessage::Request(JsonRpcRequest::notification(
                        "notifications/initialized",
                        None,
                    )),
                    JsonRpcMessage::Request(JsonRpcRequest::new(
                        "tools/call",
                        Some(serde_json::json!({
                            "name": "live_runtime_listed_tool",
                            "arguments": {},
                        })),
                        42_i64,
                    )),
                ]),
                sent: Arc::clone(&sent),
                receive_calls: Arc::clone(&receive_calls),
            },
        )
        .expect("an exact legacy lifecycle must complete through the live adapter");

        assert_eq!(receive_calls.load(Ordering::Acquire), 4);
        let sent = sent
            .lock()
            .expect("protocol-policy test sent-message mutex must not be poisoned");
        let [
            JsonRpcMessage::Response(initialize),
            JsonRpcMessage::Response(call),
        ] = sent.as_slice()
        else {
            panic!("legacy initialize and tools/call must be the only adapter responses");
        };
        assert_eq!(initialize.id, Some(41_i64.into()));
        assert_eq!(
            initialize
                .result
                .as_ref()
                .and_then(|result| result["protocolVersion"].as_str()),
            Some(LEGACY_PROTOCOL_VERSION)
        );
        assert_eq!(call.id, Some(42_i64.into()));
        assert_eq!(
            call.result
                .as_ref()
                .and_then(|result| result["content"].as_array())
                .and_then(|content| content.first())
                .and_then(|content| content["text"].as_str()),
            Some("live runtime legacy adapter request 42")
        );
        assert!(
            call.result
                .as_ref()
                .is_some_and(|result| result.get("resultType").is_none())
        );
    }

    // Exact-2024 era: legacy cancellation on a legacy connection.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_legacy_runtime_ignores_invalid_cancellation_without_closing_the_connection() {
        let sent = Arc::new(Mutex::new(Vec::new()));
        let receive_calls = Arc::new(AtomicUsize::new(0));

        run_returning_transport_with_test_runtime(
            Server::new("legacy-invalid-cancellation", "1.0.0")
                .protocol_policy(ProtocolPolicy::Auto)
                .expect("Auto must be available to this test build")
                .build(),
            ProtocolPolicyScriptTransport {
                inbound: std::collections::VecDeque::from([
                    exact_legacy_initialize_request(71, serde_json::json!("1.0.0")),
                    JsonRpcMessage::Request(JsonRpcRequest::notification(
                        "notifications/initialized",
                        None,
                    )),
                    JsonRpcMessage::Request(JsonRpcRequest::notification(
                        "notifications/cancelled",
                        Some(serde_json::json!({
                            "requestId": 72,
                            "unexpected": true,
                        })),
                    )),
                    JsonRpcMessage::Request(JsonRpcRequest::new("ping", None, 72_i64)),
                ]),
                sent: Arc::clone(&sent),
                receive_calls: Arc::clone(&receive_calls),
            },
        )
        .expect("an invalid cancellation must leave the legacy connection usable");

        assert_eq!(receive_calls.load(Ordering::Acquire), 5);
        let sent = sent
            .lock()
            .expect("protocol-policy test sent-message mutex must not be poisoned");
        let [
            JsonRpcMessage::Response(initialize),
            JsonRpcMessage::Response(ping),
        ] = sent.as_slice()
        else {
            panic!(
                "the invalid notification must not respond or prevent the following legacy request"
            );
        };
        assert_eq!(initialize.id, Some(71_i64.into()));
        assert!(initialize.error.is_none());
        assert_eq!(ping.id, Some(72_i64.into()));
        assert!(ping.error.is_none());
    }

    #[test]
    fn rh5_stdio_rejects_server_notification_without_dispatch_or_connection_loss() {
        let sent = Arc::new(Mutex::new(Vec::new()));
        let receive_calls = Arc::new(AtomicUsize::new(0));
        let handler_calls = Arc::new(AtomicUsize::new(0));
        let middleware_calls = Arc::new(AtomicUsize::new(0));
        let saw_credential = Arc::new(AtomicBool::new(false));
        let server_notification = JsonRpcMessage::Request(JsonRpcRequest::notification(
            "notifications/progress",
            Some(serde_json::json!({
                "progressToken": "server-only",
                "progress": 1,
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                },
            })),
        ));
        let valid_call = JsonRpcMessage::Request(JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({
                "name": "modern_http_auth_counter",
                "arguments": {},
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                },
            })),
            73_i64,
        ));

        Server::new("stdio-wrong-direction-notification", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .middleware(ModernHttpAuthMiddleware {
                calls: Arc::clone(&middleware_calls),
                saw_credential: Arc::clone(&saw_credential),
            })
            .tool(ModernHttpAuthCounterTool {
                calls: Arc::clone(&handler_calls),
            })
            .build()
            .run_transport_returning_with_cx(
                &Cx::for_testing(),
                ProtocolPolicyScriptTransport {
                    inbound: std::collections::VecDeque::from([
                        modern_discovery_request(72),
                        server_notification,
                        valid_call,
                    ]),
                    sent: Arc::clone(&sent),
                    receive_calls: Arc::clone(&receive_calls),
                },
            )
            .expect("wrong-direction stdio notification must not close the connection");

        assert_eq!(receive_calls.load(Ordering::Acquire), 4);
        assert_eq!(middleware_calls.load(Ordering::Acquire), 2);
        assert_eq!(handler_calls.load(Ordering::Acquire), 1);
        assert!(!saw_credential.load(Ordering::Acquire));
        let sent = sent
            .lock()
            .expect("stdio sent-message mutex must not be poisoned");
        assert!(matches!(
            sent.as_slice(),
            [JsonRpcMessage::Response(discovery), JsonRpcMessage::Response(call)]
                if discovery.id == Some(72_i64.into())
                    && discovery.error.is_none()
                    && call.id == Some(73_i64.into())
                    && call.error.is_none()
        ));
    }

    // Exact-2024 era: legacy runtime context after a legacy opening.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn public_split_transport_legacy_runtime_retains_state_notifications_and_sampling() {
        let sent = live_legacy_runtime_connection_transcript(true);

        assert!(
            sent.iter().any(|message| {
                matches!(message, JsonRpcMessage::Request(request) if request.method == "sampling/createMessage")
            }),
            "an advertised legacy sampling capability must install the connection request sender"
        );
        assert_eq!(
            sent.iter()
                .filter(|message| {
                    matches!(message, JsonRpcMessage::Request(request) if request.method == "notifications/progress")
                })
                .count(),
            2,
            "both handler calls must use the connection notification sender for progress"
        );
        assert_eq!(
            sent.iter()
                .filter(|message| {
                    matches!(message, JsonRpcMessage::Request(request) if request.method == "notifications/message")
                })
                .count(),
            2,
            "the negotiated legacy log level must use the same notification sender"
        );

        let first = sent.iter().find_map(|message| match message {
            JsonRpcMessage::Response(response) if response.id == Some(703_i64.into()) => {
                response.result.as_ref()
            }
            _ => None,
        });
        assert_eq!(
            first
                .and_then(|result| result["content"].as_array())
                .and_then(|content| content.first())
                .and_then(|content| content["text"].as_str()),
            Some("legacy-runtime-1-sampled-value")
        );

        let second = sent.iter().find_map(|message| match message {
            JsonRpcMessage::Response(response) if response.id == Some(704_i64.into()) => {
                response.result.as_ref()
            }
            _ => None,
        });
        assert_eq!(
            second
                .and_then(|result| result["content"].as_array())
                .and_then(|content| content.first())
                .and_then(|content| content["text"].as_str()),
            Some("legacy-runtime-2-without-sampling"),
            "the second public-path call must observe the first call's SessionState mutation"
        );
    }

    // Exact-2024 era: legacy runtime context after a legacy opening.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn public_split_transport_legacy_context_installs_roots_provider_after_negotiation() {
        let sent = legacy_roots_context_transcript(true);
        assert!(
            sent.iter().any(|message| {
                matches!(message, JsonRpcMessage::Request(request) if request.method == "roots/list")
            }),
            "a negotiated roots capability must install a request-scoped roots provider"
        );
        let response = sent.iter().find_map(|message| match message {
            JsonRpcMessage::Response(response) if response.id == Some(732_i64.into()) => {
                response.result.as_ref()
            }
            _ => None,
        });
        assert_eq!(
            response
                .and_then(|result| result["content"].as_array())
                .and_then(|content| content.first())
                .and_then(|content| content["text"].as_str()),
            Some("negotiated roots: file:///workspace")
        );
    }

    // Exact-2024 era: legacy runtime context after a legacy opening.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn public_split_transport_legacy_context_withholds_roots_provider_without_capability() {
        let sent = legacy_roots_context_transcript(false);
        assert!(
            !sent.iter().any(|message| {
                matches!(message, JsonRpcMessage::Request(request) if request.method == "roots/list")
            }),
            "changing only the negotiated roots capability must not emit a roots request"
        );
        let response = sent.iter().find_map(|message| match message {
            JsonRpcMessage::Response(response) if response.id == Some(732_i64.into()) => {
                response.result.as_ref()
            }
            _ => None,
        });
        assert_eq!(
            response
                .and_then(|result| result["content"].as_array())
                .and_then(|content| content.first())
                .and_then(|content| content["text"].as_str()),
            Some("roots authority unavailable")
        );
    }

    // Exact-2024 era: legacy progress after a legacy opening.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn public_stdio_legacy_progress_token_installs_f64_notification_sender() {
        let sent = legacy_stdio_progress_transcript(true);
        let progress = sent.iter().find_map(|message| match message {
            JsonRpcMessage::Request(request) if request.method == "notifications/progress" => {
                Some(request)
            }
            _ => None,
        });
        let params = progress
            .and_then(|request| request.params.as_ref())
            .expect("the public legacy stdio request must emit progress");
        assert_eq!(
            params.get("progressToken"),
            Some(&serde_json::json!("legacy-stdio-progress"))
        );
        assert_eq!(
            params.get("progress").and_then(serde_json::Value::as_f64),
            Some(1.0)
        );
        assert_eq!(
            params.get("message"),
            Some(&serde_json::json!("legacy connection progress")),
            "legacy progress must retain its f64 ProgressParams wire model"
        );
    }

    // Exact-2024 era: legacy progress after a legacy opening.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn public_stdio_legacy_progress_sender_is_absent_when_only_token_is_removed() {
        let sent = legacy_stdio_progress_transcript(false);
        assert!(
            sent.iter().any(|message| matches!(
                message,
                JsonRpcMessage::Response(response)
                    if response.id == Some(712_i64.into()) && response.error.is_none()
            )),
            "removing only the progress token must retain normal legacy handler dispatch"
        );
        assert!(
            !sent.iter().any(|message| matches!(
                message,
                JsonRpcMessage::Request(request) if request.method == "notifications/progress"
            )),
            "removing only the progress token must leave the legacy progress sender absent"
        );
    }

    // Exact-2024 era: legacy server-to-client sampling.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn public_split_legacy_sampling_cancel_late_reply_preserves_connection() {
        let sent = Arc::new(Mutex::new(Vec::new()));
        let (outbound, inbound) = sync_channel(32);
        let result = run_live_split_transport(
            Duration::from_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS),
            Server::new("legacy-cancel-late", "1.0.0")
                .protocol_policy(ProtocolPolicy::Auto)
                .expect("Auto must be available to this test build")
                .tool(LiveLegacyRuntimeConnectionTool)
                .build(),
            LegacyCancelLateRecv {
                phase: 0,
                outbound: inbound,
                reverse_id: None,
                stale_offset: 0,
                cancellation_request_id: RequestId::Number(802),
            },
            LiveLegacyRuntimeSplitSend {
                sent: Arc::clone(&sent),
                outbound,
            },
        );
        assert!(
            result.is_ok(),
            "retired late response must preserve the connection: {result:?}; sent={:?}",
            sent.lock().expect("sent messages mutex")
        );
        assert!(
            sent.lock()
                .expect("sent messages mutex")
                .iter()
                .any(|message| matches!(
                    message,
            JsonRpcMessage::Response(response)
                if response.id == Some(803_i64.into())
                    && response
                        .result
                        .as_ref()
                        .and_then(|result| result.get("content"))
                        .is_some_and(|content| content.to_string().contains("legacy-runtime-2-without-sampling"))
                ))
        );
    }

    // Exact-2024 era: legacy server-to-client sampling.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn public_split_legacy_sampling_numeric_cancellation_alias_retires_late_reply() {
        let sent = Arc::new(Mutex::new(Vec::new()));
        let (outbound, inbound) = sync_channel(32);
        let result = run_live_split_transport(
            Duration::from_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS),
            Server::new("legacy-cancel-numeric-alias", "1.0.0")
                .protocol_policy(ProtocolPolicy::Auto)
                .expect("Auto must be available to this test build")
                .tool(LiveLegacyRuntimeConnectionTool)
                .build(),
            LegacyCancelLateRecv {
                phase: 0,
                outbound: inbound,
                reverse_id: None,
                stale_offset: 0,
                cancellation_request_id: RequestId::Integer("802e0".to_owned()),
            },
            LiveLegacyRuntimeSplitSend {
                sent: Arc::clone(&sent),
                outbound,
            },
        );
        result.expect(
            "numeric cancellation aliases must retire the late reply and preserve the connection",
        );
        assert!(
            sent.lock()
                .expect("sent messages mutex")
                .iter()
                .any(|message| matches!(
                    message,
                    JsonRpcMessage::Response(response)
                        if response.id == Some(803_i64.into())
                            && response
                                .result
                                .as_ref()
                                .and_then(|result| result.get("content"))
                                .is_some_and(|content| content.to_string().contains("legacy-runtime-2-without-sampling"))
                )),
            "changing only the cancellation ID spelling must retain the successful follow-up request"
        );
    }

    // Exact-2024 era: legacy server-to-client sampling.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn public_split_legacy_sampling_next_negative_reply_remains_invalid() {
        let sent = Arc::new(Mutex::new(Vec::new()));
        let (outbound, inbound) = sync_channel(32);
        let result = run_live_split_transport(
            Duration::from_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS),
            Server::new("legacy-cancel-next-negative", "1.0.0")
                .protocol_policy(ProtocolPolicy::Auto)
                .expect("Auto must be available to this test build")
                .tool(LiveLegacyRuntimeConnectionTool)
                .build(),
            LegacyCancelLateRecv {
                phase: 0,
                outbound: inbound,
                reverse_id: None,
                stale_offset: -1,
                cancellation_request_id: RequestId::Number(802),
            },
            LiveLegacyRuntimeSplitSend {
                sent: Arc::clone(&sent),
                outbound,
            },
        );
        result.expect_err("next unissued negative response must remain invalid");
        assert!(
            !sent
                .lock()
                .expect("sent messages mutex")
                .iter()
                .any(|message| matches!(
                        message,
                JsonRpcMessage::Response(response) if response.id == Some(803_i64.into())
                    ))
        );
    }

    // Exact-2024 era: legacy runtime context after a legacy opening.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn public_split_transport_legacy_runtime_rejects_sampling_when_only_capability_is_removed() {
        let sent = live_legacy_runtime_connection_transcript(false);

        assert!(
            !sent.iter().any(|message| {
                matches!(message, JsonRpcMessage::Request(request) if request.method == "sampling/createMessage")
            }),
            "removing only the advertised sampling capability must prevent a reverse request"
        );
        assert_eq!(
            sent.iter()
                .filter(|message| {
                    matches!(message, JsonRpcMessage::Request(request) if request.method == "notifications/progress")
                })
                .count(),
            2,
            "the negative must retain the same connection state and notification path"
        );

        let rejected = sent.iter().find_map(|message| match message {
            JsonRpcMessage::Response(response) if response.id == Some(703_i64.into()) => {
                Some(response)
            }
            _ => None,
        });
        let rejected_result = rejected
            .and_then(|response| response.result.as_ref())
            .expect("the tool-level sampling refusal must use a legacy tools/call result");
        assert_eq!(
            rejected_result.get("isError"),
            Some(&serde_json::json!(true))
        );
        assert!(
            rejected_result
                .get("content")
                .and_then(serde_json::Value::as_array)
                .and_then(|content| content.first())
                .and_then(|content| content.get("text"))
                .and_then(serde_json::Value::as_str)
                .is_some_and(|message| message.contains("Sampling not available")),
            "the otherwise identical handler call must fail at the advertised-capability gate"
        );

        let second = sent.iter().find_map(|message| match message {
            JsonRpcMessage::Response(response) if response.id == Some(704_i64.into()) => {
                response.result.as_ref()
            }
            _ => None,
        });
        assert_eq!(
            second
                .and_then(|result| result["content"].as_array())
                .and_then(|content| content.first())
                .and_then(|content| content["text"].as_str()),
            Some("legacy-runtime-2-without-sampling"),
            "removing only sampling capability must not replace the retained SessionState"
        );
    }

    // Exact-2024 era: legacy tools/call argument validation.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_runtime_rejects_only_non_object_legacy_tool_arguments_without_advancing_lifecycle() {
        let sent = Arc::new(Mutex::new(Vec::new()));

        run_returning_transport_with_test_runtime(
            Server::new("live-legacy-runtime-negative", "1.0.0")
                .protocol_policy(ProtocolPolicy::Auto)
                .expect("Auto must be available to this test build")
                .tool(LiveRuntimeListedTool)
                .build(),
            ProtocolPolicyScriptTransport {
                inbound: std::collections::VecDeque::from([
                    exact_legacy_initialize_request(51, serde_json::json!("1.0.0")),
                    JsonRpcMessage::Request(JsonRpcRequest::notification(
                        "notifications/initialized",
                        None,
                    )),
                    JsonRpcMessage::Request(JsonRpcRequest::new(
                        "tools/call",
                        Some(serde_json::json!({
                            "name": "live_runtime_listed_tool",
                            "arguments": [],
                        })),
                        52_i64,
                    )),
                    JsonRpcMessage::Request(JsonRpcRequest::new(
                        "tools/call",
                        Some(serde_json::json!({
                            "name": "live_runtime_listed_tool",
                            "arguments": {},
                        })),
                        53_i64,
                    )),
                ]),
                sent: Arc::clone(&sent),
                receive_calls: Arc::new(AtomicUsize::new(0)),
            },
        )
        .expect("only the changed invalid arguments field must be rejected");

        let sent = sent
            .lock()
            .expect("protocol-policy test sent-message mutex must not be poisoned");
        let [
            JsonRpcMessage::Response(initialize),
            JsonRpcMessage::Response(rejected),
            JsonRpcMessage::Response(call),
        ] = sent.as_slice()
        else {
            panic!(
                "a rejected tools/call must leave the exact lifecycle ready for the unchanged valid call"
            );
        };
        assert_eq!(initialize.id, Some(51_i64.into()));
        assert_eq!(
            initialize
                .result
                .as_ref()
                .and_then(|result| result["protocolVersion"].as_str()),
            Some(LEGACY_PROTOCOL_VERSION)
        );
        assert_eq!(rejected.id, Some(52_i64.into()));
        assert_eq!(
            rejected
                .error
                .as_ref()
                .and_then(|error| error.code.as_i32()),
            Some(-32602)
        );
        assert_eq!(call.id, Some(53_i64.into()));
        assert_eq!(
            call.result
                .as_ref()
                .and_then(|result| result["content"].as_array())
                .and_then(|content| content.first())
                .and_then(|content| content["text"].as_str()),
            Some("live runtime legacy adapter request 53")
        );
        assert!(
            call.result
                .as_ref()
                .is_some_and(|result| result.get("resultType").is_none())
        );
    }

    // Exact-2024 era: legacy completion/complete routing.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_runtime_routes_exact_legacy_completion_through_the_legacy_router_surface() {
        let sent = Arc::new(Mutex::new(Vec::new()));

        run_returning_transport_with_test_runtime(
            Server::new("live-legacy-completion", "1.0.0")
                .protocol_policy(ProtocolPolicy::Auto)
                .expect("Auto must be available to this test build")
                .completion_handler(LiveLegacyCompletionHandler)
                .build(),
            ProtocolPolicyScriptTransport {
                inbound: std::collections::VecDeque::from([
                    exact_legacy_initialize_request(61, serde_json::json!("1.0.0")),
                    JsonRpcMessage::Request(JsonRpcRequest::notification(
                        "notifications/initialized",
                        None,
                    )),
                    JsonRpcMessage::Request(JsonRpcRequest::new(
                        "completion/complete",
                        Some(serde_json::json!({
                            "ref": {"type": "ref/prompt", "name": "deploy"},
                            "argument": {"name": "environment", "value": "sta"},
                        })),
                        62_i64,
                    )),
                ]),
                sent: Arc::clone(&sent),
                receive_calls: Arc::new(AtomicUsize::new(0)),
            },
        )
        .expect("the live exact legacy completion route must return its legacy result");

        let sent = sent
            .lock()
            .expect("legacy completion sent-message mutex must not be poisoned");
        let [
            JsonRpcMessage::Response(initialize),
            JsonRpcMessage::Response(completion),
        ] = sent.as_slice()
        else {
            panic!("exact legacy completion must emit initialize and completion responses");
        };
        assert_eq!(initialize.id, Some(61_i64.into()));
        assert_eq!(completion.id, Some(62_i64.into()));
        assert_eq!(
            completion
                .result
                .as_ref()
                .and_then(|result| result["completion"]["values"].as_array())
                .and_then(|values| values.first())
                .and_then(serde_json::Value::as_str),
            Some("legacy:sta")
        );
        assert!(
            completion
                .result
                .as_ref()
                .is_some_and(|result| result.get("resultType").is_none())
        );
    }

    // Exact-2024 era: a legacy completion notification after a legacy initialize.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_runtime_rejects_completion_notification_without_invoking_handler() {
        let sent = Arc::new(Mutex::new(Vec::new()));
        let calls = Arc::new(AtomicUsize::new(0));
        let completion_params = serde_json::json!({
            "ref": {"type": "ref/prompt", "name": "deploy"},
            "argument": {"name": "environment", "value": "sta"},
        });

        run_returning_transport_with_test_runtime(
            Server::new("live-legacy-completion-id", "1.0.0")
                .protocol_policy(ProtocolPolicy::Auto)
                .expect("Auto must be available to this test build")
                .completion_handler(CountingLegacyCompletionHandler {
                    calls: Arc::clone(&calls),
                })
                .build(),
            ProtocolPolicyScriptTransport {
                inbound: std::collections::VecDeque::from([
                    exact_legacy_initialize_request(63, serde_json::json!("1.0.0")),
                    JsonRpcMessage::Request(JsonRpcRequest::notification(
                        "notifications/initialized",
                        None,
                    )),
                    JsonRpcMessage::Request(JsonRpcRequest::notification(
                        "completion/complete",
                        Some(completion_params.clone()),
                    )),
                    JsonRpcMessage::Request(JsonRpcRequest::new(
                        "completion/complete",
                        Some(completion_params),
                        64_i64,
                    )),
                ]),
                sent: Arc::clone(&sent),
                receive_calls: Arc::new(AtomicUsize::new(0)),
            },
        )
        .expect("the rejected notification must leave the valid request executable");

        assert_eq!(calls.load(Ordering::Acquire), 1);
        let sent = sent
            .lock()
            .expect("completion notification sent-message mutex must not be poisoned");
        let [
            JsonRpcMessage::Response(initialize),
            JsonRpcMessage::Response(completion),
        ] = sent.as_slice()
        else {
            panic!("only initialize and the ID-bearing completion may emit responses");
        };
        assert_eq!(initialize.id, Some(63_i64.into()));
        assert_eq!(completion.id, Some(64_i64.into()));
        assert_eq!(
            completion
                .result
                .as_ref()
                .and_then(|result| result["completion"]["values"].as_array())
                .and_then(|values| values.first())
                .and_then(serde_json::Value::as_str),
            Some("legacy:sta")
        );
    }

    #[test]
    fn builder_http_endpoint_dispatches_a_modern_request_end_to_end() {
        let cx = Cx::for_testing();
        let endpoint = Server::new("modern-http-endpoint", "1.0.0")
            .test_http_endpoint("http://legacy.test")
            .expect("builder must construct the configured dual-era endpoint");
        let mut session = endpoint
            .open_session(&cx)
            .expect("endpoint must open a bounded live session");
        let request = JsonRpcRequest::new(
            SERVER_DISCOVER_METHOD,
            Some(serde_json::json!({
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                },
            })),
            201_i64,
        );

        let response = block_on(
            session.handle_async(
                &cx,
                HttpRequest::new(HttpMethod::Post, "/mcp")
                    .with_header("content-type", "application/json")
                    .with_header("accept", "application/json")
                    .with_header("mcp-protocol-version", MODERN_PROTOCOL_VERSION)
                    .with_header("mcp-method", SERVER_DISCOVER_METHOD)
                    .with_body(
                        serde_json::to_vec(&request)
                            .expect("modern discovery request must serialize"),
                    ),
            ),
        )
        .expect("modern request must be admitted and dispatched");
        let ServerHttpEndpointResponse::Immediate(response) = response else {
            panic!("modern JSON negotiation must produce an immediate HTTP response");
        };
        assert_eq!(response.status, HttpStatus::OK);
        let response: JsonRpcResponse =
            serde_json::from_slice(&response.body).expect("modern response must be JSON-RPC");
        assert_eq!(response.id, Some(201_i64.into()));
        assert!(response.error.is_none());
        assert_eq!(
            response.result.as_ref().and_then(|result| {
                result["_meta"][fastmcp_protocol::SERVER_DISCOVER_SERVER_INFO_META_KEY]["name"]
                    .as_str()
            }),
            Some("modern-http-endpoint")
        );
    }

    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn public_http_endpoint_routes_a_shared_target_by_method() {
        let cx = Cx::for_testing();
        let endpoint = Server::new("http-shared-target", "1.0.0")
            .http_config(
                HttpServerConfig::new()
                    .mcp_path("/bridge")
                    .legacy_sse_path("/bridge")
                    .legacy_message_path("/messages"),
            )
            .build_http_endpoint("http://legacy.test")
            .expect("a shared modern POST and legacy GET target is valid");

        let mut legacy_session = endpoint
            .open_session(&cx)
            .expect("legacy session opens before shared-target GET");
        let rejected = block_on(legacy_session.handle_async(
            &cx,
            HttpRequest::new(HttpMethod::Get, "/bridge").with_body(b"{}".to_vec()),
        ))
        .expect("nonempty shared-target GET becomes an HTTP rejection");
        assert!(matches!(
            rejected,
            ServerHttpEndpointResponse::Immediate(response)
                if response.status == HttpStatus::BAD_REQUEST
        ));
        assert_eq!(legacy_session.selected_era, None);
        let legacy = block_on(
            legacy_session.handle_async(&cx, HttpRequest::new(HttpMethod::Get, "/bridge")),
        )
        .expect("shared GET target selects legacy SSE");
        assert!(matches!(legacy, ServerHttpEndpointResponse::LegacySse(_)));
        assert_eq!(legacy_session.selected_era, Some(ProtocolEra::Legacy2024));

        let mut modern_session = endpoint
            .open_session(&cx)
            .expect("modern session opens before shared-target POST");
        let mut modern = modern_http_json_tool_request("missing", 2_020);
        modern.path = "/bridge".to_owned();
        let modern = block_on(modern_session.handle_async(&cx, modern))
            .expect("shared POST target selects final modern admission");
        assert!(matches!(modern, ServerHttpEndpointResponse::Immediate(_)));
        assert_eq!(modern_session.selected_era, Some(ProtocolEra::Modern2026));
    }

    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn public_http_legacy_reconnect_rotates_the_advertised_post_capability() {
        let cx = Cx::for_testing();
        let endpoint = Server::new("http-legacy-reconnect", "1.0.0")
            .build_http_endpoint("http://legacy.test")
            .expect("dual-era endpoint must build");
        let mut session = endpoint
            .open_session(&cx)
            .expect("legacy session must open");
        let ServerHttpEndpointResponse::LegacySse(first) =
            block_on(session.handle_async(&cx, HttpRequest::new(HttpMethod::Get, "/sse")))
                .expect("first legacy GET must open")
        else {
            panic!("first legacy GET must return an SSE body");
        };
        let first_session_id = session.legacy_session_id().to_owned();
        drop(first);

        let ServerHttpEndpointResponse::LegacySse(mut second) = block_on(
            session.handle_async(
                &cx,
                HttpRequest::new(HttpMethod::Get, "/sse")
                    .with_header("last-event-id", "non-replayable"),
            ),
        )
        .expect("reconnect must open a fresh legacy body") else {
            panic!("reconnect must return an SSE body");
        };
        assert_ne!(session.legacy_session_id(), first_session_id);
        assert!(
            session.legacy_lifecycle.commit_if_live(|| ()).is_some(),
            "server fast paths must refresh to the reconnect generation"
        );
        assert_eq!(
            second
                .recv_event(&cx)
                .expect("fresh body must advertise its endpoint")
                .data,
            format!(
                "http://legacy.test/messages?session_id={}",
                session.legacy_session_id()
            )
        );

        let initialize = JsonRpcRequest::new(
            "initialize",
            Some(serde_json::json!({
                "protocolVersion": LEGACY_PROTOCOL_VERSION,
                "capabilities": {},
                "clientInfo": {"name": "reconnect-client", "version": "1.0.0"},
            })),
            2_024_i64,
        );
        let old_capability = block_on(
            session.handle_async(
                &cx,
                HttpRequest::new(HttpMethod::Post, "/messages")
                    .with_header("content-type", "application/json")
                    .with_query("session_id", first_session_id)
                    .with_body(
                        serde_json::to_vec(&initialize).expect("legacy initialize must serialize"),
                    ),
            ),
        )
        .expect("old POST capability must become an HTTP rejection");
        assert!(matches!(
            old_capability,
            ServerHttpEndpointResponse::Immediate(response)
                if response.status == HttpStatus::NOT_FOUND
        ));

        let current_session_id = session.legacy_session_id().to_owned();
        let current_capability = block_on(
            session.handle_async(
                &cx,
                HttpRequest::new(HttpMethod::Post, "/messages")
                    .with_header("content-type", "application/json")
                    .with_query("session_id", current_session_id)
                    .with_body(
                        serde_json::to_vec(&initialize).expect("legacy initialize must serialize"),
                    ),
            ),
        )
        .expect("fresh POST capability must remain usable");
        assert!(matches!(
            current_capability,
            ServerHttpEndpointResponse::Immediate(response)
                if response.status == HttpStatus::ACCEPTED
        ));
    }

    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn public_http_legacy_reconnect_revokes_server_issued_generation_capabilities() {
        let cx = Cx::for_testing();
        let endpoint = Server::new("http-legacy-capability-generation", "1.0.0")
            .build_http_endpoint("http://legacy.test")
            .expect("dual-era endpoint must build");
        let mut session = endpoint
            .open_session(&cx)
            .expect("legacy session must open");
        let ServerHttpEndpointResponse::LegacySse(mut first_stream) =
            block_on(session.handle_async(&cx, HttpRequest::new(HttpMethod::Get, "/sse")))
                .expect("first legacy GET must open")
        else {
            panic!("first legacy GET must return an SSE body");
        };
        let _first_endpoint = first_stream
            .recv_event(&cx)
            .expect("first body advertises its exact POST capability");
        let first_session_id = session.legacy_session_id().to_owned();
        let first_post = |message: JsonRpcMessage| {
            HttpRequest::new(HttpMethod::Post, "/messages")
                .with_header("content-type", "application/json")
                .with_query("session_id", first_session_id.clone())
                .with_body(serde_json::to_vec(&message).expect("legacy message must serialize"))
        };
        for message in [
            JsonRpcMessage::Request(JsonRpcRequest::new(
                "initialize",
                Some(serde_json::json!({
                    "protocolVersion": LEGACY_PROTOCOL_VERSION,
                    "capabilities": {"roots": {}},
                    "clientInfo": {"name": "first-generation", "version": "1.0.0"},
                })),
                2_041_i64,
            )),
            JsonRpcMessage::Request(JsonRpcRequest::notification(
                "notifications/initialized",
                None,
            )),
        ] {
            assert!(matches!(
                block_on(session.handle_async(&cx, first_post(message))),
                Ok(ServerHttpEndpointResponse::Immediate(response))
                    if response.status == HttpStatus::ACCEPTED
            ));
        }
        let _first_initialize = first_stream
            .recv_event(&cx)
            .expect("first generation initializes before exposing roots");
        let stale_provider = session
            .legacy_roots_provider()
            .expect("first generation advertises roots");
        let stale_pending = Arc::clone(&session.legacy_pending_requests);
        let stale_binding_generation = session.legacy_binding.generation();
        assert!(session.legacy_adapter.as_ref().is_some_and(|adapter| {
            let snapshot = adapter.snapshot();
            snapshot.operating_transition_count == 1 && snapshot.close_release_count == 0
        }));

        let stale_task = std::thread::spawn(move || block_on(stale_provider.list_roots()));
        let stale_request = first_stream
            .recv_event(&cx)
            .expect("old provider publishes only into its own live generation");
        let JsonRpcMessage::Request(stale_request) = Codec::new()
            .decode_complete_message(stale_request.data.as_bytes())
            .expect("old roots request remains JSON-RPC")
        else {
            panic!("old provider must emit a roots request");
        };
        let stale_request_id = stale_request.id.expect("old roots request has an ID");
        assert_eq!(stale_pending.in_flight_len(), 1);
        drop(first_stream);

        let ServerHttpEndpointResponse::LegacySse(mut fresh_stream) = block_on(
            session.handle_async(
                &cx,
                HttpRequest::new(HttpMethod::Get, "/sse")
                    .with_header("last-event-id", "old-generation"),
            ),
        )
        .expect("reconnect opens a fresh generation") else {
            panic!("reconnect must return an SSE body");
        };
        let _fresh_endpoint = fresh_stream
            .recv_event(&cx)
            .expect("fresh body advertises its new POST capability");
        assert_ne!(
            session.legacy_binding.generation(),
            stale_binding_generation
        );
        assert!(
            session.legacy_adapter.is_none(),
            "the old adapter cannot remain authoritative in the fresh generation"
        );
        assert_eq!(stale_pending.in_flight_len(), 0);
        assert!(
            stale_task
                .join()
                .expect("stale provider task must not panic")
                .is_err(),
            "body drop plus reconnect cancels the old provider's pending request"
        );
        assert!(
            fresh_stream
                .try_recv_event(&cx)
                .expect("fresh stream remains readable")
                .is_none(),
            "the stale runtime sender cannot publish into the fresh body"
        );

        let fresh_session_id = session.legacy_session_id().to_owned();
        let fresh_post = |message: JsonRpcMessage| {
            HttpRequest::new(HttpMethod::Post, "/messages")
                .with_header("content-type", "application/json")
                .with_query("session_id", fresh_session_id.clone())
                .with_body(serde_json::to_vec(&message).expect("legacy message must serialize"))
        };
        for message in [
            JsonRpcMessage::Request(JsonRpcRequest::new(
                "initialize",
                Some(serde_json::json!({
                    "protocolVersion": LEGACY_PROTOCOL_VERSION,
                    "capabilities": {"roots": {}},
                    "clientInfo": {"name": "fresh-generation", "version": "1.0.0"},
                })),
                2_042_i64,
            )),
            JsonRpcMessage::Request(JsonRpcRequest::notification(
                "notifications/initialized",
                None,
            )),
        ] {
            assert!(matches!(
                block_on(session.handle_async(&cx, fresh_post(message))),
                Ok(ServerHttpEndpointResponse::Immediate(response))
                    if response.status == HttpStatus::ACCEPTED
            ));
        }
        let _fresh_initialize = fresh_stream
            .recv_event(&cx)
            .expect("fresh generation initializes independently");
        let fresh_provider = session
            .legacy_roots_provider()
            .expect("fresh generation exposes its own roots provider");
        let fresh_task = std::thread::spawn(move || block_on(fresh_provider.list_roots()));
        let fresh_request = fresh_stream
            .recv_event(&cx)
            .expect("fresh provider publishes into the fresh body");
        let JsonRpcMessage::Request(fresh_request) = Codec::new()
            .decode_complete_message(fresh_request.data.as_bytes())
            .expect("fresh roots request remains JSON-RPC")
        else {
            panic!("fresh provider must emit a roots request");
        };
        let fresh_request_id = fresh_request.id.expect("fresh roots request has an ID");
        assert_eq!(fresh_request_id, stale_request_id);
        assert_eq!(session.legacy_pending_requests.in_flight_len(), 1);

        let stale_completion = JsonRpcResponse::success(
            stale_request_id,
            serde_json::json!({"roots": [{"uri": "file:///stale"}]}),
        );
        assert!(
            !stale_pending.route_response(&stale_completion),
            "the retained old PendingRequests authority cannot deliver after rotation"
        );
        assert_eq!(
            session.legacy_pending_requests.in_flight_len(),
            1,
            "stale completion leaves the fresh same-ID waiter unchanged"
        );

        let fresh_completion = JsonRpcResponse::success(
            fresh_request_id,
            serde_json::json!({"roots": [{"uri": "file:///fresh", "name": "fresh"}]}),
        );
        assert!(matches!(
            block_on(session.handle_async(
                &cx,
                fresh_post(JsonRpcMessage::Response(fresh_completion))
            )),
            Ok(ServerHttpEndpointResponse::Immediate(response))
                if response.status == HttpStatus::ACCEPTED
        ));
        let roots = fresh_task
            .join()
            .expect("fresh provider task must not panic")
            .expect("fresh response completes only the fresh provider");
        assert_eq!(roots.len(), 1);
        assert_eq!(roots[0].uri, "file:///fresh");
    }

    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn public_http_session_rejects_legacy_after_modern_admission_without_mutation() {
        let cx = Cx::for_testing();
        let endpoint = Server::new("http-era-pin-modern", "1.0.0")
            .build_http_endpoint("http://legacy.test")
            .expect("dual-era endpoint must build");
        let mut session = endpoint
            .open_session(&cx)
            .expect("session must open before first-era admission");

        let modern =
            block_on(session.handle_async(&cx, modern_http_json_tool_request("missing", 2_021)))
                .expect("an admitted modern request may return a JSON-RPC handler error");
        assert!(matches!(modern, ServerHttpEndpointResponse::Immediate(_)));
        let before_era = session.selected_era;
        let before_dispatches = session
            .modern_dispatches
            .lock()
            .expect("modern dispatch registry must not be poisoned")
            .len();
        assert_eq!(before_era, Some(ProtocolEra::Modern2026));
        assert!(session.legacy_adapter.is_none());

        let rejected =
            block_on(session.handle_async(&cx, HttpRequest::new(HttpMethod::Get, "/sse")))
                .expect("cross-era request must become an HTTP rejection");
        assert!(matches!(
            rejected,
            ServerHttpEndpointResponse::Immediate(response) if response.status == HttpStatus::BAD_REQUEST
        ));
        assert_eq!(session.selected_era, before_era);
        assert!(session.legacy_adapter.is_none());
        assert_eq!(
            session
                .modern_dispatches
                .lock()
                .expect("rejection must not poison modern dispatch state")
                .len(),
            before_dispatches,
            "changing only the HTTP era must not allocate legacy or modern session work",
        );
    }

    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn public_http_session_rejects_modern_after_legacy_admission_without_mutation() {
        let cx = Cx::for_testing();
        let endpoint = Server::new("http-era-pin-legacy", "1.0.0")
            .build_http_endpoint("http://legacy.test")
            .expect("dual-era endpoint must build");
        let mut session = endpoint
            .open_session(&cx)
            .expect("session must open before first-era admission");

        let legacy = block_on(session.handle_async(&cx, HttpRequest::new(HttpMethod::Get, "/sse")))
            .expect("legacy SSE opening request must be admitted");
        assert!(matches!(legacy, ServerHttpEndpointResponse::LegacySse(_)));
        let before_era = session.selected_era;
        let before_session_id = session.legacy_session_id().to_owned();
        let before_dispatches = session
            .modern_dispatches
            .lock()
            .expect("modern dispatch registry must not be poisoned")
            .len();
        assert_eq!(before_era, Some(ProtocolEra::Legacy2024));

        let rejected =
            block_on(session.handle_async(&cx, modern_http_json_tool_request("missing", 2_022)))
                .expect("cross-era request must become an HTTP rejection");
        assert!(matches!(
            rejected,
            ServerHttpEndpointResponse::Immediate(response) if response.status == HttpStatus::BAD_REQUEST
        ));
        assert_eq!(session.selected_era, before_era);
        assert_eq!(session.legacy_session_id(), before_session_id);
        assert_eq!(
            session
                .modern_dispatches
                .lock()
                .expect("rejection must not poison modern dispatch state")
                .len(),
            before_dispatches,
            "changing only the HTTP era must not allocate modern session work",
        );
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn builder_http_endpoint_dispatches_admitted_extension_without_metadata_leakage() {
        let cx = Cx::for_testing();
        let calls = Arc::new(AtomicUsize::new(0));
        let endpoint = extension_registry_test_server(Arc::clone(&calls))
            .test_http_endpoint("http://legacy.test")
            .expect("extension server must construct the configured HTTP endpoint");
        let mut session = endpoint
            .open_session(&cx)
            .expect("endpoint must open a bounded live session");

        let response = block_on(session.handle_async(
            &cx,
            extension_tasks_get_http_request(MODERN_PROTOCOL_VERSION),
        ))
        .expect("exact modern extension request must be admitted and dispatched");
        let ServerHttpEndpointResponse::Immediate(response) = response else {
            panic!("modern JSON extension dispatch must produce an immediate HTTP response");
        };
        assert_eq!(response.status, HttpStatus::OK);
        let response: JsonRpcResponse =
            serde_json::from_slice(&response.body).expect("modern response must be JSON-RPC");
        assert_eq!(response.id, Some(71_i64.into()));
        assert_eq!(response.result, Some(serde_json::json!({ "next": 42 })));
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    // Exact-2024 era: drives the dual-era internal HTTP dispatcher.
    #[cfg(all(feature = "tasks", feature = "legacy-2024-11-05"))]
    #[test]
    fn builder_http_endpoint_rejects_one_variable_wrong_extension_version() {
        let cx = Cx::for_testing();
        let calls = Arc::new(AtomicUsize::new(0));
        let endpoint = extension_registry_test_server(Arc::clone(&calls))
            .into_http_endpoint("http://legacy.test")
            .expect("extension server must construct the configured HTTP endpoint");
        let legacy_sessions: LiveHttpSessionRegistry = Arc::new(Mutex::new(HashMap::new()));
        let modern_sessions: LiveModernHttpSessionRegistry =
            Arc::new(LiveModernHttpSessionRegistryState::new());

        let response = dispatch_http_request(
            &cx,
            &endpoint,
            &legacy_sessions,
            &modern_sessions,
            extension_tasks_get_http_request(LEGACY_PROTOCOL_VERSION),
            None,
            LiveHttpLegacyDispatchMode::Blocking,
        );

        assert_eq!(response.status, HttpStatus::BAD_REQUEST);
        assert_eq!(calls.load(Ordering::SeqCst), 0);
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn live_modern_stdio_extension_preserves_metadata_through_admission() {
        let calls = Arc::new(AtomicUsize::new(0));
        let sent = Arc::new(Mutex::new(Vec::new()));
        extension_registry_test_server(Arc::clone(&calls))
            .run_transport_returning_with_cx(
                &Cx::for_testing(),
                ProtocolPolicyScriptTransport {
                    inbound: std::collections::VecDeque::from([
                        modern_discovery_opening_request(),
                        JsonRpcMessage::Request(extension_tasks_get_request(serde_json::json!({}))),
                    ]),
                    sent: Arc::clone(&sent),
                    receive_calls: Arc::new(AtomicUsize::new(0)),
                },
            )
            .expect("exact modern metadata must reach extension admission before sanitization");

        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn live_modern_stdio_extension_rejects_one_variable_wrong_version() {
        let calls = Arc::new(AtomicUsize::new(0));
        let sent = Arc::new(Mutex::new(Vec::new()));
        let mut wrong_version = extension_tasks_get_request(serde_json::json!({}));
        *wrong_version
            .params
            .as_mut()
            .and_then(|value| value.pointer_mut("/_meta/io.modelcontextprotocol~1protocolVersion"))
            .expect("extension request has modern protocol metadata") =
            serde_json::json!(LEGACY_PROTOCOL_VERSION);

        extension_registry_test_server(Arc::clone(&calls))
            .run_transport_returning_with_cx(
                &Cx::for_testing(),
                ProtocolPolicyScriptTransport {
                    inbound: std::collections::VecDeque::from([
                        modern_discovery_opening_request(),
                        JsonRpcMessage::Request(wrong_version),
                    ]),
                    sent: Arc::clone(&sent),
                    receive_calls: Arc::new(AtomicUsize::new(0)),
                },
            )
            // MCP 2026-07-28 (c7f4717b): a wrong version is a per-request
            // -32022 refusal and the stdio runtime keeps serving to EOF.
            .expect("only the extension protocol version differs from the admitted positive");

        assert_eq!(calls.load(Ordering::SeqCst), 0, "the handler never runs");
        let refused = sent.lock().unwrap().iter().any(|message| {
            matches!(message, JsonRpcMessage::Response(response)
                if response.error.as_ref().map(|error| error.code.clone())
                    == Some(fastmcp_protocol::UNSUPPORTED_PROTOCOL_VERSION_ERROR_CODE.into()))
        });
        assert!(
            refused,
            "the wrong version receives the typed -32022 refusal"
        );
    }

    // Exact-2024 era: selects LegacyOnly, which a no-legacy build refuses.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn public_http_protocol_policy_rejects_opposite_era_requests_both_ways() {
        let modern_request = JsonRpcRequest::new(
            SERVER_DISCOVER_METHOD,
            Some(serde_json::json!({
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                },
            })),
            218_i64,
        );
        let modern_inbound =
            InboundRequestContext::new(Cx::for_testing(), 218, InboundRequestTransport::Http);
        let legacy_only = Server::new("legacy-only-http-policy", "1.0.0")
            .protocol_policy(ProtocolPolicy::LegacyOnly)
            .expect("LegacyOnly must be available to this test build")
            .build();
        let modern_response = block_on(legacy_only.dispatch_http_with_protocol_policy(
            ProtocolPolicy::LegacyOnly,
            &modern_inbound,
            &modern_request,
        ));
        assert_eq!(modern_response.status, HttpStatus::BAD_REQUEST);

        let legacy_request = JsonRpcRequest::new(
            "initialize",
            Some(serde_json::json!({
                "protocolVersion": LEGACY_PROTOCOL_VERSION,
                "capabilities": {},
                "clientInfo": {"name": "legacy-http-client", "version": "1.0.0"},
            })),
            219_i64,
        );
        let legacy_inbound =
            InboundRequestContext::new(Cx::for_testing(), 219, InboundRequestTransport::Http);
        let modern_only = Server::new("modern-only-http-policy", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .build();
        let legacy_response = block_on(modern_only.dispatch_http_with_protocol_policy(
            ProtocolPolicy::ModernOnly,
            &legacy_inbound,
            &legacy_request,
        ));
        assert_eq!(legacy_response.status, HttpStatus::BAD_REQUEST);
    }

    #[test]
    fn public_http_protocol_policy_admits_matching_modern_metadata() {
        let request = JsonRpcRequest::new(
            SERVER_DISCOVER_METHOD,
            Some(serde_json::json!({
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                },
            })),
            220_i64,
        );
        let inbound =
            InboundRequestContext::new(Cx::for_testing(), 220, InboundRequestTransport::Http);
        let server = Server::new("modern-http-policy", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .build();

        let response = block_on(server.dispatch_http_with_protocol_policy(
            ProtocolPolicy::ModernOnly,
            &inbound,
            &request,
        ));

        assert_eq!(response.status, HttpStatus::OK);
        let response: JsonRpcResponse =
            serde_json::from_slice(&response.body).expect("modern response must be JSON-RPC");
        assert_eq!(response.id, Some(220_i64.into()));
        assert!(response.error.is_none());
    }

    #[test]
    fn public_http_protocol_policy_rejects_metadata_free_modern_request() {
        // This differs from the matching-metadata positive only by omitting
        // the final-era protocol marker. Public dispatch must not infer the
        // modern era merely because the caller selected ModernOnly.
        let request =
            JsonRpcRequest::new(SERVER_DISCOVER_METHOD, Some(serde_json::json!({})), 220_i64);
        let inbound =
            InboundRequestContext::new(Cx::for_testing(), 220, InboundRequestTransport::Http);
        let server = Server::new("modern-http-policy", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .build();

        let response = block_on(server.dispatch_http_with_protocol_policy(
            ProtocolPolicy::ModernOnly,
            &inbound,
            &request,
        ));

        assert_eq!(response.status, HttpStatus::BAD_REQUEST);
        let response: JsonRpcResponse =
            serde_json::from_slice(&response.body).expect("rejection must be JSON-RPC");
        assert_eq!(response.id, Some(220_i64.into()));
        assert!(response.result.is_none());
        assert_eq!(
            response
                .error
                .as_ref()
                .and_then(|error| error.code.as_i32()),
            Some(McpErrorCode::InvalidRequest.into())
        );
    }

    #[test]
    fn live_http_loopback_dispatches_modern_json_over_a_real_socket() {
        run_live_http_test(|cx| async move {
            let bound = Server::new("live-modern-http", "1.0.0")
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("live modern HTTP bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("live modern HTTP address failed: {error}"))?;
            let caller_cx = cx.clone();
            let request = JsonRpcRequest::new(
                SERVER_DISCOVER_METHOD,
                Some(serde_json::json!({
                    "_meta": {
                        MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                        FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                    },
                })),
                801_i64,
            );
            let body = serde_json::to_vec(&request)
                .map_err(|error| format!("modern wire request did not serialize: {error}"))?;
            let request = live_http_post(
                "/mcp",
                &body,
                &[
                    ("Accept", "application/json"),
                    ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                    ("Mcp-Method", SERVER_DISCOVER_METHOD),
                ],
            );
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let response = live_http_exchange(address, request).await;
                    caller_cx.cancel_with(CancelKind::User, Some("modern loopback complete"));
                    response
                })
                .map_err(|error| format!("modern loopback client admission failed: {error}"))?;

            let serve = bound.serve(&cx).await;
            let response = client
                .join(&cx)
                .await
                .map_err(|error| format!("modern loopback client failed: {error:?}"))??;
            let shutdown =
                serve.map_err(|error| format!("modern loopback server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "modern loopback").await?;

            let response = std::str::from_utf8(&response)
                .map_err(|error| format!("modern loopback response was not UTF-8: {error}"))?;
            if !response.starts_with("HTTP/1.1 200") {
                return Err(format!(
                    "modern loopback response status was unexpected: {response}"
                ));
            }
            if !response
                .to_ascii_lowercase()
                .contains("\r\nconnection: close\r\n")
            {
                return Err(format!(
                    "single-request HTTP response did not declare connection closure: {response}"
                ));
            }
            if live_http_response_header(response.as_bytes(), "mcp-session-id").is_ok() {
                return Err("modern discovery response issued MCP-Session-Id".to_owned());
            }
            let response: JsonRpcResponse = serde_json::from_slice(live_http_response_body(
                response.as_bytes(),
            )?)
            .map_err(|error| format!("modern loopback JSON-RPC response was invalid: {error}"))?;
            if response.id != Some(801_i64.into()) || response.error.is_some() {
                return Err(format!(
                    "modern loopback request was not dispatched: {response:?}"
                ));
            }
            if response.result.as_ref().and_then(|result| {
                result["_meta"][fastmcp_protocol::SERVER_DISCOVER_SERVER_INFO_META_KEY]["name"]
                    .as_str()
            }) != Some("live-modern-http")
            {
                return Err(format!(
                    "modern loopback discovery result was unexpected: {response:?}"
                ));
            }
            Ok(())
        });
    }

    /// Explicit test consent backend installed through the production API;
    /// native Basic tests do not depend on the cfg(test) default approval.
    struct NativeBasicConsent;

    impl oauth::AuthorizationApprovalBackend for NativeBasicConsent {
        fn generation(&self) -> oauth::AuthorizationApprovalGeneration {
            oauth::AuthorizationApprovalGeneration::from_bytes([0x42; 32])
        }

        fn approve(
            &self,
            request: &oauth::AuthorizationApprovalRequest,
        ) -> oauth::AuthorizationApprovalDisposition {
            oauth::AuthorizationApprovalDisposition::Approved(
                request
                    .approve(
                        "native-basic-owner".to_owned(),
                        request.scopes().to_vec(),
                        request.resource().map(str::to_owned),
                        self.generation(),
                    )
                    .expect("approve the exact bounded client request"),
            )
        }
    }

    fn native_oauth_basic_header(encoded_components: &str) -> String {
        use base64::Engine as _;
        format!(
            "Basic {}",
            base64::engine::general_purpose::STANDARD.encode(encoded_components),
        )
    }

    fn native_oauth_basic_fixture() -> (OAuthHttpRoutes, String, String) {
        native_oauth_client_method_fixture(oauth::TokenEndpointAuthMethod::ClientSecretBasic)
    }

    fn native_oauth_client_method_fixture(
        method: oauth::TokenEndpointAuthMethod,
    ) -> (OAuthHttpRoutes, String, String) {
        let oauth = Arc::new(
            oauth::OAuthServer::try_with_approval_backend(
                oauth::OAuthServerConfig::default(),
                Arc::new(NativeBasicConsent),
            )
            .expect("valid explicit consent configuration"),
        );
        oauth
            .register_client(
                oauth::OAuthClient::builder("native:basic+client")
                    .secret("S3cret:+ &=%")
                    .token_endpoint_auth_method(method)
                    .redirect_uri("https://client.example.test/callback")
                    .scope("mcp")
                    .build()
                    .expect("bounded confidential client"),
            )
            .expect("register confidential client");
        let (code, _) = oauth
            .authorize(&oauth::AuthorizationRequest {
                response_type: "code".to_owned(),
                client_id: "native:basic+client".to_owned(),
                redirect_uri: "https://client.example.test/callback".to_owned(),
                scopes: vec!["mcp".to_owned()],
                resource: None,
                state: None,
                code_challenge: "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM".to_owned(),
                code_challenge_method: oauth::CodeChallengeMethod::S256,
            })
            .expect("issue a code through the explicit consent backend");
        let form = format!(
            "grant_type=authorization_code&code={code}&redirect_uri=https%3A%2F%2Fclient.example.test%2Fcallback&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
        );
        // These literal OAuth components exercise encoded colons, plus signs,
        // spaces, ampersands, equals signs and percent signs independently of
        // the production percent decoder.
        let basic = native_oauth_basic_header("native%3Abasic%2Bclient:S3cret%3A%2B+%26%3D%25");
        let routes = OAuthHttpRoutes::new(oauth, "https://fastmcp.invalid/oauth")
            .expect("native OAuth routes");
        (routes, form, basic)
    }

    fn native_oauth_form_request(
        path: &str,
        form: &str,
        authorization: Option<&str>,
    ) -> asupersync::http::h1::Request {
        let mut headers = vec![(
            "Content-Type".to_owned(),
            "application/x-www-form-urlencoded".to_owned(),
        )];
        if let Some(authorization) = authorization {
            headers.push(("Authorization".to_owned(), authorization.to_owned()));
        }
        asupersync::http::h1::Request {
            method: Http1Method::Post,
            uri: path.to_owned(),
            version: asupersync::http::h1::Version::Http11,
            headers,
            body: form.as_bytes().to_vec(),
            trailers: Vec::new(),
            peer_addr: None,
        }
    }

    #[cfg(all(feature = "builtin-auth-server", feature = "oauth-client-credentials"))]
    fn native_development_machine_fixture(enabled: bool) -> (OAuthHttpRoutes, String) {
        let oauth = Arc::new(
            oauth::OAuthServer::try_new(oauth::OAuthServerConfig {
                allow_development_client_credentials: enabled,
                ..oauth::OAuthServerConfig::default()
            })
            .unwrap(),
        );
        let endpoint =
            fastmcp_core::CanonicalHttpUrl::parse("https://resource.example/api").unwrap();
        let resource = fastmcp_core::CanonicalResourceId::parse_for_endpoint(
            endpoint.as_str(),
            &endpoint,
            fastmcp_core::CanonicalResourceIdPolicy::DEFAULT,
        )
        .unwrap();
        oauth
            .register_client(
                oauth::OAuthClient::builder("native-machine")
                    .secret("machine-secret")
                    .scope("browser:admin")
                    .development_client_credentials(
                        oauth::DevelopmentClientCredentialsGrant::new(
                            resource,
                            ["machine:read", "machine:write"],
                        )
                        .unwrap(),
                    )
                    .build()
                    .unwrap(),
            )
            .unwrap();
        (
            OAuthHttpRoutes::new(oauth, "https://fastmcp.invalid/oauth").unwrap(),
            native_oauth_basic_header("native-machine:machine-secret"),
        )
    }

    #[cfg(all(feature = "builtin-auth-server", feature = "oauth-client-credentials"))]
    #[test]
    fn native_development_client_credentials_issue_revoke_and_advertise_exact_enabled_grant() {
        let (routes, basic) = native_development_machine_fixture(true);
        let form = "grant_type=client_credentials&resource=https%3A%2F%2Fresource.example%2Fapi&scope=machine%3Awrite+machine%3Aread";
        let request = native_oauth_form_request(routes.token_path(), form, Some(&basic));
        let response = dispatch_oauth_h1_request(&routes, &request, routes.token_path(), "");
        assert_eq!(response.status, HttpStatus::OK);
        assert_eq!(
            response.headers.get("cache-control").map(String::as_str),
            Some("no-store")
        );
        assert_eq!(
            response.headers.get("pragma").map(String::as_str),
            Some("no-cache")
        );
        let issued: serde_json::Value = serde_json::from_slice(&response.body).unwrap();
        assert_eq!(issued["scope"], "machine:read machine:write");
        assert_eq!(issued["expires_in"], 900);
        assert!(issued.get("refresh_token").is_none());
        assert!(issued.get("id_token").is_none());
        let token = issued["access_token"].as_str().unwrap();
        let retained = routes.server().validate_access_token(token).unwrap();
        assert_eq!(retained.client_id, "native-machine");
        assert!(retained.subject.is_none());
        assert_eq!(
            retained.resource.as_deref(),
            Some("https://resource.example/api")
        );

        let mut metadata_request = native_oauth_form_request(routes.metadata_path(), "", None);
        metadata_request.method = Http1Method::Get;
        metadata_request.headers.clear();
        let metadata =
            dispatch_oauth_h1_request(&routes, &metadata_request, routes.metadata_path(), "");
        assert_eq!(metadata.status, HttpStatus::OK);
        let metadata: serde_json::Value = serde_json::from_slice(&metadata.body).unwrap();
        assert_eq!(
            metadata["grant_types_supported"],
            serde_json::json!(["authorization_code", "refresh_token", "client_credentials",])
        );
        assert!(
            metadata["token_endpoint_auth_methods_supported"]
                .as_array()
                .unwrap()
                .iter()
                .any(|method| method == "client_secret_basic")
        );

        let revoke = native_oauth_form_request(
            routes.revocation_path(),
            &format!("token={token}"),
            Some(&basic),
        );
        let response = dispatch_oauth_h1_request(&routes, &revoke, routes.revocation_path(), "");
        assert_eq!(response.status, HttpStatus::OK);
        assert!(routes.server().validate_access_token(token).is_none());
        assert_eq!(routes.server().stats().refresh_tokens, 0);
    }

    #[cfg(all(feature = "builtin-auth-server", feature = "oauth-client-credentials"))]
    #[test]
    fn native_development_client_credentials_reject_method_resource_scope_and_mixed_grants() {
        let (routes, basic) = native_development_machine_fixture(true);
        let base = "grant_type=client_credentials&resource=https%3A%2F%2Fresource.example%2Fapi&scope=machine%3Aread";
        let baseline = native_oauth_form_request(routes.token_path(), base, Some(&basic));
        let response = dispatch_oauth_h1_request(&routes, &baseline, routes.token_path(), "");
        assert_eq!(response.status, HttpStatus::OK);
        let issued: serde_json::Value = serde_json::from_slice(&response.body).unwrap();
        let token = issued["access_token"].as_str().unwrap();
        for (form, authorization, status, error, challenge) in [
            (
                base.to_string(),
                Some(native_oauth_basic_header("native-machine:wrong-secret")),
                HttpStatus::UNAUTHORIZED,
                "invalid_client",
                Some("Basic realm=\"oauth\""),
            ),
            (
                format!("{base}&client_id=native-machine&client_secret=machine-secret"),
                None,
                HttpStatus::BAD_REQUEST,
                "invalid_client",
                None,
            ),
            (
                base.replace("resource.example%2Fapi", "resource.example%2Fother"),
                Some(basic.clone()),
                HttpStatus::BAD_REQUEST,
                "invalid_request",
                None,
            ),
            (
                base.replace("machine%3Aread", "browser%3Aadmin"),
                Some(basic.clone()),
                HttpStatus::BAD_REQUEST,
                "invalid_scope",
                None,
            ),
            (
                base.replace("machine%3Aread", "machine%3Aread%09machine%3Awrite"),
                Some(basic.clone()),
                HttpStatus::BAD_REQUEST,
                "invalid_request",
                None,
            ),
            (
                base.replace("machine%3Aread", "+machine%3Aread"),
                Some(basic.clone()),
                HttpStatus::BAD_REQUEST,
                "invalid_scope",
                None,
            ),
            (
                base.replace("machine%3Aread", "machine%3Aread++machine%3Awrite"),
                Some(basic.clone()),
                HttpStatus::BAD_REQUEST,
                "invalid_scope",
                None,
            ),
            (
                base.replace("&scope=machine%3Aread", ""),
                Some(basic.clone()),
                HttpStatus::BAD_REQUEST,
                "invalid_scope",
                None,
            ),
            (
                format!("{base}&scope=machine%3Aread"),
                Some(basic.clone()),
                HttpStatus::BAD_REQUEST,
                "invalid_request",
                None,
            ),
            (
                format!("{base}&resource=https%3A%2F%2Fresource.example%2Fapi"),
                Some(basic.clone()),
                HttpStatus::BAD_REQUEST,
                "invalid_request",
                None,
            ),
            (
                format!("{base}&code="),
                Some(basic.clone()),
                HttpStatus::BAD_REQUEST,
                "invalid_request",
                None,
            ),
            (
                format!("{base}&client_assertion=ignored"),
                Some(basic.clone()),
                HttpStatus::BAD_REQUEST,
                "invalid_request",
                None,
            ),
            (
                format!("{base}&client_assertion_type=ignored"),
                Some(basic.clone()),
                HttpStatus::BAD_REQUEST,
                "invalid_request",
                None,
            ),
        ] {
            let request =
                native_oauth_form_request(routes.token_path(), &form, authorization.as_deref());
            let response = dispatch_oauth_h1_request(&routes, &request, routes.token_path(), "");
            assert_native_oauth_error(&response, status, error, challenge);
            assert_eq!(routes.server().stats().access_tokens, 1);
            assert_eq!(routes.server().stats().refresh_tokens, 0);
            assert_eq!(routes.server().stats().revoked_tokens, 0);
            assert!(routes.server().validate_access_token(token).is_some());
        }
    }

    #[cfg(all(feature = "builtin-auth-server", feature = "oauth-client-credentials"))]
    #[test]
    fn native_development_client_credentials_opt_in_does_not_change_disabled_issuer_behavior() {
        let (routes, basic) = native_development_machine_fixture(false);
        assert_eq!(
            routes
                .authorization_server_metadata()
                .unwrap()
                .grant_types_supported,
            ["authorization_code", "refresh_token"]
        );
        let base = "grant_type=client_credentials&resource=https%3A%2F%2Fresource.example%2Fapi&scope=machine%3Aread";
        for form in [
            base.to_string(),
            format!("{base}&code="),
            format!("{base}&client_assertion=ignored"),
            base.replace("machine%3Aread", "machine%3Aread++machine%3Awrite"),
        ] {
            let request = native_oauth_form_request(routes.token_path(), &form, Some(&basic));
            let response = dispatch_oauth_h1_request(&routes, &request, routes.token_path(), "");
            assert_native_oauth_error(
                &response,
                HttpStatus::BAD_REQUEST,
                "unsupported_grant_type",
                None,
            );
            assert_eq!(routes.server().stats().access_tokens, 0);
            assert_eq!(routes.server().stats().refresh_tokens, 0);
        }
    }

    fn assert_native_oauth_error(
        response: &HttpResponse,
        status: HttpStatus,
        error: &str,
        challenge: Option<&str>,
    ) {
        assert_eq!(response.status, status);
        assert_eq!(
            serde_json::from_slice::<serde_json::Value>(&response.body).expect("OAuth error JSON"),
            serde_json::json!({ "error": error }),
        );
        assert_eq!(
            response.headers.get("www-authenticate").map(String::as_str),
            challenge,
        );
        assert_eq!(
            response.headers.get("cache-control").map(String::as_str),
            Some("no-store"),
        );
        assert_eq!(
            response.headers.get("pragma").map(String::as_str),
            Some("no-cache"),
        );
    }

    #[test]
    fn native_oauth_basic_rejections_preserve_code_and_live_grant() {
        let (routes, form, basic) = native_oauth_basic_fixture();
        let token_path = routes.token_path();
        let bad_secret = native_oauth_basic_header("native%3Abasic%2Bclient:wrong-secret");
        let unknown_client = native_oauth_basic_header("unknown-client:wrong-secret");
        for authorization in [
            bad_secret.as_str(),
            unknown_client.as_str(),
            "Basic malformed!",
            "Basic",
            "Basic \tY2xpZW50OnNlY3JldA==",
        ] {
            let request = native_oauth_form_request(token_path, &form, Some(authorization));
            assert_native_oauth_error(
                &dispatch_oauth_h1_request(&routes, &request, token_path, ""),
                HttpStatus::UNAUTHORIZED,
                "invalid_client",
                Some("Basic realm=\"oauth\""),
            );
        }
        for extra in [
            "client_id=native%3Abasic%2Bclient",
            "client_id=",
            "client_secret=wrong-secret",
            "client_secret=",
            "client%5Fsecret=",
        ] {
            let mixed_form = format!("{form}&{extra}");
            let request = native_oauth_form_request(token_path, &mixed_form, Some(&basic));
            assert_native_oauth_error(
                &dispatch_oauth_h1_request(&routes, &request, token_path, ""),
                HttpStatus::BAD_REQUEST,
                "invalid_request",
                None,
            );
        }
        let mut duplicate_header = native_oauth_form_request(token_path, &form, Some(&basic));
        duplicate_header
            .headers
            .push(("authorization".to_owned(), basic.clone()));
        assert_native_oauth_error(
            &dispatch_oauth_h1_request(&routes, &duplicate_header, token_path, ""),
            HttpStatus::BAD_REQUEST,
            "invalid_request",
            None,
        );
        let request = native_oauth_form_request(token_path, &form, Some(&basic));
        let issued = dispatch_oauth_h1_request(&routes, &request, token_path, "");
        assert_eq!(
            issued.status,
            HttpStatus::OK,
            "rejections must preserve the code",
        );
        let issued: serde_json::Value = serde_json::from_slice(&issued.body).expect("token JSON");
        let access = issued["access_token"].as_str().expect("access token");
        let refresh = issued["refresh_token"].as_str().expect("refresh token");
        assert!(routes.server().validate_access_token(access).is_some());
        let refresh_form = format!("grant_type=refresh_token&refresh_token={refresh}");
        let request = native_oauth_form_request(token_path, &refresh_form, Some(&bad_secret));
        assert_native_oauth_error(
            &dispatch_oauth_h1_request(&routes, &request, token_path, ""),
            HttpStatus::UNAUTHORIZED,
            "invalid_client",
            Some("Basic realm=\"oauth\""),
        );
        let revoke_path = routes.revocation_path();
        let revoke_form = format!("token={refresh}");
        let request = native_oauth_form_request(revoke_path, &revoke_form, Some(&bad_secret));
        assert_native_oauth_error(
            &dispatch_oauth_h1_request(&routes, &request, revoke_path, ""),
            HttpStatus::UNAUTHORIZED,
            "invalid_client",
            Some("Basic realm=\"oauth\""),
        );
        let request = native_oauth_form_request(
            revoke_path,
            &format!("{revoke_form}&client_secret="),
            Some(&basic),
        );
        assert_native_oauth_error(
            &dispatch_oauth_h1_request(&routes, &request, revoke_path, ""),
            HttpStatus::BAD_REQUEST,
            "invalid_request",
            None,
        );
        assert!(routes.server().validate_access_token(access).is_some());
        let request = native_oauth_form_request(token_path, &refresh_form, Some(&basic));
        let refreshed = dispatch_oauth_h1_request(&routes, &request, token_path, "");
        assert_eq!(
            refreshed.status,
            HttpStatus::OK,
            "rejections must preserve refresh",
        );
        let refreshed: serde_json::Value =
            serde_json::from_slice(&refreshed.body).expect("refreshed token JSON");
        let successor = refreshed["access_token"].as_str().expect("successor token");
        assert!(routes.server().validate_access_token(successor).is_some());
        let request =
            native_oauth_form_request(revoke_path, &format!("token={successor}"), Some(&basic));
        assert_eq!(
            dispatch_oauth_h1_request(&routes, &request, revoke_path, "").status,
            HttpStatus::OK,
        );
        assert!(routes.server().validate_access_token(successor).is_none());
    }

    #[test]
    fn native_oauth_basic_decoding_is_bounded_and_preserves_empty_password_authentication() {
        let client_id = "%61".repeat(oauth::MAX_OAUTH_CLIENT_ID_BYTES);
        let secret = "%62".repeat(oauth::MAX_OAUTH_CLIENT_CREDENTIAL_BYTES);
        let basic = native_oauth_basic_header(&format!("{client_id}:{secret}"));
        let mut admission =
            OAuthParameterAdmission::admit(OAuthParameterEndpoint::TokenForm, b"").unwrap();
        let (id, password, method) = oauth_http_client_credentials(&mut admission, Some(&basic))
            .expect("exact maximum percent-expanded credentials");
        assert_eq!(method, oauth::TokenEndpointAuthMethod::ClientSecretBasic);
        assert_eq!(id, "a".repeat(oauth::MAX_OAUTH_CLIENT_ID_BYTES));
        assert_eq!(
            password,
            Some("b".repeat(oauth::MAX_OAUTH_CLIENT_CREDENTIAL_BYTES)),
        );
        for components in [
            format!("{client_id}a:{secret}"),
            format!("{client_id}:{secret}b"),
            format!("{client_id}a:secret"),
            format!("client:{secret}b"),
            "client:%".to_owned(),
            "client:%GG".to_owned(),
            "client:%ff".to_owned(),
            "client:%0a".to_owned(),
            "client-without-colon".to_owned(),
            ":secret".to_owned(),
        ] {
            let basic = native_oauth_basic_header(&components);
            let mut admission =
                OAuthParameterAdmission::admit(OAuthParameterEndpoint::TokenForm, b"").unwrap();
            let error = oauth_http_client_credentials(&mut admission, Some(&basic))
                .expect_err("invalid Basic input must fail before authentication");
            assert_native_oauth_error(
                &error,
                HttpStatus::UNAUTHORIZED,
                "invalid_client",
                Some("Basic realm=\"oauth\""),
            );
        }
        let oauth = Arc::new(oauth::OAuthServer::with_defaults());
        oauth
            .register_client(
                oauth::OAuthClient::builder("public-client")
                    .redirect_uri("https://client.example.test/callback")
                    .build()
                    .expect("public client"),
            )
            .unwrap();
        let routes = OAuthHttpRoutes::new(oauth, "https://fastmcp.invalid/oauth").unwrap();
        let empty_password = native_oauth_basic_header("public-client:");
        let request = native_oauth_form_request(
            routes.revocation_path(),
            "token=unknown-token",
            Some(&empty_password),
        );
        assert_native_oauth_error(
            &dispatch_oauth_h1_request(&routes, &request, routes.revocation_path(), ""),
            HttpStatus::UNAUTHORIZED,
            "invalid_client",
            Some("Basic realm=\"oauth\""),
        );
        for secret_field in ["client_secret=", "client%5Fsecret="] {
            let request = native_oauth_form_request(
                routes.revocation_path(),
                &format!("token=unknown-token&client_id=public-client&{secret_field}"),
                None,
            );
            assert_native_oauth_error(
                &dispatch_oauth_h1_request(&routes, &request, routes.revocation_path(), ""),
                HttpStatus::BAD_REQUEST,
                "invalid_client",
                None,
            );
        }
        let request = native_oauth_form_request(
            routes.revocation_path(),
            "token=unknown-token&client_id=public-client",
            None,
        );
        assert_eq!(
            dispatch_oauth_h1_request(&routes, &request, routes.revocation_path(), "").status,
            HttpStatus::OK,
            "the same public client remains usable with none authentication",
        );
    }

    #[test]
    fn native_oauth_registered_authentication_method_controls_code_refresh_and_revoke() {
        for registered in [
            oauth::TokenEndpointAuthMethod::ClientSecretBasic,
            oauth::TokenEndpointAuthMethod::ClientSecretPost,
        ] {
            let (routes, code_form, basic) = native_oauth_client_method_fixture(registered);
            let token_path = routes.token_path();
            let revoke_path = routes.revocation_path();
            let basic_registered = registered == oauth::TokenEndpointAuthMethod::ClientSecretBasic;
            // The decoded client ID and secret are identical in both requests.
            // Only their credential location differs from the registration.
            let request = |path: &str, form: &str, use_basic: bool| {
                if use_basic {
                    native_oauth_form_request(path, form, Some(&basic))
                } else {
                    native_oauth_form_request(
                        path,
                        &format!(
                            "{form}&client_id=native%3Abasic%2Bclient&client_secret=S3cret%3A%2B+%26%3D%25"
                        ),
                        None,
                    )
                }
            };
            let assert_method_rejection = |response: &HttpResponse| {
                assert_native_oauth_error(
                    response,
                    if basic_registered {
                        HttpStatus::BAD_REQUEST
                    } else {
                        HttpStatus::UNAUTHORIZED
                    },
                    "invalid_client",
                    if basic_registered {
                        None
                    } else {
                        Some("Basic realm=\"oauth\"")
                    },
                );
            };
            let denied = request(token_path, &code_form, !basic_registered);
            assert_method_rejection(&dispatch_oauth_h1_request(&routes, &denied, token_path, ""));
            let accepted = request(token_path, &code_form, basic_registered);
            let issued = dispatch_oauth_h1_request(&routes, &accepted, token_path, "");
            assert_eq!(
                issued.status,
                HttpStatus::OK,
                "same code remains redeemable"
            );
            let issued: serde_json::Value = serde_json::from_slice(&issued.body).unwrap();
            let access = issued["access_token"].as_str().unwrap();
            let refresh = issued["refresh_token"].as_str().unwrap();
            let refresh_form = format!("grant_type=refresh_token&refresh_token={refresh}");
            let denied = request(token_path, &refresh_form, !basic_registered);
            assert_method_rejection(&dispatch_oauth_h1_request(&routes, &denied, token_path, ""));
            let denied = request(revoke_path, &format!("token={refresh}"), !basic_registered);
            assert_method_rejection(&dispatch_oauth_h1_request(
                &routes,
                &denied,
                revoke_path,
                "",
            ));
            assert!(routes.server().validate_access_token(access).is_some());
            let accepted = request(token_path, &refresh_form, basic_registered);
            let successor = dispatch_oauth_h1_request(&routes, &accepted, token_path, "");
            assert_eq!(
                successor.status,
                HttpStatus::OK,
                "same refresh remains usable"
            );
            let successor: serde_json::Value = serde_json::from_slice(&successor.body).unwrap();
            let access = successor["access_token"].as_str().unwrap();
            let refresh = successor["refresh_token"].as_str().unwrap();
            let accepted = request(revoke_path, &format!("token={refresh}"), basic_registered);
            assert_eq!(
                dispatch_oauth_h1_request(&routes, &accepted, revoke_path, "").status,
                HttpStatus::OK,
            );
            assert!(routes.server().validate_access_token(access).is_none());
        }
    }

    #[test]
    fn live_http_oauth_basic_authorization_code_refresh_and_revocation() {
        run_live_http_test(|cx| async move {
            let (routes, code_form, basic) = native_oauth_basic_fixture();
            let oauth = Arc::clone(routes.server());
            let bound = Server::new("live-oauth-basic", "1.0.0")
                .oauth_http_routes(routes)
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("Basic OAuth listener failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("Basic OAuth address failed: {error}"))?;
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let result = async {
                        let request = |path: &str, form: &str, authorization: &str| {
                            format!(
                                "POST {path} HTTP/1.1\r\nHost: loopback\r\nAuthorization: {authorization}\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{form}",
                                form.len(),
                            )
                            .into_bytes()
                        };
                        let wrong_basic =
                            native_oauth_basic_header("native%3Abasic%2Bclient:wrong-secret");
                        // RH-5: only the Basic password differs from the
                        // succeeding wire request; its code must survive.
                        let rejected = live_http_exchange(
                            address,
                            request("/oauth/token", &code_form, &wrong_basic),
                        )
                        .await?;
                        if !rejected.starts_with(b"HTTP/1.1 401")
                            || live_http_response_header(&rejected, "www-authenticate")?
                                != "Basic realm=\"oauth\""
                            || serde_json::from_slice::<serde_json::Value>(
                                live_http_response_body(&rejected)?,
                            )
                            .map_err(|_| "Basic rejection was not JSON".to_owned())?
                                != serde_json::json!({ "error": "invalid_client" })
                        {
                            return Err(
                                "Basic wrong-secret rejection changed its contract".to_owned(),
                            );
                        }
                        let issued = live_http_exchange(
                            address,
                            request("/oauth/token", &code_form, &basic),
                        )
                        .await?;
                        if !issued.starts_with(b"HTTP/1.1 200")
                            || live_http_response_header(&issued, "cache-control")? != "no-store"
                            || live_http_response_header(&issued, "pragma")? != "no-cache"
                        {
                            return Err(
                                "Basic authorization-code exchange did not succeed".to_owned(),
                            );
                        }
                        let issued: serde_json::Value =
                            serde_json::from_slice(live_http_response_body(&issued)?)
                                .map_err(|_| "Basic token response was not JSON".to_owned())?;
                        let access = issued["access_token"]
                            .as_str()
                            .ok_or_else(|| "Basic token response omitted access token".to_owned())?;
                        if oauth.validate_access_token(access).is_none() {
                            return Err("Basic access token is not usable".to_owned());
                        }
                        let refresh = issued["refresh_token"]
                            .as_str()
                            .ok_or_else(|| "Basic token response omitted refresh token".to_owned())?;
                        let refreshed = live_http_exchange(
                            address,
                            request(
                                "/oauth/token",
                                &format!("grant_type=refresh_token&refresh_token={refresh}"),
                                &basic,
                            ),
                        )
                        .await?;
                        if !refreshed.starts_with(b"HTTP/1.1 200") {
                            return Err("Basic refresh exchange did not succeed".to_owned());
                        }
                        let refreshed: serde_json::Value =
                            serde_json::from_slice(live_http_response_body(&refreshed)?)
                                .map_err(|_| "Basic refresh response was not JSON".to_owned())?;
                        let successor = refreshed["access_token"]
                            .as_str()
                            .ok_or_else(|| "Basic refresh omitted access token".to_owned())?;
                        if successor == access || oauth.validate_access_token(successor).is_none() {
                            return Err("Basic refresh did not issue a usable successor".to_owned());
                        }
                        let revoked = live_http_exchange(
                            address,
                            request("/oauth/revoke", &format!("token={successor}"), &basic),
                        )
                        .await?;
                        if !revoked.starts_with(b"HTTP/1.1 200")
                            || oauth.validate_access_token(successor).is_some()
                        {
                            return Err("Basic revocation did not invalidate its token".to_owned());
                        }
                        Ok(())
                    }
                    .await;
                    caller_cx.cancel_with(CancelKind::User, Some("Basic OAuth lifecycle complete"));
                    result
                })
                .map_err(|error| format!("Basic OAuth client spawn failed: {error}"))?;
            let serve = bound.serve(&cx).await;
            client
                .join(&cx)
                .await
                .map_err(|error| format!("Basic OAuth client failed: {error:?}"))??;
            let shutdown = serve.map_err(|error| format!("Basic OAuth server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "Basic OAuth lifecycle").await
        });
    }

    /// Native OAuth routes with OIDC under `base`, plus an access token for a
    /// client registered and authorized with `scopes`. A Pending signer
    /// activation is all `with_oidc` needs to fix the OIDC paths.
    #[cfg(feature = "builtin-auth-server")]
    fn native_oidc_userinfo_fixture(scopes: &[&str], base: &str) -> (OAuthHttpRoutes, String) {
        const CLIENT_ID: &str = "native-userinfo-client";
        const REDIRECT_URI: &str = "http://127.0.0.1/userinfo-callback";
        // RFC 7636 appendix B.
        const CODE_VERIFIER: &str = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
        const CODE_CHALLENGE: &str = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM";

        let oauth = Arc::new(oauth::OAuthServer::with_defaults());
        oauth
            .register_client(
                oauth::OAuthClient::builder(CLIENT_ID)
                    .redirect_uri(REDIRECT_URI)
                    .scopes(scopes.iter().copied())
                    .build()
                    .expect("valid userinfo client"),
            )
            .expect("register userinfo client");
        let (code, _) = oauth
            .authorize(&oauth::AuthorizationRequest {
                response_type: "code".to_string(),
                client_id: CLIENT_ID.to_string(),
                redirect_uri: REDIRECT_URI.to_string(),
                scopes: scopes.iter().map(|scope| (*scope).to_string()).collect(),
                resource: None,
                state: Some("userinfo-state".to_string()),
                code_challenge: CODE_CHALLENGE.to_string(),
                code_challenge_method: oauth::CodeChallengeMethod::S256,
            })
            .expect("authorize userinfo client");
        let access_token = oauth
            .token(&oauth::TokenRequest {
                grant_type: "authorization_code".to_string(),
                code: Some(code),
                redirect_uri: Some(REDIRECT_URI.to_string()),
                client_id: CLIENT_ID.to_string(),
                client_secret: None,
                client_authentication_method: oauth::TokenEndpointAuthMethod::None,
                code_verifier: Some(CODE_VERIFIER.to_string()),
                refresh_token: None,
                scopes: None,
                resource: None,
            })
            .expect("exchange userinfo access token")
            .access_token;

        let provider = native_pending_oidc_provider(&oauth, "https://fastmcp.invalid/oidc/jwks");
        let routes = OAuthHttpRoutes::new(oauth, base)
            .expect("OAuth route base")
            .with_oidc(provider)
            .expect("OIDC routes");
        (routes, access_token)
    }

    /// An OIDC provider over `oauth` whose signer activation is Pending on
    /// `jwks_uri`, which fixes the JWKS route `with_oidc` will serve.
    #[cfg(feature = "builtin-auth-server")]
    fn native_pending_oidc_provider(
        oauth: &Arc<oauth::OAuthServer>,
        jwks_uri: &str,
    ) -> Arc<oidc::OidcProvider> {
        let signer = oidc_public_canary_signer();
        let provider = Arc::new(
            oidc::OidcProvider::with_defaults(Arc::clone(oauth)).expect("default OIDC provider"),
        );
        provider
            .set_id_token_signing_activation_dependencies(
                Arc::new(LiveLoopbackOidcReadBackVerifier {
                    address: Mutex::new(None),
                    generation: signer.binding().ring_generation(),
                }) as Arc<dyn oidc::OidcJwksReadBackVerifier>,
                Arc::new(LiveOidcActivationStore::default())
                    as Arc<dyn oidc::OidcSigningActivationStore>,
            )
            .expect("OIDC activation dependencies");
        provider
            .begin_id_token_signing_activation(signer, jwks_uri)
            .expect("OIDC Pending activation");
        provider
    }

    /// The UserInfo route shares the OAuth route prefix, so a JWKS URI that
    /// lands on it would make one path answer two documents. `with_oidc` must
    /// refuse that configuration; a JWKS path beside it is accepted.
    #[cfg(feature = "builtin-auth-server")]
    #[test]
    fn native_oidc_routes_refuse_a_jwks_path_on_the_userinfo_route() {
        for (jwks_uri, accepted) in [
            ("https://fastmcp.invalid/oauth/jwks", true),
            ("https://fastmcp.invalid/oauth/userinfo", false),
        ] {
            let oauth = Arc::new(oauth::OAuthServer::with_defaults());
            let provider = native_pending_oidc_provider(&oauth, jwks_uri);
            let routes = OAuthHttpRoutes::new(oauth, "https://fastmcp.invalid/oauth")
                .expect("OAuth route base")
                .with_oidc(provider);
            if accepted {
                let routes = routes.expect("a distinct JWKS path is accepted");
                let oidc = routes.oidc_routes().expect("OIDC routes configured");
                assert_eq!(oidc.jwks_path(), "/oauth/jwks");
                assert_eq!(oidc.userinfo_path(), "/oauth/userinfo");
            } else {
                assert_eq!(
                    routes.err(),
                    Some(oauth::OAuthHttpRouteConfigurationError::InvalidPublicEndpointBase)
                );
            }
        }
    }

    #[cfg(feature = "builtin-auth-server")]
    fn native_oidc_userinfo_request(
        routes: &OAuthHttpRoutes,
        method: Http1Method,
        authorization: Option<&str>,
    ) -> HttpResponse {
        let path = routes
            .oidc_routes()
            .expect("OIDC routes configured")
            .userinfo_path()
            .to_owned();
        let request = asupersync::http::h1::Request {
            method,
            uri: path.clone(),
            version: asupersync::http::h1::Version::Http11,
            headers: authorization
                .map(|value| vec![("Authorization".to_owned(), value.to_owned())])
                .unwrap_or_default(),
            body: Vec::new(),
            trailers: Vec::new(),
            peer_addr: None,
        };
        dispatch_oauth_h1_request(routes, &request, &path, "")
    }

    /// bd-vej30: discovery advertises `userinfo_endpoint`, so a native route
    /// must serve it, under either spelling of the endpoint base.
    #[cfg(feature = "builtin-auth-server")]
    #[test]
    fn native_oidc_userinfo_serves_claims_for_an_openid_token_positive() {
        for base in [
            "https://fastmcp.invalid/oauth",
            "https://fastmcp.invalid/oauth/",
        ] {
            let (routes, access_token) = native_oidc_userinfo_fixture(&["openid"], base);
            let oidc = routes.oidc_routes().expect("OIDC routes configured");
            let discovery = oidc
                .provider()
                .discovery_document(routes.public_endpoint_base());
            assert_eq!(
                discovery.userinfo_endpoint,
                Some(format!("https://fastmcp.invalid{}", oidc.userinfo_path())),
                "{base}"
            );
            assert!(routes.has_path(oidc.userinfo_path()), "{base}");

            for method in [Http1Method::Get, Http1Method::Post] {
                let response = native_oidc_userinfo_request(
                    &routes,
                    method,
                    Some(&format!("Bearer {access_token}")),
                );
                assert_eq!(response.status, HttpStatus::OK, "{base} {response:?}");
                assert_eq!(
                    response.headers.get("cache-control").map(String::as_str),
                    Some("no-store")
                );
                let claims: serde_json::Value =
                    serde_json::from_slice(&response.body).expect("userinfo JSON");
                assert!(
                    claims["sub"].as_str().is_some_and(|sub| !sub.is_empty()),
                    "{claims}"
                );
            }
        }
    }

    #[cfg(feature = "builtin-auth-server")]
    #[test]
    fn native_oidc_userinfo_refuses_a_token_without_openid_scope_negative() {
        let (routes, access_token) =
            native_oidc_userinfo_fixture(&["mcp"], "https://fastmcp.invalid/oauth");
        let response = native_oidc_userinfo_request(
            &routes,
            Http1Method::Get,
            Some(&format!("Bearer {access_token}")),
        );
        assert_eq!(response.status, HttpStatus::FORBIDDEN, "{response:?}");
        assert_eq!(
            response.headers.get("www-authenticate").map(String::as_str),
            Some("Bearer error=\"insufficient_scope\"")
        );
        let body: serde_json::Value = serde_json::from_slice(&response.body).expect("error JSON");
        assert_eq!(body, serde_json::json!({ "error": "insufficient_scope" }));
    }

    #[cfg(feature = "builtin-auth-server")]
    #[test]
    fn native_oidc_userinfo_challenges_missing_and_unknown_bearer_tokens() {
        let (routes, _) =
            native_oidc_userinfo_fixture(&["openid"], "https://fastmcp.invalid/oauth");
        for authorization in [None, Some("Basic dXNlcjpwYXNz"), Some("Bearer")] {
            let response = native_oidc_userinfo_request(&routes, Http1Method::Get, authorization);
            assert_eq!(
                response.status,
                HttpStatus::UNAUTHORIZED,
                "{authorization:?}"
            );
            assert_eq!(
                response.headers.get("www-authenticate").map(String::as_str),
                Some("Bearer"),
                "{authorization:?}"
            );
        }
        let response = native_oidc_userinfo_request(
            &routes,
            Http1Method::Get,
            Some("Bearer forged-opaque-credential"),
        );
        assert_eq!(response.status, HttpStatus::UNAUTHORIZED);
        assert_eq!(
            response.headers.get("www-authenticate").map(String::as_str),
            Some("Bearer error=\"invalid_token\"")
        );
        let response = native_oidc_userinfo_request(&routes, Http1Method::Put, None);
        assert_eq!(response.status, HttpStatus::METHOD_NOT_ALLOWED);
    }

    #[cfg(feature = "builtin-auth-server")]
    #[test]
    fn live_http_oidc_jwks_read_back_then_discovery_activate_exact_public_bytes() {
        run_live_http_test(|cx| async move {
            use fastmcp_protocol::jose::ExternalRs256SigningDeadline;

            let oauth = Arc::new(oauth::OAuthServer::with_defaults());
            let signer = oidc_public_canary_signer();
            let expected_jwks = signer
                .canonical_public_jwks()
                .map_err(|error| format!("OIDC canonical JWKS failed: {error}"))?
                .as_bytes()
                .to_vec();
            let provider = Arc::new(
                oidc::OidcProvider::with_defaults(Arc::clone(&oauth))
                    .map_err(|error| format!("OIDC provider construction failed: {error}"))?,
            );
            let verifier = Arc::new(LiveLoopbackOidcReadBackVerifier {
                address: Mutex::new(None),
                generation: signer.binding().ring_generation(),
            });
            let store = Arc::new(LiveOidcActivationStore::default());
            provider
                .set_id_token_signing_activation_dependencies(
                    Arc::clone(&verifier) as Arc<dyn oidc::OidcJwksReadBackVerifier>,
                    Arc::clone(&store) as Arc<dyn oidc::OidcSigningActivationStore>,
                )
                .map_err(|error| format!("OIDC external dependencies failed: {error}"))?;
            provider
                .begin_id_token_signing_activation(
                    Arc::clone(&signer),
                    "https://fastmcp.invalid/oidc/jwks",
                )
                .map_err(|error| format!("OIDC Pending admission failed: {error}"))?;
            provider
                .publish_id_token_signing_jwks(
                    signer.canonical_public_jwks().map_err(|error| {
                        format!("OIDC JWKS publication generation failed: {error}")
                    })?,
                )
                .map_err(|error| format!("OIDC canonical JWKS publication failed: {error}"))?;
            let routes = OAuthHttpRoutes::new(Arc::clone(&oauth), "https://fastmcp.invalid/oauth")
                .map_err(|error| format!("OIDC OAuth route base failed: {error}"))?
                .with_oidc(Arc::clone(&provider))
                .map_err(|error| format!("OIDC public route configuration failed: {error}"))?;
            let bound = Server::new("live-oidc-jwks", "1.0.0")
                .oauth_http_routes(routes)
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("OIDC public HTTP bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("OIDC public HTTP address failed: {error}"))?;
            verifier.set_address(address);
            let provider_for_client = Arc::clone(&provider);
            let caller_cx = cx.clone();
            let expected_for_client = expected_jwks.clone();
            let mut client = cx
                .spawn(move |client_cx| async move {
                    let jwks = live_http_exchange(
                        address,
                        b"GET /oidc/jwks HTTP/1.1\r\nHost: loopback\r\nConnection: close\r\n\r\n"
                            .to_vec(),
                    )
                    .await?;
                    if !jwks.starts_with(b"HTTP/1.1 200")
                        || live_http_response_body(&jwks)? != expected_for_client.as_slice()
                    {
                        return Err(format!(
                            "OIDC public JWKS did not return exact canonical bytes: {}",
                            String::from_utf8_lossy(&jwks)
                        ));
                    }
                    let deadline = ExternalRs256SigningDeadline::new(Duration::from_secs(1))
                        .map_err(|error| format!("OIDC canary deadline invalid: {error}"))?;
                    provider_for_client
                        .activate_id_token_signing(&client_cx, deadline)
                        .await
                        .map_err(|error| format!("OIDC active admission failed: {error}"))?;
                    let discovery = live_http_exchange(
                        address,
                        b"GET /.well-known/openid-configuration HTTP/1.1\r\nHost: loopback\r\nConnection: close\r\n\r\n"
                            .to_vec(),
                    )
                    .await?;
                    caller_cx.cancel_with(CancelKind::User, Some("live OIDC publication complete"));
                    Ok::<_, String>(discovery)
                })
                .map_err(|error| format!("OIDC public client admission failed: {error}"))?;

            let serve = bound.serve(&cx).await;
            let discovery = client
                .join(&cx)
                .await
                .map_err(|error| format!("OIDC public client failed: {error:?}"))??;
            let shutdown = serve.map_err(|error| format!("OIDC public server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "live OIDC public JWKS").await?;
            if !discovery.starts_with(b"HTTP/1.1 200") {
                return Err(format!(
                    "OIDC discovery did not become publicly reachable: {}",
                    String::from_utf8_lossy(&discovery)
                ));
            }
            let discovery: serde_json::Value =
                serde_json::from_slice(live_http_response_body(&discovery)?)
                    .map_err(|error| format!("OIDC discovery was not JSON: {error}"))?;
            if discovery["issuer"] != "https://fastmcp.invalid/"
                || discovery["jwks_uri"] != "https://fastmcp.invalid/oidc/jwks"
            {
                return Err(format!(
                    "OIDC discovery mismatched active publication: {discovery}"
                ));
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_oauth_pkce_authorize_then_token_is_publicly_reachable() {
        run_live_http_test(|cx| async move {
            let oauth = Arc::new(oauth::OAuthServer::with_defaults());
            oauth
                .register_client(
                    oauth::OAuthClient::builder("live-pkce-client")
                        .redirect_uri("https://client.example.test/callback")
                        .scope("mcp")
                        .build()
                        .map_err(|error| {
                            format!("live OAuth client registration failed: {error}")
                        })?,
                )
                .map_err(|error| format!("live OAuth client retention failed: {error}"))?;
            let routes = OAuthHttpRoutes::new(Arc::clone(&oauth), "https://fastmcp.invalid/oauth")
                .map_err(|error| format!("live OAuth HTTP routes were invalid: {error}"))?;
            let bound = Server::new("live-oauth-pkce", "1.0.0")
                .oauth_http_routes(routes)
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("live OAuth HTTP bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("live OAuth HTTP address failed: {error}"))?;
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let denied = "GET /oauth/authorize?response_type=code&client_id=live-pkce-client&redirect_uri=https%3A%2F%2Fclient.example.test%2Fcallback&scope=denied&state=opaque-state&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&code_challenge_method=S256 HTTP/1.1\r\nHost: loopback\r\nConnection: close\r\n\r\n".to_owned();
                    // RH-5: this differs from the successful request only in
                    // its requested scope. A valid redirect must carry the
                    // OAuth error and the original opaque state.
                    let denied = live_http_exchange(address, denied.into_bytes()).await?;
                    let authorize = "GET /oauth/authorize?response_type=code&client_id=live-pkce-client&redirect_uri=https%3A%2F%2Fclient.example.test%2Fcallback&scope=mcp&state=opaque-state&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&code_challenge_method=S256 HTTP/1.1\r\nHost: loopback\r\nConnection: close\r\n\r\n".to_owned();
                    let authorize = live_http_exchange(address, authorize.into_bytes()).await?;
                    let location = live_http_response_header(&authorize, "location")?;
                    let redirect = url::Url::parse(&location)
                        .map_err(|error| format!("OAuth authorization Location was invalid: {error}"))?;
                    let code = redirect
                        .query_pairs()
                        .find_map(|(name, value)| (name == "code").then(|| value.into_owned()))
                        .ok_or_else(|| "OAuth authorization Location omitted code".to_owned())?;
                    if redirect
                        .query_pairs()
                        .find_map(|(name, value)| (name == "state").then(|| value.into_owned()))
                        .as_deref()
                        != Some("opaque-state")
                    {
                        return Err("OAuth authorization Location changed state".to_owned());
                    }
                    let form = format!(
                        "grant_type=authorization_code&code={}&redirect_uri=https%3A%2F%2Fclient.example.test%2Fcallback&client_id=live-pkce-client&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk",
                        url::form_urlencoded::byte_serialize(code.as_bytes()).collect::<String>(),
                    );
                    let token = format!(
                        "POST /oauth/token HTTP/1.1\r\nHost: loopback\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                        form.len(), form,
                    );
                    let token = live_http_exchange(address, token.into_bytes()).await?;
                    caller_cx.cancel_with(CancelKind::User, Some("live OAuth PKCE complete"));
                    Ok::<_, String>((denied, authorize, token))
                })
                .map_err(|error| format!("live OAuth client admission failed: {error}"))?;

            let serve = bound.serve(&cx).await;
            let (denied, authorize, token) = client
                .join(&cx)
                .await
                .map_err(|error| format!("live OAuth client failed: {error:?}"))??;
            let shutdown = serve.map_err(|error| format!("live OAuth server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "live OAuth PKCE").await?;
            if !authorize.starts_with(b"HTTP/1.1 303") {
                return Err(format!(
                    "OAuth authorization did not redirect: {}",
                    String::from_utf8_lossy(&authorize)
                ));
            }
            if !denied.starts_with(b"HTTP/1.1 303") {
                return Err(format!(
                    "valid OAuth error did not redirect: {}",
                    String::from_utf8_lossy(&denied)
                ));
            }
            let denied_location = live_http_response_header(&denied, "location")?;
            let denied_redirect = url::Url::parse(&denied_location)
                .map_err(|error| format!("OAuth error Location was invalid: {error}"))?;
            if denied_redirect
                .query_pairs()
                .find_map(|(name, value)| (name == "error").then(|| value.into_owned()))
                .as_deref()
                != Some("invalid_scope")
                || denied_redirect
                    .query_pairs()
                    .find_map(|(name, value)| (name == "state").then(|| value.into_owned()))
                    .as_deref()
                    != Some("opaque-state")
                || denied_redirect
                    .query_pairs()
                    .find_map(|(name, value)| (name == "iss").then(|| value.into_owned()))
                    .as_deref()
                    != Some("https://fastmcp.invalid/")
                || denied_redirect
                    .query_pairs()
                    .any(|(name, _)| name == "code")
            {
                return Err(format!(
                    "OAuth error redirect did not preserve the safe client response: {denied_location}"
                ));
            }
            if !token.starts_with(b"HTTP/1.1 200")
                || live_http_response_header(&token, "cache-control")? != "no-store"
            {
                return Err(format!(
                    "OAuth token response was not a no-store success: {}",
                    String::from_utf8_lossy(&token)
                ));
            }
            let token: serde_json::Value = serde_json::from_slice(live_http_response_body(&token)?)
                .map_err(|error| format!("OAuth token response was not JSON: {error}"))?;
            if token["token_type"] != "bearer"
                || token["access_token"].as_str().is_none_or(str::is_empty)
            {
                return Err(format!("OAuth token response was incomplete: {token}"));
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_oauth_redirect_uri_mismatch_preserves_authorization_code() {
        run_live_http_test(|cx| async move {
            let oauth = Arc::new(oauth::OAuthServer::with_defaults());
            oauth
                .register_client(
                    oauth::OAuthClient::builder("live-redirect-client")
                        .secret("correct-secret")
                        .token_endpoint_auth_method(
                            oauth::TokenEndpointAuthMethod::ClientSecretPost,
                        )
                        .redirect_uri("https://client.example.test/callback")
                        .scope("mcp")
                        .build()
                        .map_err(|error| {
                            format!("live redirect client registration failed: {error}")
                        })?,
                )
                .map_err(|error| format!("live redirect client retention failed: {error}"))?;
            let routes = OAuthHttpRoutes::new(Arc::clone(&oauth), "https://fastmcp.invalid/oauth")
                .map_err(|error| format!("live redirect OAuth routes were invalid: {error}"))?;
            let bound = Server::new("live-oauth-redirect-retry", "1.0.0")
                .oauth_http_routes(routes)
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("live redirect OAuth HTTP bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("live redirect OAuth HTTP address failed: {error}"))?;
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let authorize = "GET /oauth/authorize?response_type=code&client_id=live-redirect-client&redirect_uri=https%3A%2F%2Fclient.example.test%2Fcallback&scope=mcp&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&code_challenge_method=S256 HTTP/1.1\r\nHost: loopback\r\nConnection: close\r\n\r\n".to_owned();
                    let authorize = live_http_exchange(address, authorize.into_bytes()).await?;
                    let location = live_http_response_header(&authorize, "location")?;
                    let redirect = url::Url::parse(&location)
                        .map_err(|error| format!("OAuth redirect Location was invalid: {error}"))?;
                    let code = redirect
                        .query_pairs()
                        .find_map(|(name, value)| (name == "code").then(|| value.into_owned()))
                        .ok_or_else(|| "OAuth redirect Location omitted code".to_owned())?;
                    let encoded_code = url::form_urlencoded::byte_serialize(code.as_bytes())
                        .collect::<String>();
                    let original = format!(
                        "grant_type=authorization_code&code={encoded_code}&redirect_uri=https%3A%2F%2Fclient.example.test%2Fcallback&client_id=live-redirect-client&client_secret=correct-secret&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
                    );
                    // RH-5: this form differs from `original` only at redirect_uri.
                    let mismatch = original.replace(
                        "redirect_uri=https%3A%2F%2Fclient.example.test%2Fcallback",
                        "redirect_uri=https%3A%2F%2Fclient.example.test%2Fother",
                    );
                    // RH-5: this form differs from `original` only at the
                    // confidential client credential. Its rejection must not
                    // consume the authorization code.
                    let wrong_secret = original.replace(
                        "client_secret=correct-secret",
                        "client_secret=wrong-secret",
                    );
                    let request = |path: &str, form: &str, authorization: Option<&str>| {
                        format!(
                            "POST {path} HTTP/1.1\r\nHost: loopback\r\nContent-Type: application/x-www-form-urlencoded\r\n{}Content-Length: {}\r\nConnection: close\r\n\r\n{}",
                            authorization.map_or_else(String::new, |value| format!("Authorization: {value}\r\n")),
                            form.len(),
                            form,
                        )
                        .into_bytes()
                    };
                    let rejected =
                        live_http_exchange(address, request("/oauth/token", &mismatch, None)).await?;
                    let wrong_secret_rejected = live_http_exchange(
                        address,
                        request("/oauth/token", &wrong_secret, None),
                    )
                    .await?;
                    // RH-5: compared with the eventual successful redemption,
                    // this adds a second client-credential location.
                    let header_rejected = live_http_exchange(
                        address,
                        request("/oauth/token", &original, Some("Basic ZmFzdG1jcDppbnZhbGlk")),
                    )
                    .await?;
                    // RH-5: this differs from `original` only in its
                    // unsupported Bearer Authorization header. It must not
                    // be converted into a Basic challenge or consume `code`.
                    let bearer_rejected = live_http_exchange(
                        address,
                        request("/oauth/token", &original, Some("Bearer unsupported-token")),
                    )
                    .await?;
                    let revocation =
                        "token=not-a-token&client_id=live-redirect-client&client_secret=wrong-secret";
                    let revoke_wrong_secret = live_http_exchange(
                        address,
                        request("/oauth/revoke", revocation, None),
                    )
                    .await?;
                    // A declared over-limit OAuth form must be rejected from
                    // its head alone; no body bytes follow this request.
                    let over_limit = format!(
                        "POST /oauth/token HTTP/1.1\r\nHost: loopback\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                        oauth::MAX_OAUTH_FORM_BODY_BYTES + 1,
                    )
                    .into_bytes();
                    let over_limit = live_http_exchange(address, over_limit).await?;
                    let retried =
                        live_http_exchange(address, request("/oauth/token", &original, None)).await?;
                    let access_token = serde_json::from_slice::<serde_json::Value>(
                        live_http_response_body(&retried)?,
                    )
                    .map_err(|error| {
                        format!("successful retry token response was not JSON: {error}")
                    })?["access_token"]
                        .as_str()
                        .filter(|token| !token.is_empty())
                        .ok_or_else(|| {
                            "successful retry token response omitted access_token".to_owned()
                        })?
                        .to_owned();
                    let bearer_revocation_form = format!(
                        "token={}&client_id=live-redirect-client&client_secret=correct-secret",
                        url::form_urlencoded::byte_serialize(access_token.as_bytes())
                            .collect::<String>(),
                    );
                    // RH-5: this differs only by an unsupported Bearer
                    // Authorization header from the form that would revoke
                    // the freshly issued access token.
                    let bearer_revoke_rejected = live_http_exchange(
                        address,
                        request(
                            "/oauth/revoke",
                            &bearer_revocation_form,
                            Some("Bearer unsupported-token"),
                        ),
                    )
                    .await?;
                    caller_cx.cancel_with(CancelKind::User, Some("live OAuth redirect retry complete"));
                    Ok::<_, String>((
                        rejected,
                        wrong_secret_rejected,
                        header_rejected,
                        bearer_rejected,
                        revoke_wrong_secret,
                        over_limit,
                        retried,
                        bearer_revoke_rejected,
                        access_token,
                    ))
                })
                .map_err(|error| format!("live redirect OAuth client admission failed: {error}"))?;

            let serve = bound.serve(&cx).await;
            let (
                rejected,
                wrong_secret_rejected,
                header_rejected,
                bearer_rejected,
                revoke_wrong_secret,
                over_limit,
                retried,
                bearer_revoke_rejected,
                access_token,
            ) = client
                .join(&cx)
                .await
                .map_err(|error| format!("live redirect OAuth client failed: {error:?}"))??;
            let shutdown =
                serve.map_err(|error| format!("live redirect OAuth server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "live OAuth redirect retry").await?;
            if !rejected.starts_with(b"HTTP/1.1 400")
                || serde_json::from_slice::<serde_json::Value>(live_http_response_body(&rejected)?)
                    .ok()
                    .and_then(|body| body["error"].as_str().map(str::to_owned))
                    .as_deref()
                    != Some("invalid_grant")
            {
                return Err(format!(
                    "redirect-only mismatch was not an invalid_grant rejection: {}",
                    String::from_utf8_lossy(&rejected)
                ));
            }
            if !retried.starts_with(b"HTTP/1.1 200") {
                return Err(format!(
                    "a rejected token request consumed the authorization code: {}",
                    String::from_utf8_lossy(&retried)
                ));
            }
            for (endpoint, response) in [
                ("token form", &wrong_secret_rejected),
                ("revocation form", &revoke_wrong_secret),
            ] {
                if !response.starts_with(b"HTTP/1.1 400")
                    || live_http_response_has_header(response, "www-authenticate")?
                    || serde_json::from_slice::<serde_json::Value>(live_http_response_body(
                        response,
                    )?)
                    .ok()
                    .and_then(|body| body["error"].as_str().map(str::to_owned))
                    .as_deref()
                        != Some("invalid_client")
                {
                    return Err(format!(
                        "{endpoint} wrong-secret rejection was not an unchallenged invalid_client 400: {}",
                        String::from_utf8_lossy(response)
                    ));
                }
            }
            if !header_rejected.starts_with(b"HTTP/1.1 400")
                || live_http_response_has_header(&header_rejected, "www-authenticate")?
                || serde_json::from_slice::<serde_json::Value>(live_http_response_body(
                    &header_rejected,
                )?)
                .ok()
                .and_then(|body| body["error"].as_str().map(str::to_owned))
                .as_deref()
                    != Some("invalid_request")
            {
                return Err(format!(
                    "mixed client credentials were not an unchallenged invalid_request 400: {}",
                    String::from_utf8_lossy(&header_rejected)
                ));
            }
            for (endpoint, response) in [
                ("token Bearer", &bearer_rejected),
                ("revocation Bearer", &bearer_revoke_rejected),
            ] {
                if !response.starts_with(b"HTTP/1.1 400")
                    || live_http_response_has_header(response, "www-authenticate")?
                    || serde_json::from_slice::<serde_json::Value>(live_http_response_body(
                        response,
                    )?)
                    .ok()
                    .and_then(|body| body["error"].as_str().map(str::to_owned))
                    .as_deref()
                        != Some("invalid_request")
                {
                    return Err(format!(
                        "{endpoint} rejection was not an unchallenged invalid_request: {}",
                        String::from_utf8_lossy(response)
                    ));
                }
            }
            if oauth.validate_access_token(&access_token).is_none() {
                return Err(
                    "Bearer rejection on /oauth/revoke changed the issued access-token state"
                        .to_owned(),
                );
            }
            if !over_limit.starts_with(b"HTTP/1.1 400") {
                return Err(format!(
                    "over-limit OAuth form was not rejected from its head: {}",
                    String::from_utf8_lossy(&over_limit)
                ));
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_strict_admission_dispatches_a_canonical_modern_post() {
        run_live_http_test(|cx| async move {
            let response = live_http_strict_admission_exchange(&cx, SERVER_DISCOVER_METHOD).await?;
            if !response.starts_with(b"HTTP/1.1 200") {
                return Err(format!(
                    "canonical strict-admission POST used an unexpected response: {}",
                    String::from_utf8_lossy(&response)
                ));
            }
            let response: JsonRpcResponse =
                serde_json::from_slice(live_http_response_body(&response)?).map_err(|error| {
                    format!("canonical strict-admission response was invalid: {error}")
                })?;
            if response.id != Some(803_i64.into()) || response.error.is_some() {
                return Err(format!(
                    "canonical strict-admission POST was not dispatched: {response:?}"
                ));
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_strict_admission_rejects_only_a_mismatched_method_mirror() {
        run_live_http_test(|cx| async move {
            // This is the canonical live POST above with only its Mcp-Method
            // header changed; the JSON body still names server/discover.
            let response =
                live_http_strict_admission_exchange(&cx, "server/discover-mismatch").await?;
            if !response.starts_with(b"HTTP/1.1 400") {
                return Err(format!(
                    "mismatched strict-admission mirror used an unexpected response: {}",
                    String::from_utf8_lossy(&response)
                ));
            }
            let response: JsonRpcResponse =
                serde_json::from_slice(live_http_response_body(&response)?).map_err(|error| {
                    format!("strict-admission rejection was not valid JSON-RPC: {error}")
                })?;
            if response.id != Some(803_i64.into())
                || response.result.is_some()
                || response
                    .error
                    .as_ref()
                    .and_then(|error| error.code.as_i32())
                    != Some(fastmcp_protocol::HEADER_MISMATCH_ERROR_CODE)
                || response
                    .error
                    .as_ref()
                    .and_then(|error| error.data.as_ref())
                    .is_some()
            {
                return Err(format!(
                    "strict-admission mirror did not retain its canonical pre-dispatch error: {response:?}"
                ));
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_listener_merges_repeated_accept_but_rejects_a_duplicate_singleton() {
        run_live_http_test(|cx| async move {
            let bound = Server::new("live-http-repeated-admission", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("repeated admission HTTP bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("repeated admission HTTP address failed: {error}"))?;
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    struct CancelServerOnDrop(Cx);

                    impl Drop for CancelServerOnDrop {
                        fn drop(&mut self) {
                            self.0.cancel_with(
                                CancelKind::User,
                                Some("repeated admission client exited"),
                            );
                        }
                    }

                    let _server_cancellation = CancelServerOnDrop(caller_cx);
                    let request = JsonRpcRequest::new(
                        SERVER_DISCOVER_METHOD,
                        Some(serde_json::json!({
                            "_meta": {
                                MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                                FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                            },
                        })),
                        803_i64,
                    );
                    let body = serde_json::to_vec(&request).map_err(|error| {
                        format!("repeated admission request did not serialize: {error}")
                    })?;
                    let later_member_required = live_http_exchange(
                        address,
                        live_http_post(
                            "/mcp",
                            &body,
                            &[
                                ("Accept", "text/plain"),
                                ("Accept", "application/json"),
                                ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                ("Mcp-Method", SERVER_DISCOVER_METHOD),
                            ],
                        ),
                    )
                    .await?;
                    let accepted = live_http_exchange(
                        address,
                        live_http_post(
                            "/mcp",
                            &body,
                            &[
                                ("Accept", "application/json"),
                                ("Accept", "text/event-stream; q=0"),
                                ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                ("Mcp-Method", SERVER_DISCOVER_METHOD),
                            ],
                        ),
                    )
                    .await?;
                    let rejected = live_http_exchange(
                        address,
                        live_http_post(
                            "/mcp",
                            &body,
                            &[
                                ("Accept", "application/json"),
                                ("Accept", "text/event-stream; q=0"),
                                ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                ("Mcp-Method", SERVER_DISCOVER_METHOD),
                                ("Mcp-Method", SERVER_DISCOVER_METHOD),
                            ],
                        ),
                    )
                    .await?;
                    Ok::<_, String>((later_member_required, accepted, rejected))
                })
                .map_err(|error| format!("repeated admission client was not admitted: {error}"))?;

            let serve = bound.serve(&cx).await;
            let (later_member_required, accepted, rejected) = client
                .join(&cx)
                .await
                .map_err(|error| format!("repeated admission client failed: {error:?}"))??;
            let shutdown =
                serve.map_err(|error| format!("repeated admission server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "repeated admission").await?;

            if !later_member_required.starts_with(b"HTTP/1.1 200") {
                return Err(format!(
                    "a later valid repeated Accept member was not retained: {}",
                    String::from_utf8_lossy(&later_member_required)
                ));
            }
            if !accepted.starts_with(b"HTTP/1.1 200") {
                return Err(format!(
                    "wire-ordered repeated Accept fields used an unexpected response: {}",
                    String::from_utf8_lossy(&accepted)
                ));
            }
            if !rejected.starts_with(b"HTTP/1.1 400") {
                return Err(format!(
                    "changing only the repeated header name to a singleton used an unexpected response: {}",
                    String::from_utf8_lossy(&rejected)
                ));
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_modern_sse_post_dispatches_without_discovery_or_session_id() {
        run_live_http_test(|cx| async move {
            let calls = Arc::new(AtomicUsize::new(0));
            let bound = Server::new("live-http-stateless-sse", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .auth_provider(auth_00_mrtr_provider(true))
                .tool(LiveHttpMrtrTool {
                    name: "live_http_mrtr",
                    calls: Arc::clone(&calls),
                })
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("live HTTP MRTR bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("live HTTP MRTR address failed: {error}"))?;
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let initial = JsonRpcRequest::new(
                        "tools/call",
                        Some(serde_json::json!({
                            "name": "live_http_mrtr",
                            "arguments": {},
                            "_meta": {
                                MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                                FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                                "progressToken": "live-http-mrtr-sse",
                            },
                        })),
                        922_i64,
                    );
                    let initial_body = serde_json::to_vec(&initial).map_err(|error| {
                        format!("MRTR initial request did not serialize: {error}")
                    })?;
                    let initial = live_http_exchange(
                        address,
                        live_http_post(
                            "/mcp",
                            &initial_body,
                            &[
                                ("Accept", "text/event-stream"),
                                ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                ("Mcp-Method", "tools/call"),
                                ("Mcp-Name", "live_http_mrtr"),
                                ("Authorization", "Bearer alpha"),
                            ],
                        ),
                    )
                    .await?;
                    caller_cx.cancel_with(
                        CancelKind::User,
                        Some("live HTTP stateless SSE request complete"),
                    );
                    Ok::<_, String>(initial)
                })
                .map_err(|error| format!("live HTTP MRTR client admission failed: {error}"))?;

            let serve = bound.serve(&cx).await;
            let response = client
                .join(&cx)
                .await
                .map_err(|error| format!("live HTTP MRTR client failed: {error:?}"))??;
            let shutdown =
                serve.map_err(|error| format!("live HTTP MRTR server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "live HTTP MRTR").await?;
            let response = live_http_sse_jsonrpc_response(&response)?;
            if response.id != Some(922_i64.into())
                || response.error.is_some()
                || response
                    .result
                    .as_ref()
                    .and_then(|result| result.get("resultType"))
                    != Some(&serde_json::json!("input_required"))
            {
                return Err(format!(
                    "sessionless modern SSE POST did not dispatch: {response:?}"
                ));
            }
            if calls.load(Ordering::Acquire) != 1 {
                return Err(
                    "sessionless modern SSE POST did not invoke the handler once".to_owned(),
                );
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_modern_authorization_allows_native_bearer_once() {
        run_live_http_test(|cx| async move {
            let calls = Arc::new(AtomicUsize::new(0));
            let bound = Server::new("live-http-modern-authorization", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .auth_provider(ModernHttpAuthProvider)
                .tool(ModernHttpAuthCounterTool {
                    calls: Arc::clone(&calls),
                })
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("live HTTP authorization bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("live HTTP authorization address failed: {error}"))?;
            let request = modern_http_json_tool_request("modern_http_auth_counter", 935);
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let response = live_http_exchange(
                        address,
                        live_http_post(
                            "/mcp",
                            &request.body,
                            &[
                                ("Accept", "application/json"),
                                ("Authorization", "Bearer alpha"),
                                ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                ("Mcp-Method", "tools/call"),
                                ("Mcp-Name", "modern_http_auth_counter"),
                            ],
                        ),
                    )
                    .await;
                    caller_cx.cancel_with(
                        CancelKind::User,
                        Some("live HTTP native bearer proof complete"),
                    );
                    response
                })
                .map_err(|error| {
                    format!("live HTTP authorization client admission failed: {error}")
                })?;
            let serve = bound.serve(&cx).await;
            let response = client
                .join(&cx)
                .await
                .map_err(|error| format!("live HTTP authorization client failed: {error:?}"))??;
            let shutdown =
                serve.map_err(|error| format!("live HTTP authorization server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "live HTTP native bearer").await?;
            let response: JsonRpcResponse =
                serde_json::from_slice(live_http_response_body(&response)?).map_err(|error| {
                    format!("live HTTP authorization response was not JSON-RPC: {error}")
                })?;
            if response.id != Some(935_i64.into()) || response.error.is_some() {
                return Err(format!(
                    "allowed native bearer did not dispatch: {response:?}"
                ));
            }
            if calls.load(Ordering::Acquire) != 1 {
                return Err(
                    "allowed native bearer did not invoke the handler exactly once".to_owned(),
                );
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_native_authorization_rejects_before_owned_state_and_strips_valid_bearer() {
        run_live_http_test(|cx| async move {
            let handler_calls = Arc::new(AtomicUsize::new(0));
            let middleware_calls = Arc::new(AtomicUsize::new(0));
            let saw_credential = Arc::new(AtomicBool::new(false));
            let bound = Server::new("live-http-native-auth-admission", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .auth_provider(ModernHttpAuthProvider)
                .middleware(ModernHttpAuthMiddleware {
                    calls: Arc::clone(&middleware_calls),
                    saw_credential: Arc::clone(&saw_credential),
                })
                .tool(ModernHttpAuthCounterTool {
                    calls: Arc::clone(&handler_calls),
                })
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("native auth admission bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("native auth admission address failed: {error}"))?;
            let request = modern_http_json_tool_request("modern_http_auth_counter", 936);
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let common = [
                        ("Accept", "application/json"),
                        ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                        ("Mcp-Method", "tools/call"),
                        ("Mcp-Name", "modern_http_auth_counter"),
                    ];
                    let result = async {
                        let missing = live_http_exchange(
                            address,
                            live_http_post("/mcp", &request.body, &common),
                        )
                        .await?;
                        let invalid = live_http_exchange(
                            address,
                            live_http_post(
                                "/mcp",
                                &request.body,
                                &[
                                    ("Authorization", "Bearer invalid-never-echo"),
                                    ("Accept", "application/json"),
                                    ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                    ("Mcp-Method", "tools/call"),
                                    ("Mcp-Name", "modern_http_auth_counter"),
                                ],
                            ),
                        )
                        .await?;
                        let malformed = live_http_exchange(
                            address,
                            live_http_post(
                                "/mcp",
                                &request.body,
                                &[
                                    ("Authorization", "Bearer"),
                                    ("Accept", "application/json"),
                                    ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                    ("Mcp-Method", "tools/call"),
                                    ("Mcp-Name", "modern_http_auth_counter"),
                                ],
                            ),
                        )
                        .await?;
                        let duplicate = live_http_exchange(
                            address,
                            live_http_post(
                                "/mcp",
                                &request.body,
                                &[
                                    ("Authorization", "Bearer alpha"),
                                    ("aUtHoRiZaTiOn", "Bearer beta"),
                                    ("Accept", "application/json"),
                                    ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                    ("Mcp-Method", "tools/call"),
                                    ("Mcp-Name", "modern_http_auth_counter"),
                                ],
                            ),
                        )
                        .await?;
                        let accepted = live_http_exchange(
                            address,
                            live_http_post(
                                "/mcp",
                                &request.body,
                                &[
                                    ("Authorization", "Bearer alpha"),
                                    ("Accept", "application/json"),
                                    ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                    ("Mcp-Method", "tools/call"),
                                    ("Mcp-Name", "modern_http_auth_counter"),
                                ],
                            ),
                        )
                        .await?;
                        Ok::<_, String>((missing, invalid, malformed, duplicate, accepted))
                    }
                    .await;
                    caller_cx.cancel_with(
                        CancelKind::User,
                        Some("native HTTP authorization admission proof complete"),
                    );
                    result
                })
                .map_err(|error| {
                    format!("native auth admission client admission failed: {error}")
                })?;
            let serve = bound.serve(&cx).await;
            let (missing, invalid, malformed, duplicate, accepted) = client
                .join(&cx)
                .await
                .map_err(|error| format!("native auth admission client failed: {error:?}"))??;
            let shutdown =
                serve.map_err(|error| format!("native auth admission server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "native HTTP authorization admission")
                .await?;
            for (label, response) in [
                ("missing", missing),
                ("invalid", invalid),
                ("malformed", malformed),
                ("duplicate", duplicate),
            ] {
                if !response.starts_with(b"HTTP/1.1 401")
                    || live_http_response_header(&response, "www-authenticate")? != "Bearer"
                    || std::str::from_utf8(&response)
                        .map_err(|error| format!("{label} auth response was not UTF-8: {error}"))?
                        .contains("invalid-never-echo")
                {
                    return Err(format!(
                        "{label} native Authorization was not a bounded pre-dispatch 401"
                    ));
                }
            }
            let accepted: JsonRpcResponse =
                serde_json::from_slice(live_http_response_body(&accepted)?).map_err(|error| {
                    format!("valid native Authorization did not return JSON-RPC: {error}")
                })?;
            if accepted.error.is_some()
                || handler_calls.load(Ordering::Acquire) != 1
                || middleware_calls.load(Ordering::Acquire) != 1
                || saw_credential.load(Ordering::Acquire)
            {
                return Err(
                    "native Authorization admission mutated owned state or leaked bearer"
                        .to_owned(),
                );
            }
            Ok(())
        });
    }

    #[derive(Clone)]
    struct HttpHeaderAuthProbe {
        provider: Arc<auth::TokenAuthProvider>,
        provider_calls: Arc<AtomicUsize>,
        middleware_calls: Arc<AtomicUsize>,
        handler_calls: Arc<AtomicUsize>,
        token: String,
        subject: String,
    }

    impl HttpHeaderAuthProbe {
        fn new() -> Self {
            let nonce = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("test clock must follow the Unix epoch")
                .as_nanos();
            let token = format!("auth01-{}-{nonce}", std::process::id());
            let subject = format!("http-principal-{nonce}");
            let verifier = auth::StaticTokenVerifier::new([(
                token.clone(),
                AuthContext::with_subject(subject.clone()),
            )])
            .expect("runtime-selected static credential must be admissible");
            Self {
                provider: Arc::new(auth::TokenAuthProvider::new(verifier)),
                provider_calls: Arc::new(AtomicUsize::new(0)),
                middleware_calls: Arc::new(AtomicUsize::new(0)),
                handler_calls: Arc::new(AtomicUsize::new(0)),
                token,
                subject,
            }
        }

        fn effects(&self) -> (usize, usize, usize) {
            (
                self.provider_calls.load(Ordering::Acquire),
                self.middleware_calls.load(Ordering::Acquire),
                self.handler_calls.load(Ordering::Acquire),
            )
        }
    }

    impl AuthProvider for HttpHeaderAuthProbe {
        fn authenticate(
            &self,
            ctx: &McpContext,
            request: AuthRequest<'_>,
        ) -> McpResult<AuthContext> {
            self.provider_calls.fetch_add(1, Ordering::AcqRel);
            self.provider.authenticate(ctx, request)
        }
    }

    impl Middleware for HttpHeaderAuthProbe {
        fn on_request(
            &self,
            ctx: &McpContext,
            request: &JsonRpcRequest,
        ) -> McpResult<MiddlewareDecision> {
            self.middleware_calls.fetch_add(1, Ordering::AcqRel);
            let serialized = serde_json::to_string(request)
                .map_err(|error| McpError::internal_error(error.to_string()))?;
            if serialized.contains(&self.token)
                || ctx.auth().and_then(|auth| auth.subject).as_deref() != Some(&self.subject)
            {
                return Err(McpError::internal_error(
                    "HTTP credential custody or principal changed",
                ));
            }
            Ok(MiddlewareDecision::Continue)
        }
    }

    impl ToolHandler for HttpHeaderAuthProbe {
        fn definition(&self) -> Tool {
            Tool {
                name: "http_header_auth_probe".to_owned(),
                description: None,
                input_schema: serde_json::json!({"type": "object"}),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(&self, ctx: &McpContext, arguments: serde_json::Value) -> McpResult<Vec<Content>> {
            self.handler_calls.fetch_add(1, Ordering::AcqRel);
            if arguments
                != serde_json::json!({"token": "application-data", "access_token": "application-data"})
            {
                return Err(McpError::internal_error(
                    "application arguments changed during authentication",
                ));
            }
            Ok(vec![Content::text(
                ctx.auth().and_then(|auth| auth.subject).unwrap_or_default(),
            )])
        }
    }

    fn require_http_credential_location_rejection(
        response: &[u8],
        token: &str,
    ) -> Result<(), String> {
        if !response.starts_with(b"HTTP/1.1 401")
            || live_http_response_header(response, "www-authenticate")? != "Bearer"
            || response
                .windows(token.len())
                .any(|window| window == token.as_bytes())
        {
            return Err("credential location did not produce a secret-free HTTP 401".to_owned());
        }
        let body: serde_json::Value = serde_json::from_slice(live_http_response_body(response)?)
            .map_err(|error| error.to_string())?;
        if body
            != serde_json::json!({
                "error": "invalid_request",
                "message": "HTTP credentials must use the Authorization header",
            })
        {
            return Err(
                "credential location rejection lost its fixed migration message".to_owned(),
            );
        }
        Ok(())
    }

    #[cfg(feature = "tasks")]
    struct AuthTaskSupervisor;

    #[cfg(feature = "tasks")]
    impl ApplicationTaskSupervisor for AuthTaskSupervisor {
        fn resume<'a>(
            &'a self,
            _cx: &'a Cx,
            handoff: FinalTaskSupervisorHandoff,
        ) -> FinalTaskSupervisorFuture<'a> {
            Box::pin(async move {
                match handoff {
                    FinalTaskSupervisorHandoff::Initial(initial) => {
                        initial.require_input(
                            serde_json::from_value(
                                serde_json::json!({"roots": {"method": "roots/list"}}),
                            )
                            .unwrap(),
                            None,
                        )?;
                    }
                    FinalTaskSupervisorHandoff::Resumed(accepted) => {
                        accepted.complete_task(serde_json::from_value(serde_json::json!({"content": [{"type": "text", "text": "owner input consumed"}]})).unwrap(), None)?;
                    }
                }
                Ok(())
            })
        }
    }

    #[cfg(feature = "tasks")]
    fn auth_task_http_frame(request: &JsonRpcRequest, authorization: &str) -> Vec<u8> {
        let mut headers = vec![
            (
                "Accept",
                if request.method == SUBSCRIPTIONS_LISTEN {
                    "text/event-stream"
                } else {
                    "application/json"
                },
            ),
            ("Authorization", authorization),
            ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
            ("Mcp-Method", request.method.as_str()),
        ];
        if request.method == "tools/call" {
            headers.push(("Mcp-Name", "durable_final_task"));
        } else if let Some(task_id) = request
            .params
            .as_ref()
            .and_then(|params| params.get("taskId"))
            .and_then(serde_json::Value::as_str)
        {
            headers.push(("Mcp-Name", task_id));
        }
        live_http_post("/mcp", &serde_json::to_vec(request).unwrap(), &headers)
    }

    #[cfg(feature = "tasks")]
    async fn auth_task_http_rpc(
        address: SocketAddr,
        request: &JsonRpcRequest,
        authorization: &str,
    ) -> Result<JsonRpcResponse, String> {
        let frame =
            live_http_exchange(address, auth_task_http_frame(request, authorization)).await?;
        let response = if live_http_response_header(&frame, "content-type")?
            .starts_with("text/event-stream")
        {
            live_http_sse_jsonrpc_response(&frame)?
        } else {
            serde_json::from_slice(live_http_response_body(&frame)?)
                .map_err(|error| error.to_string())?
        };
        eprintln!(
            "{}",
            serde_json::json!({"proof": "auth_00_local_task_owner", "method": request.method, "response": response, "frame_sha256": sha256_bounded(&frame, 65_536).unwrap().as_bytes()})
        );
        Ok(response)
    }

    #[cfg(feature = "tasks")]
    fn auth_00_local_task_owner_probe(plant_foreign_caller: bool) {
        run_live_http_test(move |cx| async move {
            let subject = format!(
                "task-owner-{}",
                std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .unwrap()
                    .as_nanos()
            );
            // TokenAuthProvider derives a fallback owner per credential, so a
            // rotated credential changes it (756719c3). Continuity across the
            // refresh therefore needs the verifier's own owner, as auth.rs
            // documents; the foreign caller has a distinct one.
            let verified_owner = |subject: &str| {
                sha256_bounded(subject.as_bytes(), 256).expect("bounded test owner subject")
            };
            let owner = verified_owner(&subject);
            let mut refreshed =
                AuthContext::with_subject(subject.clone()).with_session_owner(owner);
            refreshed.scopes = vec!["tasks".to_owned()];
            let foreign_subject = format!("foreign-{subject}");
            let verifier = StaticTokenVerifier::new([
                (
                    "owner-first",
                    AuthContext::with_subject(subject.clone()).with_session_owner(owner),
                ),
                ("owner-refreshed", refreshed),
                (
                    "foreign-valid",
                    AuthContext::with_subject(foreign_subject.clone())
                        .with_session_owner(verified_owner(&foreign_subject)),
                ),
            ])
            .map_err(|error| error.to_string())?;
            let store = Arc::new(tasks::InMemoryFinalTaskStore::default());
            let task_runtime = FinalTaskRuntime::new(
                store.clone(),
                FinalTaskRuntimeConfig::new(60_000, Some(5_000)).unwrap(),
                Arc::new(|_| {}),
            );
            let runner = task_runtime
                .install_task_service(1, Arc::new(AuthTaskSupervisor))
                .map_err(|error| error.to_string())?;
            let scope = cx.scope();
            let mut service = cx
                .spawn_in(&scope, move |service_cx| async move {
                    runner.run(&service_cx).await
                })
                .map_err(|error| error.to_string())?;
            let ready_deadline = cx.now().saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
            while !task_runtime.is_task_service_ready() {
                if cx.now() >= ready_deadline {
                    return Err("task service did not become ready".to_owned());
                }
                asupersync::runtime::yield_now().await;
            }
            let bound = Server::new("auth-task-owner", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .unwrap()
                .auth_provider(TokenAuthProvider::new(verifier))
                .tool(FinalTaskCreatingTool)
                .final_tasks(task_runtime.clone())
                .unwrap()
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| error.to_string())?;
            let address = bound.local_addr().map_err(|error| error.to_string())?;
            let task_server = Arc::clone(&bound.endpoint.server);
            let caller_cx = cx.clone();
            let mut client = cx.spawn(move |client_cx| async move {
                struct CancelServerOnDrop(Cx);
                impl Drop for CancelServerOnDrop {
                    fn drop(&mut self) {
                        self.0.cancel_with(CancelKind::User, Some("task owner probe exited"));
                    }
                }
                let _shutdown = CancelServerOnDrop(caller_cx.clone());
                let result = async {
                    let mut streams = Vec::new();
                    for method in [fastmcp_protocol::tasks_extension::TASK_UPDATE, fastmcp_protocol::TASK_CANCEL] {
                        let created = auth_task_http_rpc(address, &final_task_creating_tool_request(true), "Bearer owner-first").await?;
                        let created = created.result.ok_or_else(|| format!("authenticated task creation failed: {:?}", created.error))?;
                        let task_id = fastmcp_protocol::FinalTaskId::parse(created["taskId"].as_str().ok_or("task handle missing")?).map_err(|error| error.to_string())?;
                        let deadline = client_cx.now().saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
                        loop {
                            if matches!(task_runtime.get_task(&task_id).unwrap().task, fastmcp_protocol::Task::InputRequired { .. }) { break; }
                            if client_cx.now() >= deadline { return Err("application did not request task input".to_owned()); }
                            asupersync::time::sleep(client_cx.now(), Duration::from_millis(5)).await;
                        }
                        let params = final_tasks_params(&task_id, serde_json::json!({}));
                        let get = JsonRpcRequest::new(fastmcp_protocol::TASK_GET, Some(params.clone()), 951_i64);
                        let mut update_params = params.clone();
                        update_params["inputResponses"] = serde_json::json!({"roots": {"roots": []}});
                        let update = JsonRpcRequest::new(fastmcp_protocol::tasks_extension::TASK_UPDATE, Some(update_params), 952_i64);
                        let cancel = JsonRpcRequest::new(fastmcp_protocol::TASK_CANCEL, Some(params.clone()), 953_i64);
                        let mut notifications = SubscriptionFilter::default();
                        set_task_subscription_ids(&mut notifications, vec![task_id.clone()]).unwrap();
                        let listen = JsonRpcRequest::new(SUBSCRIPTIONS_LISTEN, Some(serde_json::json!({"_meta": params["_meta"], "notifications": notifications})), 954_i64);
                        if plant_foreign_caller {
                            let before = store.get_task_snapshot(&task_id).unwrap().unwrap();
                            let notification_before = serde_json::to_value(store.latest_notification(&task_id)).unwrap();
                            for request in [&get, &update, &cancel, &listen] {
                                let foreign = auth_task_http_rpc(address, request, "Bearer foreign-valid").await?;
                                let mut missing = request.clone();
                                if request.method == SUBSCRIPTIONS_LISTEN {
                                    let mut absent_filter = SubscriptionFilter::default();
                                    set_task_subscription_ids(&mut absent_filter, vec![fastmcp_protocol::FinalTaskId::parse("absent-task").unwrap()]).unwrap();
                                    missing.params.as_mut().unwrap()["notifications"] = serde_json::to_value(absent_filter).unwrap();
                                } else {
                                    missing.params.as_mut().unwrap()["taskId"] = serde_json::json!("absent-task");
                                }
                                let absent = auth_task_http_rpc(address, &missing, "Bearer foreign-valid").await?;
                                assert!(foreign.result.is_none());
                                assert_eq!(serde_json::to_value(&foreign.error).unwrap(), serde_json::to_value(&absent.error).unwrap());
                                assert_eq!(foreign.error.unwrap().message, "Task not found");
                                let after = store.get_task_snapshot(&task_id).unwrap().unwrap();
                                assert_eq!(after.generation(), before.generation());
                                assert_eq!(serde_json::to_value(after.task()).unwrap(), serde_json::to_value(before.task()).unwrap());
                                assert_eq!(after.authenticated_principal(), before.authenticated_principal());
                                assert_eq!(serde_json::to_value(store.latest_notification(&task_id)).unwrap(), notification_before);
                                assert!(!store.is_cancellation_requested(&task_id).unwrap());
                                assert!(store.next_accepted_input_snapshot().unwrap().is_none());
                            }
                        }
                        let read = auth_task_http_rpc(address, &get, "Bearer owner-refreshed").await?;
                        assert!(read.error.is_none());
                        assert_eq!(read.result.unwrap()["taskId"], serde_json::json!(task_id));
                        let mut stream = AsyncTcpStream::connect(address).await.map_err(|error| error.to_string())?;
                        stream.write_all(&auth_task_http_frame(&listen, "Bearer owner-refreshed")).await.map_err(|error| error.to_string())?;
                        stream.flush().await.map_err(|error| error.to_string())?;
                        let mut received = Vec::new();
                        read_live_http_until(&mut stream, &mut received, b"notifications/subscriptions/acknowledged").await?;
                        let control = if method == fastmcp_protocol::tasks_extension::TASK_UPDATE { &update } else { &cancel };
                        let controlled = auth_task_http_rpc(address, control, "Bearer owner-refreshed").await?;
                        assert!(controlled.error.is_none());
                        assert_eq!(controlled.result.unwrap()["resultType"], "complete");
                        let terminal = if method == fastmcp_protocol::tasks_extension::TASK_UPDATE { "completed" } else { "cancelled" };
                        read_live_http_until(&mut stream, &mut received, format!("\"status\":\"{terminal}\"").as_bytes()).await?;
                        streams.push((stream, received, task_id, terminal));
                    }
                    assert_eq!(task_server.terminate_subscription_streams(), 2);
                    for (mut stream, mut received, task_id, terminal) in streams {
                        read_live_http_to_end(&mut stream, &mut received, "owner subscription terminal EOF").await?;
                        let messages = live_http_chunked_sse_messages(&received)?;
                        let Some(JsonRpcMessage::Request(acknowledgement)) = messages.first() else { panic!("missing subscription acknowledgement"); };
                        let ServerNotification::SubscriptionsAcknowledged(acknowledgement) = ServerNotification::decode(acknowledgement).unwrap() else { panic!("first event must acknowledge subscription"); };
                        assert_eq!(task_subscription_ids(&acknowledgement.notifications).unwrap().unwrap(), vec![task_id.clone()]);
                        let events = messages.iter().filter_map(|message| {
                            let JsonRpcMessage::Request(request) = message else { return None; };
                            (request.method == fastmcp_protocol::TASK_STATUS_NOTIFICATION).then(|| serde_json::from_value::<FinalTaskStatusNotification>(serde_json::to_value(request).unwrap()).unwrap())
                        }).collect::<Vec<_>>();
                        assert!(!events.is_empty());
                        assert!(events.iter().all(|event| event.params.task.base().task_id == task_id));
                        let terminal_events = events.iter().filter(|event| serde_json::to_value(&event.params.task).unwrap()["status"] == terminal).collect::<Vec<_>>();
                        assert_eq!(terminal_events.len(), 1);
                        if terminal == "completed" {
                            let task = serde_json::to_value(&terminal_events[0].params.task).unwrap();
                            assert_eq!(task["result"]["content"][0]["text"], "owner input consumed");
                        }
                        eprintln!("{}", serde_json::json!({"proof": "auth_00_local_task_owner", "subject": subject, "task_id": task_id, "terminal": terminal, "subscription_events": events.len(), "subscription_frame_sha256": sha256_bounded(&received, 65_536).unwrap().as_bytes(), "negative": plant_foreign_caller}));
                    }
                    Ok::<_, String>(())
                }.await;
                caller_cx.cancel_with(CancelKind::User, Some("task owner probe complete"));
                result
            }).map_err(|error| error.to_string())?;
            let serve = bound.serve(&cx).await;
            // The application service has its own context. Cancelling the
            // HTTP caller does not stop that context or its idle receiver.
            service.abort();
            let client_result = client
                .join(&cx)
                .await
                .map_err(|error| format!("task owner client failed: {error:?}"));
            let mut service_shutdown = Box::pin(asupersync::time::timeout_at(
                cx.now().saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS),
                service.join(&cx),
            ));
            // Keep the real cleanup deadline while shielding its timer from
            // the caller's cancellation. The service's own abort stays active.
            let service_result = std::future::poll_fn(|task_context| {
                cx.masked(|| service_shutdown.as_mut().poll(task_context))
            })
            .await
            .map_err(|_| live_http_test_timeout("task owner service shutdown"))?;
            match service_result {
                Ok(Ok(())) | Err(asupersync::runtime::JoinError::Cancelled(_)) => {}
                other => return Err(format!("task service failed during owner probe: {other:?}")),
            }
            client_result??;
            require_quiescent_http_shutdown(serve.map_err(|error| error.to_string())?, "task owner")
                .await
        });
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn auth_00_local_task_owner_positive() {
        auth_00_local_task_owner_probe(false);
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn auth_00_local_task_owner_planted_negative() {
        auth_00_local_task_owner_probe(true);
    }

    #[cfg(feature = "tasks")]
    fn auth_00_task_notification_origin_probe(foreign_origin: bool) {
        let runtime = FinalTaskRuntime::in_memory(
            FinalTaskRuntimeConfig::new(60_000, None).unwrap(),
            Arc::new(|_| {}),
        );
        let _service = start_final_tasks_test_service(&runtime);
        let captured = Arc::new(Mutex::new(Vec::new()));
        let captured_by_emitter = Arc::clone(&captured);
        runtime.add_owned_notification_emitter(Arc::new(move |notification, principal| {
            captured_by_emitter
                .lock()
                .unwrap()
                .push((notification, principal));
        }));
        let owner = McpContext::new(Cx::for_testing(), 1)
            .with_auth(AuthContext::with_subject("notification-owner"));
        let created = runtime
            .create_task_for_request(&owner, final_tasks_test_work_descriptor(), None)
            .unwrap();
        let task_id = created.task.base().task_id.clone();
        let (notification, principal) = captured.lock().unwrap()[0].clone();
        assert_eq!(
            principal,
            Some(auth::principal_fingerprint(owner.auth().as_ref()).unwrap())
        );
        let registry = Arc::new(FinalSubscriptionRegistry::default());
        let sent = Arc::new(Mutex::new(Vec::new()));
        let sent_by_sender = Arc::clone(&sent);
        let mut requested = SubscriptionFilter::default();
        set_task_subscription_ids(&mut requested, vec![task_id]).unwrap();
        let _lease = registry
            .open_with_task_principal(
                1_i64.into(),
                requested,
                true,
                None,
                McpRequestCancellation::new(),
                None,
                Arc::new(move |event| sent_by_sender.lock().unwrap().push(event)),
                principal,
            )
            .unwrap();
        assert_eq!(sent.lock().unwrap().len(), 1);
        let origin = if foreign_origin {
            Some(
                auth::principal_fingerprint(Some(&AuthContext::with_subject("old-foreign-owner")))
                    .unwrap(),
            )
        } else {
            principal
        };
        let published = registry
            .publish_owned_task(notification.clone(), origin)
            .unwrap();
        assert_eq!(published, usize::from(!foreign_origin));
        assert_eq!(sent.lock().unwrap().len(), 1 + published);
        if foreign_origin {
            // A task ID, timestamp, and payload may all be identical after
            // store reuse. Origin custody alone prevents the stale owner event.
            assert_eq!(
                registry
                    .publish_owned_task(notification, principal)
                    .unwrap(),
                1
            );
            assert_eq!(sent.lock().unwrap().len(), 2);
        }
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn auth_00_task_notification_origin_positive() {
        auth_00_task_notification_origin_probe(false);
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn auth_00_task_notification_origin_planted_negative() {
        auth_00_task_notification_origin_probe(true);
    }

    fn auth_01_http_header_probe(reject_forbidden_locations: bool) {
        run_live_http_test(move |cx| async move {
            let probe = HttpHeaderAuthProbe::new();
            let bound = Server::new("auth-01-http-header", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("modern policy must be available")
                .auth_provider(probe.clone())
                .middleware(probe.clone())
                .tool(probe.clone())
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| error.to_string())?;
            let address = bound.local_addr().map_err(|error| error.to_string())?;
            let caller_cx = cx.clone();
            let mut client = cx.spawn(move |_client_cx| async move {
                let result = async {
                    let authorization = format!("Bearer {}", probe.token);
                    let mut request = modern_http_json_tool_request("http_header_auth_probe", 945);
                    let mut body: serde_json::Value = serde_json::from_slice(&request.body)
                        .map_err(|error| error.to_string())?;
                    body["params"]["arguments"] = serde_json::json!({
                        "token": "application-data", "access_token": "application-data",
                    });
                    request.body = serde_json::to_vec(&body).map_err(|error| error.to_string())?;
                    for (index, accept) in ["application/json", "text/event-stream"].into_iter().enumerate() {
                        let common = [
                            ("Accept", accept),
                            ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                            ("Mcp-Method", "tools/call"),
                            ("Mcp-Name", "http_header_auth_probe"),
                        ];
                        let mut headers = common.to_vec();
                        headers.push(("Authorization", authorization.as_str()));
                        let mut rejected_locations = 0;
                        if reject_forbidden_locations {
                            let before = probe.effects();
                            for container in [None, Some("_meta"), Some("headers")] {
                                for field in ["authorization", "Authorization", "auth", "token", "access_token", "accessToken"] {
                                    let mut forbidden = body.clone();
                                    let destination = match container {
                                        Some(container) => &mut forbidden["params"][container],
                                        None => &mut forbidden["params"],
                                    };
                                    destination[field] = serde_json::json!(authorization);
                                    let forbidden = serde_json::to_vec(&forbidden).map_err(|error| error.to_string())?;
                                    for credential_headers in [&common[..], &headers[..]] {
                                        let rejected = live_http_exchange(address, live_http_post("/mcp?application_context=permitted", &forbidden, credential_headers)).await?;
                                        require_http_credential_location_rejection(&rejected, &probe.token)?;
                                        rejected_locations += 1;
                                        if probe.effects() != before {
                                            return Err(format!("body credential invoked provider/middleware/handler: container={container:?}, field={field}"));
                                        }
                                    }
                                }
                            }
                            for field in ["access_token", "%61ccess_token", "ACCESS_TOKEN", "authorization", "auth", "token", "accessToken"] {
                                for credential_headers in [&common[..], &headers[..]] {
                                    let rejected = live_http_exchange(address, live_http_post(
                                        &format!("/mcp?application_context=permitted&{field}={}", probe.token), &request.body, credential_headers,
                                    )).await?;
                                    require_http_credential_location_rejection(&rejected, &probe.token)?;
                                    rejected_locations += 1;
                                    if probe.effects() != before {
                                        return Err(format!("query credential invoked provider/middleware/handler: field={field}"));
                                    }
                                }
                            }
                        }
                        let accepted = live_http_exchange(address, live_http_post(
                            "/mcp?application_context=permitted", &request.body, &headers,
                        )).await?;
                        if !accepted.starts_with(b"HTTP/1.1 200") {
                            return Err(format!("native header did not reach the {accept} handler"));
                        }
                        let responses = if accept == "application/json" {
                            vec![serde_json::from_slice::<JsonRpcResponse>(live_http_response_body(&accepted)?)
                                .map_err(|error| error.to_string())?]
                        } else {
                            live_http_chunked_sse_messages(&accepted)?.into_iter().filter_map(|message| {
                                if let JsonRpcMessage::Response(response) = message { Some(response) } else { None }
                            }).collect::<Vec<_>>()
                        };
                        if responses.len() != 1 || responses[0].id != Some(945_i64.into())
                            || responses[0].error.is_some()
                            || responses[0].result.as_ref().and_then(|result| result.pointer("/content/0/text")).and_then(serde_json::Value::as_str) != Some(probe.subject.as_str())
                            || probe.effects() != (index + 1, index + 1, index + 1)
                        {
                            return Err(format!("native header lost its principal, response, or exactly-once effects: {accept}"));
                        }
                        eprintln!("{}", serde_json::json!({
                            "proof": "auth_01_http_header", "bead": "bd-f6apv",
                            "transport": accept, "listener": address.to_string(),
                            "runtime_subject": probe.subject, "request_id": 945,
                            "response_frame": String::from_utf8_lossy(&accepted),
                            "response_sha256": sha256_bounded(&accepted, 65_536).map_err(|error| error.to_string())?.as_bytes(),
                            "effects": probe.effects(), "responses": responses.len(),
                            "rejected_locations": rejected_locations,
                            "expected_rejections": if reject_forbidden_locations { 50 } else { 0 },
                            "finished_unix_ns": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_err(|error| error.to_string())?.as_nanos(),
                        }));
                    }
                    Ok::<_, String>(())
                }.await;
                caller_cx.cancel_with(CancelKind::User, Some("AUTH-01 HTTP probe complete"));
                result
            }).map_err(|error| error.to_string())?;
            let serve = bound.serve(&cx).await;
            client
                .join(&cx)
                .await
                .map_err(|error| format!("HTTP auth probe client failed: {error:?}"))??;
            require_quiescent_http_shutdown(
                serve.map_err(|error| error.to_string())?,
                "AUTH-01 HTTP",
            )
            .await
        });
    }

    #[test]
    fn auth_01_http_header_only_positive() {
        auth_01_http_header_probe(false);
    }

    #[test]
    fn auth_01_http_body_query_planted_negative() {
        auth_01_http_header_probe(true);
        // Direct embedding retains raw query names too: the same encoded
        // credential must be rejected before a session era or provider changes.
        let cx = Cx::for_testing();
        let probe = HttpHeaderAuthProbe::new();
        let endpoint = Server::new("auth-01-direct-http", "1.0.0")
            .auth_provider(probe.clone())
            .middleware(probe.clone())
            .tool(probe.clone())
            .test_http_endpoint("http://auth.test")
            .expect("endpoint must build");
        let mut session = endpoint.open_session(&cx).expect("session must open");
        for request in [
            modern_http_json_tool_request("http_header_auth_probe", 945),
            HttpRequest::new(HttpMethod::Get, "/sse"),
        ] {
            let response = block_on(
                session.handle_async(
                    &cx,
                    request
                        .with_header("Authorization", format!("Bearer {}", probe.token))
                        .with_query("%61ccess_token", &probe.token),
                ),
            )
            .expect("credential refusal must be an HTTP response");
            assert!(
                matches!(response, ServerHttpEndpointResponse::Immediate(response) if response.status == HttpStatus::UNAUTHORIZED)
            );
            assert_eq!(session.selected_era, None);
            assert_eq!(probe.effects(), (0, 0, 0));
        }
        cx.cancel_with(CancelKind::User, Some("cancel before HTTP authentication"));
        let response = block_on(
            session.handle_async(
                &cx,
                modern_http_json_tool_request("http_header_auth_probe", 945)
                    .with_header("Authorization", format!("Bearer {}", probe.token)),
            ),
        )
        .expect("cancelled authentication must return an HTTP refusal");
        assert!(
            matches!(response, ServerHttpEndpointResponse::Immediate(response) if response.status == HttpStatus::UNAUTHORIZED)
        );
        assert_eq!(session.selected_era, None);
        assert_eq!(probe.effects(), (0, 0, 0));
        let expired =
            Cx::for_testing_with_budget(Budget::new().with_deadline(asupersync::Time::ZERO));
        let mut session = endpoint
            .open_session(&Cx::for_testing())
            .expect("deadline probe must start with a fresh live session");
        let response = block_on(
            session.handle_async(
                &expired,
                modern_http_json_tool_request("http_header_auth_probe", 945)
                    .with_header("Authorization", format!("Bearer {}", probe.token)),
            ),
        )
        .expect("expired authentication must return an HTTP refusal");
        assert!(
            matches!(response, ServerHttpEndpointResponse::Immediate(response) if response.status == HttpStatus::UNAUTHORIZED)
        );
        assert_eq!(session.selected_era, None);
        assert_eq!(probe.effects(), (0, 0, 0));

        #[cfg(feature = "legacy-2024-11-05")]
        auth_01_legacy_receipt_keeps_request_zero_and_notification_distinct(&endpoint, &probe);
    }

    /// The provider's numeric context ID is not a wire identity: a
    /// notification and request ID zero both map to zero. Receipt reuse must
    /// preserve that distinction without another provider call.
    // Exact-2024 era: the receipt is committed through the legacy path.
    #[cfg(feature = "legacy-2024-11-05")]
    fn auth_01_legacy_receipt_keeps_request_zero_and_notification_distinct(
        endpoint: &ServerHttpEndpoint,
        probe: &HttpHeaderAuthProbe,
    ) {
        let cx = Cx::for_testing();
        let authorization = transport_authorization_from_http_request(
            &HttpRequest::new(HttpMethod::Post, "/messages")
                .with_header("Authorization", format!("Bearer {}", probe.token)),
        )
        .expect("native header must be captured");
        let original = JsonRpcRequest::new("tools/list", None, 0_i64);
        let receipt = endpoint
            .server
            .preauthenticate_http_request(&cx, &original, &authorization)
            .expect("the original request must authenticate");
        assert_eq!(probe.effects(), (1, 0, 0));
        let changed = JsonRpcRequest::notification("tools/list", None);
        let rejected_ctx = McpContext::new(cx.clone(), 0);
        assert!(receipt.commit_legacy(&rejected_ctx, &changed).is_err());
        assert!(rejected_ctx.auth().is_none());
        assert_eq!(probe.effects(), (1, 0, 0));
        let accepted_ctx = McpContext::new(cx, 0);
        receipt
            .commit_legacy(&accepted_ctx, &original)
            .expect("the unchanged request must consume its authenticated receipt");
        assert_eq!(
            accepted_ctx.auth().and_then(|auth| auth.subject),
            Some(probe.subject.clone()),
        );
        assert_eq!(probe.effects(), (1, 0, 0));
    }

    // Exact-2024 era: legacy HTTP SSE session registry.
    #[cfg(feature = "legacy-2024-11-05")]
    fn auth_01_http_legacy_cancellation_probe(reject_forbidden_locations: bool) {
        run_live_http_test(move |cx| async move {
            let probe = HttpHeaderAuthProbe::new();
            let started = Arc::new(AtomicBool::new(false));
            let observed_cancellation = Arc::new(AtomicBool::new(false));
            let bound = Server::new("auth-01-legacy-cancellation", "1.0.0")
                .auth_provider(probe.clone())
                .middleware(probe.clone())
                .tool(LiveLegacyCancellationTool {
                    started: Arc::clone(&started),
                    observed_cancellation: Arc::clone(&observed_cancellation),
                })
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| error.to_string())?;
            let address = bound.local_addr().map_err(|error| error.to_string())?;
            let legacy_sessions = Arc::clone(&bound.legacy_sessions);
            let caller_cx = cx.clone();
            let mut client = cx.spawn(move |client_cx| async move {
                let result = async {
                    let authorization = format!("Bearer {}", probe.token);
                    let headers = [("Authorization", authorization.as_str())];
                    let (_sse, session_id, _received) = open_live_legacy_http_session(address, &headers).await?;
                    if probe.provider_calls.load(Ordering::Acquire) != 1 {
                        return Err("legacy SSE opener must authenticate exactly once".to_owned());
                    }
                    let path = format!("/messages?session_id={session_id}");
                    for (index, request) in [
                        JsonRpcRequest::new("initialize", Some(serde_json::json!({
                            "protocolVersion": LEGACY_PROTOCOL_VERSION,
                            "capabilities": {},
                            "clientInfo": {"name": "auth-01-legacy", "version": "1.0.0"},
                        })), 946_i64),
                        JsonRpcRequest::notification("notifications/initialized", None),
                    ].into_iter().enumerate() {
                        let body = serde_json::to_vec(&request).map_err(|error| error.to_string())?;
                        let response = live_http_exchange(address, live_http_post(&path, &body, &headers)).await?;
                        if !response.starts_with(b"HTTP/1.1 202") {
                            return Err("header-authenticated legacy setup failed".to_owned());
                        }
                        if probe.provider_calls.load(Ordering::Acquire) != index + 2 {
                            return Err(format!("legacy {} must authenticate exactly once", request.method));
                        }
                    }
                    let target_id = RequestId::Number(947);
                    let target = JsonRpcRequest::new("tools/call", Some(serde_json::json!({
                        "name": "live_legacy_cancellation_tool", "arguments": {},
                    })), target_id.clone());
                    let target_body = serde_json::to_vec(&target).map_err(|error| error.to_string())?;
                    let target_request = live_http_post(&path, &target_body, &headers);
                    let mut target = client_cx.spawn(move |_| async move {
                        live_http_exchange(address, target_request).await
                    }).map_err(|error| error.to_string())?;
                    let deadline = client_cx.now().saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
                    while !started.load(Ordering::Acquire) {
                        asupersync::time::timeout_at(deadline,
                            asupersync::time::sleep(client_cx.now(), Duration::from_millis(1)))
                            .await.map_err(|_| live_http_test_timeout("AUTH-01 active legacy handler"))?;
                    }
                    let session = legacy_sessions.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
                        .get(&session_id).cloned().ok_or_else(|| "legacy session missing".to_owned())?;
                    let cancellation = session.cancellation.admissions.admitted_request_cancellation(&target_id)
                        .ok_or_else(|| "active legacy cancellation authority missing".to_owned())?;
                    let notification = serde_json::json!({
                        "jsonrpc": "2.0", "method": "notifications/cancelled",
                        "params": {"requestId": target_id, "reason": "AUTH-01 header cancellation"},
                    });
                    let before = probe.effects();
                    if before.0 != 4 {
                        return Err("legacy tool must authenticate exactly once".to_owned());
                    }
                    let mut rejected_locations = 0;
                    if reject_forbidden_locations {
                        for container in [None, Some("_meta"), Some("headers")] {
                            let mut forbidden = notification.clone();
                            match container {
                                Some(container) => forbidden["params"][container]["token"] = serde_json::json!(probe.token),
                                None => forbidden["params"]["token"] = serde_json::json!(probe.token),
                            }
                            let body = serde_json::to_vec(&forbidden).map_err(|error| error.to_string())?;
                            for credential_headers in [&[][..], &headers[..]] {
                                let rejected = live_http_exchange(address, live_http_post(&path, &body, credential_headers)).await?;
                                require_http_credential_location_rejection(&rejected, &probe.token)?;
                                rejected_locations += 1;
                                if probe.effects() != before || cancellation.is_cancel_requested()
                                    || observed_cancellation.load(Ordering::Acquire) || !matches!(target.try_join(), Ok(None))
                                {
                                    return Err("body credential changed provider or active cancellation state".to_owned());
                                }
                            }
                        }
                        let body = serde_json::to_vec(&notification).map_err(|error| error.to_string())?;
                        let rejected = live_http_exchange(address, live_http_post(
                            &format!("{path}&%61ccess_token={}", probe.token), &body, &headers,
                        )).await?;
                        require_http_credential_location_rejection(&rejected, &probe.token)?;
                        rejected_locations += 1;
                        if probe.effects() != before || cancellation.is_cancel_requested()
                            || observed_cancellation.load(Ordering::Acquire) || !matches!(target.try_join(), Ok(None))
                        {
                            return Err("query credential changed provider or active cancellation state".to_owned());
                        }
                    }
                    let body = serde_json::to_vec(&notification).map_err(|error| error.to_string())?;
                    let accepted = live_http_exchange(address, live_http_post(&path, &body, &headers)).await?;
                    if !accepted.starts_with(b"HTTP/1.1 202") {
                        return Err("header-only cancellation was rejected".to_owned());
                    }
                    let response = target.join(&client_cx).await.map_err(|error| format!("legacy target failed: {error:?}"))??;
                    if !response.starts_with(b"HTTP/1.1 202") || !observed_cancellation.load(Ordering::Acquire)
                        || !cancellation.is_cancel_requested() || probe.effects() != (before.0 + 1, before.1, before.2)
                    {
                        return Err("header-only cancellation lost its exactly-once authenticated effect".to_owned());
                    }
                    eprintln!("{}", serde_json::json!({
                        "proof": "auth_01_http_legacy_cancellation", "bead": "bd-f6apv",
                        "listener": address.to_string(), "runtime_subject": probe.subject,
                        "request_id": target_id, "session_id": session_id,
                        "response_frame": String::from_utf8_lossy(&accepted),
                        "response_sha256": sha256_bounded(&accepted, 65_536).map_err(|error| error.to_string())?.as_bytes(),
                        "effects_before": before, "effects_after": probe.effects(),
                        "handler_observed_cancellation": observed_cancellation.load(Ordering::Acquire),
                        "rejected_locations": rejected_locations,
                        "expected_rejections": if reject_forbidden_locations { 7 } else { 0 },
                        "finished_unix_ns": std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_err(|error| error.to_string())?.as_nanos(),
                    }));
                    Ok::<_, String>(())
                }.await;
                caller_cx.cancel_with(CancelKind::User, Some("AUTH-01 legacy cancellation probe complete"));
                result
            }).map_err(|error| error.to_string())?;
            let serve = bound.serve(&cx).await;
            client
                .join(&cx)
                .await
                .map_err(|error| format!("legacy auth client failed: {error:?}"))??;
            require_quiescent_http_shutdown(
                serve.map_err(|error| error.to_string())?,
                "AUTH-01 legacy cancellation",
            )
            .await
        });
    }

    // Exact-2024 era: legacy HTTP SSE session registry.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn auth_01_http_legacy_cancellation_header_positive() {
        auth_01_http_legacy_cancellation_probe(false);
    }

    // Exact-2024 era: legacy HTTP SSE session registry.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn auth_01_http_legacy_cancellation_body_planted_negative() {
        auth_01_http_legacy_cancellation_probe(true);
    }

    #[test]
    fn admitted_raw_params_are_withheld_after_sanitation_changes_the_request() {
        // RH-5 neighbor of the retained-source positive: a byte-exact raw
        // sidecar is legal only while the request still carries the value it
        // was admitted with.  Credential stripping changes that request, so
        // continuation routing must receive no stale source.
        let raw = r#"{"authorization":"Bearer never-forward","requestState":"state"}"#;
        let mut request = JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::from_str(raw).expect("raw sidecar fixture must decode")),
            937_i64,
        );
        let admitted = request.params.clone();
        assert_eq!(
            retained_raw_params(Some(raw), admitted.as_ref(), request.params.as_ref()),
            Some(raw)
        );
        auth::strip_recognized_access_credentials(&mut request.params);
        assert_eq!(
            retained_raw_params(Some(raw), admitted.as_ref(), request.params.as_ref()),
            None
        );
        assert_eq!(
            request.params,
            Some(serde_json::json!({"requestState": "state"})),
            "stale raw parameters must be withheld without mutating the sanitized request",
        );
    }

    #[cfg(feature = "websocket")]
    #[test]
    fn websocket_auth_custody_rejects_a_stale_connection_generation_before_dispatch() {
        let cx = Cx::for_testing();
        let custody = AuthDispatchCustody::WebSocket(Arc::new(WebSocketAuthCustody {
            connection_generation: 44,
            fingerprint: auth::principal_fingerprint(None).expect("anonymous digest must exist"),
            authenticated: None,
            rejected_inband_request_ids: Mutex::new(HashSet::new()),
        }));
        let inbound = InboundRequestContext::new(cx.clone(), 939, InboundRequestTransport::Memory);
        let mut request = JsonRpcRequest::new(
            "tools/list",
            Some(serde_json::json!({
                "_meta": {MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION},
            })),
            939_i64,
        );
        let error = custody
            .commit(&McpContext::new(cx, 939), &inbound, &mut request, Some(45))
            .expect_err("a stale WebSocket custody must not cross a connection generation");
        assert_eq!(error.code, McpErrorCode::ResourceForbidden);
        assert_eq!(request.method, "tools/list");
        assert!(request.params.is_some());
    }

    #[test]
    fn live_http_json_auth_receipt_commits_one_accepted_provider_result() {
        run_live_http_test(|cx| async move {
            let provider_calls = Arc::new(AtomicUsize::new(0));
            let handler_calls = Arc::new(AtomicUsize::new(0));
            let middleware_calls = Arc::new(AtomicUsize::new(0));
            let saw_credential = Arc::new(AtomicBool::new(false));
            let bound = Server::new("live-http-json-auth-receipt", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .auth_provider(OneShotNativeAuthProvider {
                    calls: Arc::clone(&provider_calls),
                })
                .middleware(ModernHttpAuthMiddleware {
                    calls: Arc::clone(&middleware_calls),
                    saw_credential: Arc::clone(&saw_credential),
                })
                .tool(ModernHttpAuthCounterTool {
                    calls: Arc::clone(&handler_calls),
                })
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("JSON auth receipt bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("JSON auth receipt address failed: {error}"))?;
            let request = modern_http_json_tool_request("modern_http_auth_counter", 940);
            let mixed_body = serde_json::to_vec(&JsonRpcRequest::new(
                "tools/call",
                Some(serde_json::json!({
                    "authorization": "Bearer in-band-never-echo",
                    "name": "modern_http_auth_counter",
                    "arguments": {},
                    "_meta": {
                        MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                        FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                    },
                })),
                941_i64,
            ))
            .map_err(|error| format!("mixed JSON auth receipt did not serialize: {error}"))?;
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let headers = [
                        ("Accept", "application/json"),
                        ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                        ("Mcp-Method", "tools/call"),
                        ("Mcp-Name", "modern_http_auth_counter"),
                    ];
                    let result = async {
                        // This is the first provider invocation and the only
                        // invocation allowed to create an accepted receipt.
                        let accepted = live_http_exchange(
                            address,
                            live_http_post(
                                "/mcp",
                                &request.body,
                                &[
                                    ("Authorization", "Bearer alpha"),
                                    ("Accept", "application/json"),
                                    ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                    ("Mcp-Method", "tools/call"),
                                    ("Mcp-Name", "modern_http_auth_counter"),
                                ],
                            ),
                        )
                        .await?;
                        let invalid = live_http_exchange(
                            address,
                            live_http_post(
                                "/mcp",
                                &request.body,
                                &[
                                    ("Authorization", "Bearer beta-never-echo"),
                                    ("Accept", "application/json"),
                                    ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                    ("Mcp-Method", "tools/call"),
                                    ("Mcp-Name", "modern_http_auth_counter"),
                                ],
                            ),
                        )
                        .await?;
                        let missing = live_http_exchange(
                            address,
                            live_http_post("/mcp", &request.body, &headers),
                        )
                        .await?;
                        let duplicate = live_http_exchange(
                            address,
                            live_http_post(
                                "/mcp",
                                &request.body,
                                &[
                                    ("Authorization", "Bearer alpha"),
                                    ("aUtHoRiZaTiOn", "Bearer beta"),
                                    ("Accept", "application/json"),
                                    ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                    ("Mcp-Method", "tools/call"),
                                    ("Mcp-Name", "modern_http_auth_counter"),
                                ],
                            ),
                        )
                        .await?;
                        let mixed = live_http_exchange(
                            address,
                            live_http_post(
                                "/mcp",
                                &mixed_body,
                                &[
                                    ("Authorization", "Bearer alpha"),
                                    ("Accept", "application/json"),
                                    ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                    ("Mcp-Method", "tools/call"),
                                    ("Mcp-Name", "modern_http_auth_counter"),
                                ],
                            ),
                        )
                        .await?;
                        Ok::<_, String>((accepted, invalid, missing, duplicate, mixed))
                    }
                    .await;
                    caller_cx
                        .cancel_with(CancelKind::User, Some("JSON auth receipt proof complete"));
                    result
                })
                .map_err(|error| format!("JSON auth receipt client admission failed: {error}"))?;
            let serve = bound.serve(&cx).await;
            let (accepted, invalid, missing, duplicate, mixed) = client
                .join(&cx)
                .await
                .map_err(|error| format!("JSON auth receipt client failed: {error:?}"))??;
            let shutdown =
                serve.map_err(|error| format!("JSON auth receipt server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "JSON auth receipt").await?;
            let accepted: JsonRpcResponse =
                serde_json::from_slice(live_http_response_body(&accepted)?).map_err(|error| {
                    format!("accepted JSON auth receipt was not JSON-RPC: {error}")
                })?;
            if accepted.error.is_some()
                || provider_calls.load(Ordering::Acquire) != 2
                || handler_calls.load(Ordering::Acquire) != 1
                || middleware_calls.load(Ordering::Acquire) != 1
                || saw_credential.load(Ordering::Acquire)
            {
                return Err(
                    "JSON auth receipt expected two provider attempts and one sanitized dispatch"
                        .to_owned(),
                );
            }
            for response in [invalid, missing, duplicate, mixed] {
                if !response.starts_with(b"HTTP/1.1 401")
                    || live_http_response_header(&response, "www-authenticate")? != "Bearer"
                    || String::from_utf8_lossy(&response).contains("beta-never-echo")
                    || String::from_utf8_lossy(&response).contains("in-band-never-echo")
                {
                    return Err(
                        "denied JSON auth receipt was not bounded before dispatch".to_owned()
                    );
                }
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_sse_auth_receipt_commits_one_accepted_provider_result_and_fences_denials() {
        run_live_http_test(|cx| async move {
            let provider_calls = Arc::new(AtomicUsize::new(0));
            let handler_calls = Arc::new(AtomicUsize::new(0));
            let middleware_calls = Arc::new(AtomicUsize::new(0));
            let saw_credential = Arc::new(AtomicBool::new(false));
            let bound = Server::new("live-http-auth-receipt", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .auth_provider(OneShotNativeAuthProvider {
                    calls: Arc::clone(&provider_calls),
                })
                .middleware(ModernHttpAuthMiddleware {
                    calls: Arc::clone(&middleware_calls),
                    saw_credential: Arc::clone(&saw_credential),
                })
                .tool(ModernHttpAuthCounterTool {
                    calls: Arc::clone(&handler_calls),
                })
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("auth receipt bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("auth receipt address failed: {error}"))?;
            let request = modern_http_json_tool_request("modern_http_auth_counter", 938);
            let mixed_body = serde_json::to_vec(&JsonRpcRequest::new(
                "tools/call",
                Some(serde_json::json!({
                    "authorization": "Bearer in-band-never-echo",
                    "name": "modern_http_auth_counter",
                    "arguments": {},
                    "_meta": {
                        MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                        FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                    },
                })),
                942_i64,
            ))
            .map_err(|error| format!("mixed SSE auth receipt did not serialize: {error}"))?;
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let headers = [
                        ("Accept", "text/event-stream"),
                        ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                        ("Mcp-Method", "tools/call"),
                        ("Mcp-Name", "modern_http_auth_counter"),
                    ];
                    let result = async {
                        let accepted = live_http_exchange(
                            address,
                            live_http_post(
                                "/mcp",
                                &request.body,
                                &[
                                    ("Authorization", "Bearer alpha"),
                                    ("Accept", "text/event-stream"),
                                    ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                    ("Mcp-Method", "tools/call"),
                                    ("Mcp-Name", "modern_http_auth_counter"),
                                ],
                            ),
                        )
                        .await?;
                        let invalid = live_http_exchange(
                            address,
                            live_http_post(
                                "/mcp",
                                &request.body,
                                &[
                                    ("Authorization", "Bearer beta-never-echo"),
                                    ("Accept", "text/event-stream"),
                                    ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                    ("Mcp-Method", "tools/call"),
                                    ("Mcp-Name", "modern_http_auth_counter"),
                                ],
                            ),
                        )
                        .await?;
                        let missing = live_http_exchange(
                            address,
                            live_http_post("/mcp", &request.body, &headers),
                        )
                        .await?;
                        let duplicate = live_http_exchange(
                            address,
                            live_http_post(
                                "/mcp",
                                &request.body,
                                &[
                                    ("Authorization", "Bearer alpha"),
                                    ("AUTHORIZATION", "Bearer beta"),
                                    ("Accept", "text/event-stream"),
                                    ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                    ("Mcp-Method", "tools/call"),
                                    ("Mcp-Name", "modern_http_auth_counter"),
                                ],
                            ),
                        )
                        .await?;
                        let mixed = live_http_exchange(
                            address,
                            live_http_post(
                                "/mcp",
                                &mixed_body,
                                &[
                                    ("Authorization", "Bearer alpha"),
                                    ("Accept", "text/event-stream"),
                                    ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                    ("Mcp-Method", "tools/call"),
                                    ("Mcp-Name", "modern_http_auth_counter"),
                                ],
                            ),
                        )
                        .await?;
                        Ok::<_, String>((accepted, invalid, missing, duplicate, mixed))
                    }
                    .await;
                    caller_cx.cancel_with(CancelKind::User, Some("auth receipt proof complete"));
                    result
                })
                .map_err(|error| format!("auth receipt client admission failed: {error}"))?;
            let serve = bound.serve(&cx).await;
            let (accepted, invalid, missing, duplicate, mixed) = client
                .join(&cx)
                .await
                .map_err(|error| format!("auth receipt client failed: {error:?}"))??;
            let shutdown = serve.map_err(|error| format!("auth receipt server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "auth receipt").await?;
            let accepted_event = live_http_sse_jsonrpc_response(&accepted)?;
            if !accepted.starts_with(b"HTTP/1.1 200")
                || live_http_response_header(&accepted, "content-type")? != "text/event-stream"
                || accepted_event.error.is_some()
                || provider_calls.load(Ordering::Acquire) != 2
                || handler_calls.load(Ordering::Acquire) != 1
                || middleware_calls.load(Ordering::Acquire) != 1
                || saw_credential.load(Ordering::Acquire)
            {
                return Err(
                    "SSE auth receipt did not record exactly two provider attempts and one dispatch"
                        .to_owned(),
                );
            }
            for response in [invalid, missing, duplicate, mixed] {
                if !response.starts_with(b"HTTP/1.1 401")
                    || live_http_response_header(&response, "www-authenticate")? != "Bearer"
                    || String::from_utf8_lossy(&response).contains("beta-never-echo")
                    || String::from_utf8_lossy(&response).contains("in-band-never-echo")
                {
                    return Err(
                        "denied native auth mutated dispatch or exposed a bearer".to_owned()
                    );
                }
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_anonymous_stateless_posts_isolate_disabled_components() {
        run_live_http_test(|cx| async move {
            let calls = Arc::new(AtomicUsize::new(0));
            let bound = Server::new("live-http-anonymous-disablement", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .tool(HttpSessionDisablingTool {
                    calls: Arc::clone(&calls),
                })
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("live HTTP anonymous disablement bind failed: {error}"))?;
            let address = bound.local_addr().map_err(|error| {
                format!("live HTTP anonymous disablement address failed: {error}")
            })?;
            let request = JsonRpcRequest::new(
                "tools/call",
                Some(serde_json::json!({
                    "name": "http_session_disabling_tool",
                    "arguments": {},
                    "_meta": {
                        MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                        FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                    },
                })),
                924_i64,
            );
            let body = serde_json::to_vec(&request).map_err(|error| {
                format!("anonymous disablement request did not serialize: {error}")
            })?;
            let request = live_http_post(
                "/mcp",
                &body,
                &[
                    ("Accept", "application/json"),
                    ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                    ("Mcp-Method", "tools/call"),
                    ("Mcp-Name", "http_session_disabling_tool"),
                ],
            );
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let result = async {
                        let first = live_http_exchange(address, request.clone()).await?;
                        let second = live_http_exchange(address, request).await?;
                        Ok::<_, String>((first, second))
                    }
                    .await;
                    caller_cx.cancel_with(
                        CancelKind::User,
                        Some("live HTTP anonymous disablement proof complete"),
                    );
                    result
                })
                .map_err(|error| {
                    format!("live HTTP anonymous disablement client admission failed: {error}")
                })?;

            let serve = bound.serve(&cx).await;
            let (first, second) = client.join(&cx).await.map_err(|error| {
                format!("live HTTP anonymous disablement client failed: {error:?}")
            })??;
            let shutdown = serve.map_err(|error| {
                format!("live HTTP anonymous disablement server failed: {error}")
            })?;
            require_quiescent_http_shutdown(shutdown, "live HTTP anonymous disablement").await?;

            for response in [first, second] {
                let response: JsonRpcResponse = serde_json::from_slice(live_http_response_body(
                    &response,
                )?)
                .map_err(|error| {
                    format!("anonymous disablement response was not valid JSON-RPC: {error}")
                })?;
                if response.id != Some(924_i64.into()) || response.error.is_some() {
                    return Err(format!(
                        "an anonymous stateless POST inherited disabled-component state: {response:?}"
                    ));
                }
            }
            if calls.load(Ordering::Acquire) != 2 {
                return Err(
                    "identical anonymous stateless POSTs did not each enter the disabling handler"
                        .to_owned(),
                );
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_public_final_sampling_json_returns_input_required() {
        run_live_http_test(|cx| async move {
            let (response, calls) = run_live_http_public_final_sampling_json(&cx).await?;
            if response.id != Some(940_i64.into()) {
                return Err(format!(
                    "public final sampling JSON response id was unexpected: {response:?}"
                ));
            }
            if let Some(error) = response.error.as_ref() {
                return Err(format!(
                    "public final sampling JSON POST was cancelled or rejected: {error:?}"
                ));
            }
            if response
                .result
                .as_ref()
                .and_then(|result| result.get("resultType"))
                != Some(&serde_json::json!("input_required"))
            {
                return Err(format!(
                    "public final sampling JSON POST did not yield input_required: {response:?}"
                ));
            }
            if response
                .result
                .as_ref()
                .and_then(|result| result.pointer("/inputRequests/sample/method"))
                != Some(&serde_json::json!("sampling/createMessage"))
            {
                return Err(format!(
                    "public final sampling JSON POST omitted sampling/createMessage: {response:?}"
                ));
            }
            if calls != 1 {
                return Err(format!(
                    "public final sampling handler ran {calls} times instead of once"
                ));
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_mrtr_resumes_server_issued_state_across_separate_stateless_posts() {
        run_live_http_test(|cx| async move {
            let (initial, retry, calls) = run_live_http_mrtr_retry(&cx, "").await?;
            if initial.id != Some(922_i64.into())
                || initial.error.is_some()
                || initial
                    .result
                    .as_ref()
                    .and_then(|result| result.get("resultType"))
                    != Some(&serde_json::json!("input_required"))
            {
                return Err(format!(
                    "initial stateless MRTR POST did not yield input_required: {initial:?}"
                ));
            }
            if retry.id != Some(923_i64.into())
                || retry.error.is_some()
                || retry
                    .result
                    .as_ref()
                    .and_then(|result| result.get("resultType"))
                    != Some(&serde_json::json!("complete"))
                || calls != 2
            {
                return Err(format!(
                    "an owner-bound stateless retry did not resume exactly once (retry={retry:?}, calls={calls})"
                ));
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_mrtr_rejects_foreign_state_across_separate_stateless_posts() {
        run_live_http_test(|cx| async move {
            // This is the identical cross-POST retry flow above, with only
            // the server-issued requestState changed before the retry.
            let (initial, retry, calls) = run_live_http_mrtr_retry(&cx, "-foreign").await?;
            if initial.id != Some(922_i64.into())
                || initial.error.is_some()
                || initial
                    .result
                    .as_ref()
                    .and_then(|result| result.get("resultType"))
                    != Some(&serde_json::json!("input_required"))
            {
                return Err(format!(
                    "foreign-state test initial POST did not yield input_required: {initial:?}"
                ));
            }
            if retry.id != Some(923_i64.into()) || retry.error.is_none() || calls != 1 {
                return Err(format!(
                    "changing only requestState resumed or reentered the handler (retry={retry:?}, calls={calls})"
                ));
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_mrtr_wrong_kind_rejects_without_consuming_stateless_state() {
        run_live_http_test(|cx| async move {
            let calls = Arc::new(AtomicUsize::new(0));
            let bound = Server::new("live-http-mrtr-wrong-kind", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .auth_provider(auth_00_mrtr_provider(true))
                .tool(LiveHttpMrtrTool {
                    name: "live_http_mrtr",
                    calls: Arc::clone(&calls),
                })
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("live HTTP MRTR wrong-kind bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("live HTTP MRTR wrong-kind address failed: {error}"))?;
            let caller_cx = cx.clone();
            let client_calls = Arc::clone(&calls);
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let result = async {
                        let initial = JsonRpcRequest::new(
                            "tools/call",
                            Some(serde_json::json!({
                                "name": "live_http_mrtr",
                                "arguments": {},
                                "_meta": {
                                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                                    "progressToken": "live-http-mrtr-wrong-kind",
                                },
                            })),
                            926_i64,
                        );
                        let initial_body = serde_json::to_vec(&initial).map_err(|error| {
                            format!("MRTR wrong-kind initial request did not serialize: {error}")
                        })?;
                        let initial = live_http_exchange(
                            address,
                            live_http_post(
                                "/mcp",
                                &initial_body,
                                &[
                                    ("Accept", "text/event-stream"),
                                    ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                    ("Mcp-Method", "tools/call"),
                                    ("Mcp-Name", "live_http_mrtr"),
                                    ("Authorization", "Bearer alpha"),
                                ],
                            ),
                        )
                        .await?;
                        let initial = live_http_sse_jsonrpc_response(&initial)?;
                        let request_state = initial
                            .result
                            .as_ref()
                            .and_then(|result| result.get("requestState"))
                            .and_then(serde_json::Value::as_str)
                            .ok_or_else(|| {
                                "MRTR wrong-kind initial response omitted requestState".to_owned()
                            })?
                            .to_owned();
                        let wrong_kind = serde_json::to_value(
                            bidirectional::MrtrInputResponse::sampling(
                                serde_json::from_value(serde_json::json!({
                                    "content": {
                                        "type": "text",
                                        "text": "not a roots result",
                                    },
                                    "role": "assistant",
                                    "model": "test-model",
                                }))
                                .map_err(|error| {
                                    format!(
                                        "MRTR wrong-kind final sampling response failed to decode: {error}"
                                    )
                                })?,
                            )
                            .map_err(|error| {
                                format!("MRTR wrong-kind sampling response failed: {error}")
                            })?,
                        )
                        .map_err(|error| {
                            format!("MRTR wrong-kind sampling response did not serialize: {error}")
                        })?;
                        let wrong_kind = JsonRpcRequest::new(
                            "tools/call",
                            Some(serde_json::json!({
                                "name": "live_http_mrtr",
                                "arguments": {},
                                "inputResponses": {"roots": wrong_kind},
                                "requestState": request_state.clone(),
                                "_meta": {
                                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                                },
                            })),
                            927_i64,
                        );
                        let wrong_kind_body = serde_json::to_vec(&wrong_kind).map_err(|error| {
                            format!("MRTR wrong-kind retry did not serialize: {error}")
                        })?;
                        let wrong_kind = live_http_exchange(
                            address,
                            live_http_post(
                                "/mcp",
                                &wrong_kind_body,
                                &[
                                    ("Accept", "application/json"),
                                    ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                    ("Mcp-Method", "tools/call"),
                                    ("Mcp-Name", "live_http_mrtr"),
                                    ("Authorization", "Bearer alpha"),
                                ],
                            ),
                        )
                        .await?;
                        let wrong_kind: JsonRpcResponse = serde_json::from_slice(
                            live_http_response_body(&wrong_kind)?,
                        )
                        .map_err(|error| {
                            format!(
                                "MRTR wrong-kind response was not valid JSON-RPC: {error}; raw response={}",
                                String::from_utf8_lossy(&wrong_kind),
                            )
                        })?;
                        let calls_after_wrong_kind = client_calls.load(Ordering::Acquire);
                        let roots = serde_json::to_value(
                            bidirectional::MrtrInputResponse::roots(
                                fastmcp_protocol::ListRootsResult::empty(),
                            )
                            .map_err(|error| {
                                format!("MRTR valid roots response failed: {error}")
                            })?,
                        )
                        .map_err(|error| {
                            format!("MRTR valid roots response did not serialize: {error}")
                        })?;
                        let valid = JsonRpcRequest::new(
                            "tools/call",
                            Some(serde_json::json!({
                                "name": "live_http_mrtr",
                                "arguments": {},
                                "inputResponses": {"roots": roots},
                                "requestState": request_state,
                                "_meta": {
                                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                                },
                            })),
                            928_i64,
                        );
                        let valid_body = serde_json::to_vec(&valid).map_err(|error| {
                            format!("MRTR valid retry did not serialize: {error}")
                        })?;
                        let valid = live_http_exchange(
                            address,
                            live_http_post(
                                "/mcp",
                                &valid_body,
                                &[
                                    ("Accept", "application/json"),
                                    ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                    ("Mcp-Method", "tools/call"),
                                    ("Mcp-Name", "live_http_mrtr"),
                                    ("Authorization", "Bearer alpha"),
                                ],
                            ),
                        )
                        .await?;
                        let valid: JsonRpcResponse = serde_json::from_slice(
                            live_http_response_body(&valid)?,
                        )
                        .map_err(|error| {
                            format!("MRTR valid response was not valid JSON-RPC: {error}")
                        })?;
                        Ok::<_, String>((initial, wrong_kind, calls_after_wrong_kind, valid))
                    }
                    .await;
                    caller_cx.cancel_with(
                        CancelKind::User,
                        Some("live HTTP MRTR wrong-kind retry complete"),
                    );
                    result
                })
                .map_err(|error| {
                    format!("live HTTP MRTR wrong-kind client admission failed: {error}")
                })?;

            let serve = bound.serve(&cx).await;
            let (initial, wrong_kind, calls_after_wrong_kind, valid) = client
                .join(&cx)
                .await
                .map_err(|error| format!("live HTTP MRTR wrong-kind client failed: {error:?}"))??;
            let shutdown = serve
                .map_err(|error| format!("live HTTP MRTR wrong-kind server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "live HTTP MRTR wrong-kind").await?;
            if initial.id != Some(926_i64.into())
                || initial.error.is_some()
                || initial
                    .result
                    .as_ref()
                    .and_then(|result| result.get("resultType"))
                    != Some(&serde_json::json!("input_required"))
            {
                return Err(format!(
                    "MRTR wrong-kind initial POST did not yield input_required: {initial:?}"
                ));
            }
            if wrong_kind.id != Some(927_i64.into()) || wrong_kind.error.is_none() {
                return Err(format!(
                    "wrong-kind inputResponses did not yield a JSON-RPC error: {wrong_kind:?}"
                ));
            }
            if calls_after_wrong_kind != 1 {
                return Err(format!(
                    "wrong-kind inputResponses reentered the handler before the valid retry (calls={calls_after_wrong_kind})"
                ));
            }
            if valid.id != Some(928_i64.into())
                || valid.error.is_some()
                || valid
                    .result
                    .as_ref()
                    .and_then(|result| result.get("resultType"))
                    != Some(&serde_json::json!("complete"))
                || calls.load(Ordering::Acquire) != 2
            {
                return Err(format!(
                    "wrong-kind rejection consumed state or valid retry did not resume exactly once (valid={valid:?}, calls={})",
                    calls.load(Ordering::Acquire),
                ));
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_listener_shutdown_invalidates_mrtr_before_a_later_stateless_post() {
        run_live_http_test(|cx| async move {
            let calls = Arc::new(AtomicUsize::new(0));
            let bound = Server::new("live-http-mrtr-shutdown", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .auth_provider(auth_00_mrtr_provider(true))
                .tool(LiveHttpMrtrTool {
                    name: "live_http_mrtr",
                    calls: Arc::clone(&calls),
                })
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("live HTTP MRTR shutdown bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("live HTTP MRTR shutdown address failed: {error}"))?;
            let endpoint = Arc::clone(&bound.endpoint);
            let modern_sessions = Arc::clone(&bound.modern_sessions);
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let result = async {
                        let initial = JsonRpcRequest::new(
                            "tools/call",
                            Some(serde_json::json!({
                                "name": "live_http_mrtr",
                                "arguments": {},
                                "_meta": {
                                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                                    "progressToken": "live-http-mrtr-shutdown",
                                },
                            })),
                            932_i64,
                        );
                        let body = serde_json::to_vec(&initial).map_err(|error| {
                            format!("MRTR shutdown initial request did not serialize: {error}")
                        })?;
                        let response = live_http_exchange(
                            address,
                            live_http_post(
                                "/mcp",
                                &body,
                                &[
                                    ("Accept", "text/event-stream"),
                                    ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                    ("Mcp-Method", "tools/call"),
                                    ("Mcp-Name", "live_http_mrtr"),
                                    ("Authorization", "Bearer alpha"),
                                ],
                            ),
                        )
                        .await?;
                        live_http_sse_jsonrpc_response(&response)
                    }
                    .await;
                    caller_cx.cancel_with(
                        CancelKind::User,
                        Some("live HTTP MRTR shutdown after input_required"),
                    );
                    result
                })
                .map_err(|error| {
                    format!("live HTTP MRTR shutdown client admission failed: {error}")
                })?;

            let serve = bound.serve(&cx).await;
            let initial = client
                .join(&cx)
                .await
                .map_err(|error| format!("live HTTP MRTR shutdown client failed: {error:?}"))??;
            let shutdown =
                serve.map_err(|error| format!("live HTTP MRTR shutdown server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "live HTTP MRTR shutdown").await?;
            if endpoint.server.router.test_active_mrtr_exchange_count() != 0 {
                return Err("listener shutdown retained a stateless MRTR continuation".to_owned());
            }
            let request_state = initial
                .result
                .as_ref()
                .and_then(|result| result.get("requestState"))
                .and_then(serde_json::Value::as_str)
                .ok_or_else(|| "MRTR shutdown initial response omitted requestState".to_owned())?;
            let roots = serde_json::to_value(
                bidirectional::MrtrInputResponse::roots(fastmcp_protocol::ListRootsResult::empty())
                    .map_err(|error| format!("MRTR shutdown roots response failed: {error}"))?,
            )
            .map_err(|error| format!("MRTR shutdown roots response did not serialize: {error}"))?;
            let retry = HttpRequest::new(HttpMethod::Post, "/mcp")
                .with_header("content-type", "application/json")
                .with_header("accept", "application/json")
                .with_header("mcp-protocol-version", MODERN_PROTOCOL_VERSION)
                .with_header("mcp-method", "tools/call")
                .with_header("authorization", "Bearer alpha")
                .with_body(
                    serde_json::to_vec(&JsonRpcRequest::new(
                        "tools/call",
                        Some(serde_json::json!({
                            "name": "live_http_mrtr",
                            "arguments": {},
                            "inputResponses": {"roots": roots},
                            "requestState": request_state,
                            "_meta": {
                                MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                                FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                            },
                        })),
                        933_i64,
                    ))
                    .map_err(|error| format!("MRTR shutdown retry did not serialize: {error}"))?,
                );
            let retry = dispatch_modern_http_request(
                &Cx::for_testing(),
                &endpoint,
                &modern_sessions,
                retry,
            )
            .await;
            let retry: JsonRpcResponse = serde_json::from_slice(&retry.body)
                .map_err(|error| format!("MRTR shutdown retry was not valid JSON-RPC: {error}"))?;
            if retry.id != Some(933_i64.into())
                || retry.error.is_none()
                || calls.load(Ordering::Acquire) != 1
            {
                return Err(format!(
                    "listener shutdown did not invalidate the later stateless MRTR retry (retry={retry:?}, calls={})",
                    calls.load(Ordering::Acquire),
                ));
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_modern_sse_rejects_only_session_id_before_handler() {
        run_live_http_test(|cx| async move {
            let calls = Arc::new(AtomicUsize::new(0));
            let bound = Server::new("live-http-stateless-sse-reject", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .auth_provider(auth_00_mrtr_provider(true))
                .tool(LiveHttpMrtrTool {
                    name: "live_http_mrtr",
                    calls: Arc::clone(&calls),
                })
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("live HTTP MRTR SSE bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("live HTTP MRTR SSE address failed: {error}"))?;
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let initial = JsonRpcRequest::new(
                        "tools/call",
                        Some(serde_json::json!({
                            "name": "live_http_mrtr",
                            "arguments": {},
                            "_meta": {
                                MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                                FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                                "progressToken": "live-http-mrtr-sse",
                            },
                        })),
                        925_i64,
                    );
                    let initial_body = serde_json::to_vec(&initial).map_err(|error| {
                        format!("MRTR SSE initial request did not serialize: {error}")
                    })?;
                    let rejected = live_http_exchange(
                        address,
                        live_http_post(
                            "/mcp",
                            &initial_body,
                            &[
                                ("Accept", "text/event-stream"),
                                ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                ("Mcp-Method", "tools/call"),
                                ("Mcp-Name", "live_http_mrtr"),
                                ("Authorization", "Bearer alpha"),
                                ("MCP-Session-Id", "obsolete-modern-session"),
                            ],
                        ),
                    )
                    .await;
                    caller_cx.cancel_with(
                        CancelKind::User,
                        Some("live HTTP stateless SSE session-header rejection complete"),
                    );
                    rejected
                })
                .map_err(|error| format!("live HTTP MRTR SSE client admission failed: {error}"))?;

            let serve = bound.serve(&cx).await;
            let rejected = client
                .join(&cx)
                .await
                .map_err(|error| format!("live HTTP MRTR SSE client failed: {error:?}"))??;
            let shutdown =
                serve.map_err(|error| format!("live HTTP MRTR SSE server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "live HTTP MRTR SSE").await?;
            if !rejected.starts_with(b"HTTP/1.1 400") || calls.load(Ordering::Acquire) != 0 {
                return Err("adding only MCP-Session-Id admitted a modern SSE handler".to_owned());
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_modern_discovery_does_not_retain_a_session_after_shutdown() {
        run_live_http_test(|cx| async move {
            let bound = Server::new("live-http-stateless-discovery", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("live HTTP stateless discovery bind failed: {error}"))?;
            let address = bound.local_addr().map_err(|error| {
                format!("live HTTP stateless discovery address failed: {error}")
            })?;
            let modern_sessions = Arc::clone(&bound.modern_sessions);
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let discovery = JsonRpcRequest::new(
                        SERVER_DISCOVER_METHOD,
                        Some(serde_json::json!({
                            "_meta": {
                                MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                                FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                            },
                        })),
                        931_i64,
                    );
                    let discovery_body = serde_json::to_vec(&discovery).map_err(|error| {
                        format!("stateless discovery did not serialize: {error}")
                    })?;
                    let discovery = live_http_exchange(
                        address,
                        live_http_post(
                            "/mcp",
                            &discovery_body,
                            &[
                                ("Accept", "application/json"),
                                ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                ("Mcp-Method", SERVER_DISCOVER_METHOD),
                            ],
                        ),
                    )
                    .await?;
                    caller_cx.cancel_with(
                        CancelKind::User,
                        Some("live HTTP stateless discovery complete"),
                    );
                    Ok::<_, String>(discovery)
                })
                .map_err(|error| {
                    format!("live HTTP stateless discovery client admission failed: {error}")
                })?;

            let serve = bound.serve(&cx).await;
            let response = client.join(&cx).await.map_err(|error| {
                format!("live HTTP stateless discovery client failed: {error:?}")
            })??;
            let shutdown = serve
                .map_err(|error| format!("live HTTP stateless discovery server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "live HTTP stateless discovery").await?;
            if !response.starts_with(b"HTTP/1.1 200")
                || live_http_response_header(&response, "mcp-session-id").is_ok()
            {
                return Err("modern discovery issued a session identifier".to_owned());
            }
            if !modern_sessions
                .sessions
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .is_empty()
            {
                return Err("listener shutdown retained a modern HTTP session".to_owned());
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_protocol_admission_preserves_jsonrpc_when_only_version_header_differs() {
        run_live_http_test(|cx| async move {
            let bound = Server::new("live-http-protocol-admission", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("protocol-admission HTTP bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("protocol-admission HTTP address failed: {error}"))?;
            let request = JsonRpcRequest::new(
                SERVER_DISCOVER_METHOD,
                Some(serde_json::json!({
                    "_meta": {
                        MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                        FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                    },
                })),
                814_i64,
            );
            let body = serde_json::to_vec(&request).map_err(|error| {
                format!("protocol-admission request did not serialize: {error}")
            })?;
            let accepted = live_http_post(
                "/mcp",
                &body,
                &[
                    ("Accept", "application/json"),
                    ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                    ("Mcp-Method", SERVER_DISCOVER_METHOD),
                ],
            );
            // This has the same JSON-RPC body and all the same HTTP headers
            // except the final protocol-version mirror.
            let rejected = live_http_post(
                "/mcp",
                &body,
                &[
                    ("Accept", "application/json"),
                    ("MCP-Protocol-Version", "2025-11-25"),
                    ("Mcp-Method", SERVER_DISCOVER_METHOD),
                ],
            );
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let result = async {
                        let accepted = live_http_exchange(address, accepted).await?;
                        let rejected = live_http_exchange(address, rejected).await?;
                        Ok::<_, String>((accepted, rejected))
                    }
                    .await;
                    caller_cx.cancel_with(
                        CancelKind::User,
                        Some("protocol-admission loopback complete"),
                    );
                    result
                })
                .map_err(|error| format!("protocol-admission client admission failed: {error}"))?;

            let serve = bound.serve(&cx).await;
            let (accepted, rejected) = client
                .join(&cx)
                .await
                .map_err(|error| format!("protocol-admission client failed: {error:?}"))??;
            let shutdown =
                serve.map_err(|error| format!("protocol-admission server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "protocol admission").await?;

            if !accepted.starts_with(b"HTTP/1.1 200") {
                return Err(format!(
                    "matching final protocol-version request was not accepted: {accepted:?}"
                ));
            }
            let accepted: JsonRpcResponse =
                serde_json::from_slice(live_http_response_body(&accepted)?).map_err(|error| {
                    format!("accepted protocol-admission response was invalid: {error}")
                })?;
            if accepted.id != Some(814_i64.into()) || accepted.error.is_some() {
                return Err(format!(
                    "matching final protocol-version request did not dispatch: {accepted:?}"
                ));
            }

            if !rejected.starts_with(b"HTTP/1.1 400") {
                return Err(format!(
                    "mismatched final protocol-version request did not return HTTP 400: {rejected:?}"
                ));
            }
            let rejected: JsonRpcResponse =
                serde_json::from_slice(live_http_response_body(&rejected)?).map_err(|error| {
                    format!("rejected protocol-admission response was invalid: {error}")
                })?;
            if rejected.id != Some(814_i64.into())
                || rejected.result.is_some()
                || rejected
                    .error
                    .as_ref()
                    .and_then(|error| error.code.as_i32())
                    != Some(fastmcp_protocol::HEADER_MISMATCH_ERROR_CODE)
                || rejected
                    .error
                    .as_ref()
                    .and_then(|error| error.data.as_ref())
                    .is_some()
            {
                return Err(format!(
                    "mismatched final protocol-version request did not retain its canonical JSON-RPC error: {rejected:?}"
                ));
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_dual_accept_sse_flushes_progress_log_and_terminal_once() {
        run_live_http_test(|cx| async move {
            let calls = Arc::new(AtomicUsize::new(0));
            let bound = Server::new("live-modern-sse-frames", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .log_level(Level::Debug)
                .tool(HttpRequestScopedProgressTool {
                    calls: Arc::clone(&calls),
                })
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("live modern SSE bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("live modern SSE address failed: {error}"))?;
            let request = JsonRpcRequest::new(
                "tools/call",
                Some(serde_json::json!({
                    "name": "http_request_scoped_progress",
                    "arguments": {},
                    "_meta": {
                        MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                        FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                        "progressToken": "live-http-progress",
                        "io.modelcontextprotocol/logLevel": "info",
                    },
                })),
                813_i64,
            );
            let body = serde_json::to_vec(&request)
                .map_err(|error| format!("live SSE request did not serialize: {error}"))?;
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let request = live_http_post(
                        "/mcp",
                        &body,
                        &[
                            ("Accept", "application/json, text/event-stream; Q=1."),
                            ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                            ("Mcp-Method", "tools/call"),
                            ("Mcp-Name", "http_request_scoped_progress"),
                        ],
                    );
                    let deadline = caller_cx
                        .now()
                        .saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
                    let mut stream =
                        asupersync::time::timeout_at(deadline, AsyncTcpStream::connect(address))
                            .await
                            .map_err(|_| {
                                live_http_test_timeout("live modern SSE client connection")
                            })?
                            .map_err(|error| format!("live modern SSE connect failed: {error}"))?;
                    asupersync::time::timeout_at(deadline, stream.write_all(&request))
                        .await
                        .map_err(|_| live_http_test_timeout("live modern SSE request write"))?
                        .map_err(|error| format!("live modern SSE write failed: {error}"))?;
                    asupersync::time::timeout_at(deadline, stream.flush())
                        .await
                        .map_err(|_| live_http_test_timeout("live modern SSE request flush"))?
                        .map_err(|error| format!("live modern SSE flush failed: {error}"))?;
                    let mut received = Vec::new();
                    read_live_http_until(&mut stream, &mut received, b"notifications/progress")
                        .await?;
                    read_live_http_until(&mut stream, &mut received, b"notifications/message")
                        .await?;
                    read_live_http_until(&mut stream, &mut received, b"\"id\":813").await?;
                    read_live_http_to_end(
                        &mut stream,
                        &mut received,
                        "live modern SSE terminal EOF",
                    )
                    .await?;
                    caller_cx.cancel_with(CancelKind::User, Some("modern SSE stream complete"));
                    Ok::<_, String>(received)
                })
                .map_err(|error| format!("live modern SSE client admission failed: {error}"))?;

            let serve = bound.serve(&cx).await;
            let response = client
                .join(&cx)
                .await
                .map_err(|error| format!("live modern SSE client failed: {error:?}"))??;
            let shutdown =
                serve.map_err(|error| format!("live modern SSE server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "live modern SSE").await?;
            let response_text = std::str::from_utf8(&response)
                .map_err(|error| format!("live modern SSE response was not UTF-8: {error}"))?;
            if !response_text.starts_with("HTTP/1.1 200")
                || !response_text
                    .to_ascii_lowercase()
                    .contains("content-type: text/event-stream")
            {
                return Err(format!(
                    "live modern SSE response head was unexpected: {response_text}"
                ));
            }
            let messages = live_http_chunked_sse_messages(&response)?;
            let [progress, log, terminal] = messages.as_slice() else {
                return Err(format!(
                    "live modern SSE emitted {} frames instead of progress, log, and response",
                    messages.len()
                ));
            };
            let JsonRpcMessage::Request(progress) = progress else {
                return Err("first live SSE frame was not a notification".to_owned());
            };
            let ServerNotification::Progress(progress) = ServerNotification::decode(progress)
                .map_err(|error| format!("first live SSE frame was invalid: {error}"))?
            else {
                return Err("first live SSE frame was not notifications/progress".to_owned());
            };
            if progress.progress_token != ProgressMarker::String("live-http-progress".to_owned())
                || progress.progress.as_str() != "12000"
                || progress.total.as_ref().map(|total| total.as_str()) != Some("11999")
                || progress.message.as_deref() != Some("latest")
            {
                return Err(format!(
                    "live SSE progress frame was not the coalesced update: {progress:?}"
                ));
            }
            let JsonRpcMessage::Request(log) = log else {
                return Err("second live SSE frame was not a notification".to_owned());
            };
            if !matches!(
                ServerNotification::decode(log),
                Ok(ServerNotification::Message(_))
            ) {
                return Err("second live SSE frame was not notifications/message".to_owned());
            }
            if !matches!(
                terminal,
                JsonRpcMessage::Response(response)
                    if response.id == Some(813_i64.into()) && response.error.is_none()
            ) {
                return Err("third live SSE frame was not the one terminal response".to_owned());
            }
            if calls.load(Ordering::Acquire) != 1 {
                return Err("live modern SSE handler did not execute exactly once".to_owned());
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_sse_handler_admission_preserves_parameter_header_rejection() {
        #[derive(Clone)]
        struct HeaderAdmissionProbe {
            middleware_calls: Arc<AtomicUsize>,
            handler_calls: Arc<AtomicUsize>,
        }

        impl Middleware for HeaderAdmissionProbe {
            fn on_request(
                &self,
                ctx: &McpContext,
                _request: &JsonRpcRequest,
            ) -> McpResult<MiddlewareDecision> {
                self.middleware_calls.fetch_add(1, Ordering::AcqRel);
                ctx.report_progress(0.25, Some("before parameter-header admission"));
                Ok(MiddlewareDecision::Continue)
            }
        }

        impl ToolHandler for HeaderAdmissionProbe {
            fn definition(&self) -> Tool {
                Tool {
                    name: "http_header_admission_probe".to_owned(),
                    description: None,
                    input_schema: serde_json::json!({
                        "type": "object",
                        "properties": {
                            "region": {"type": "string", "x-mcp-header": "Region"}
                        },
                        "required": ["region"]
                    }),
                    output_schema: None,
                    icon: None,
                    version: None,
                    tags: Vec::new(),
                    annotations: None,
                }
            }

            // The annotated `region` is what this test exists to exercise, so
            // the projection must be admitted rather than dropped. Derive the
            // review from this handler's own schema: a revision hard-coded
            // here would go stale the next time the schema is touched.
            fn header_exposure_reviews(
                &self,
            ) -> Vec<fastmcp_protocol::http_headers::NonSensitiveHeaderExposure> {
                let definition = self.definition();
                let revision = fastmcp_protocol::http_headers::ToolSchemaRevision::of(
                    &definition.input_schema,
                )
                .expect("the probe's bounded input schema has a revision");
                vec![
                    fastmcp_protocol::http_headers::NonSensitiveHeaderExposure::new(
                        definition.name,
                        revision,
                        ["region"],
                    ),
                ]
            }

            fn call(
                &self,
                _ctx: &McpContext,
                _arguments: serde_json::Value,
            ) -> McpResult<Vec<Content>> {
                self.handler_calls.fetch_add(1, Ordering::AcqRel);
                Ok(vec![Content::text("admitted header")])
            }
        }

        run_live_http_test(|cx| async move {
            let probe = HeaderAdmissionProbe {
                middleware_calls: Arc::new(AtomicUsize::new(0)),
                handler_calls: Arc::new(AtomicUsize::new(0)),
            };
            let bound = Server::new("live-http-handler-admission", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .middleware(probe.clone())
                .tool(probe.clone())
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("handler admission bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("handler admission address failed: {error}"))?;
            let request = JsonRpcRequest::new(
                "tools/call",
                Some(serde_json::json!({
                    "name": "http_header_admission_probe",
                    "arguments": {"region": "west"},
                    "_meta": {
                        MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                        FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                        "progressToken": "header-admission-progress",
                    },
                })),
                839_i64,
            );
            let body = serde_json::to_vec(&request)
                .map_err(|error| format!("handler admission request failed: {error}"))?;
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let result = async {
                        let mut responses = Vec::new();
                        for region in ["west", "east"] {
                            responses.push(
                                live_http_exchange(
                                    address,
                                    live_http_post(
                                        "/mcp",
                                        &body,
                                        &[
                                            ("Accept", "text/event-stream"),
                                            ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                            ("Mcp-Method", "tools/call"),
                                            ("Mcp-Name", "http_header_admission_probe"),
                                            ("Mcp-Param-Region", region),
                                        ],
                                    ),
                                )
                                .await?,
                            );
                        }
                        Ok::<_, String>(responses)
                    }
                    .await;
                    caller_cx
                        .cancel_with(CancelKind::User, Some("handler admission proof complete"));
                    result
                })
                .map_err(|error| format!("handler admission client spawn failed: {error}"))?;
            let serve = bound.serve(&cx).await;
            let responses = client
                .join(&cx)
                .await
                .map_err(|error| format!("handler admission client failed: {error:?}"))??;
            let shutdown =
                serve.map_err(|error| format!("handler admission server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "handler admission").await?;
            let [accepted, rejected] = responses.as_slice() else {
                return Err("the paired handler admission responses are missing".to_owned());
            };
            if !accepted.starts_with(b"HTTP/1.1 200")
                || live_http_response_header(accepted, "content-type")? != "text/event-stream"
            {
                return Err("matching parameter header did not admit SSE".to_owned());
            }
            let messages = live_http_chunked_sse_messages(accepted)?;
            if !messages.iter().any(|message| matches!(message,
                JsonRpcMessage::Request(notification) if notification.method == "notifications/progress"))
                || !messages.iter().any(|message| matches!(message,
                    JsonRpcMessage::Response(response) if response.id == Some(839_i64.into()) && response.error.is_none()))
            {
                return Err("admitted tool lost middleware progress or its terminal result".to_owned());
            }
            if !rejected.starts_with(b"HTTP/1.1 400")
                || live_http_response_header(rejected, "content-type")? != "application/json"
                || rejected
                    .windows(b"event: message".len())
                    .any(|window| window == b"event: message")
            {
                return Err(
                    "mismatched parameter header committed SSE before canonical JSON400".to_owned(),
                );
            }
            let rejected: JsonRpcResponse =
                serde_json::from_slice(live_http_response_body(rejected)?)
                    .map_err(|error| format!("header rejection was not JSON-RPC: {error}"))?;
            if rejected.id != Some(839_i64.into())
                || rejected
                    .error
                    .as_ref()
                    .and_then(|error| error.code.as_i32())
                    != Some(fastmcp_protocol::HEADER_MISMATCH_ERROR_CODE)
                || rejected
                    .error
                    .as_ref()
                    .and_then(|error| error.data.as_ref())
                    .is_some()
                || probe.middleware_calls.load(Ordering::Acquire) != 2
                || probe.handler_calls.load(Ordering::Acquire) != 1
            {
                return Err(
                    "header mismatch changed its canonical error or reached the handler".to_owned(),
                );
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_sse_middleware_progress_then_canonical_capability_error_is_json_400() {
        run_live_http_test(|cx| async move {
            let canonical_data = serde_json::json!({
                "requiredCapabilities": {
                    "extensions": { "io.modelcontextprotocol/tasks": {} }
                }
            });
            let bound = Server::new("live-http-middleware-capability-sse", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .mask_error_details(false)
                .middleware(HttpCapabilityErrorMiddleware {
                    data: canonical_data.clone(),
                    emit_progress: true,
                })
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("live middleware SSE bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("live middleware SSE address failed: {error}"))?;
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let request = JsonRpcRequest::new(
                        SERVER_DISCOVER_METHOD,
                        Some(serde_json::json!({
                            "_meta": {
                                MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                                FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                                "progressToken": "live-middleware-capability-progress",
                            },
                        })),
                        835_i64,
                    );
                    let body = serde_json::to_vec(&request).map_err(|error| {
                        format!("live middleware capability request did not serialize: {error}")
                    })?;
                    let response = live_http_exchange(
                        address,
                        live_http_post(
                            "/mcp",
                            &body,
                            &[
                                ("Accept", "text/event-stream"),
                                ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                ("Mcp-Method", SERVER_DISCOVER_METHOD),
                            ],
                        ),
                    )
                    .await;
                    caller_cx.cancel_with(
                        CancelKind::User,
                        Some("live middleware capability SSE rejection complete"),
                    );
                    response
                })
                .map_err(|error| format!("live middleware SSE client admission failed: {error}"))?;

            let serve = bound.serve(&cx).await;
            let response = client
                .join(&cx)
                .await
                .map_err(|error| format!("live middleware SSE client failed: {error:?}"))??;
            let shutdown =
                serve.map_err(|error| format!("live middleware SSE server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "live middleware SSE").await?;

            if !response.starts_with(b"HTTP/1.1 400")
                || live_http_response_header(&response, "content-type")
                    .ok()
                    .as_deref()
                    != Some("application/json")
            {
                return Err(format!(
                    "canonical middleware capability error did not elect JSON HTTP 400: {response:?}"
                ));
            }
            if response
                .windows(b"event: message".len())
                .any(|window| window == b"event: message")
            {
                return Err(
                    "progress-before-error middleware committed an SSE event before JSON 400"
                        .to_owned(),
                );
            }
            let response: JsonRpcResponse =
                serde_json::from_slice(live_http_response_body(&response)?)
                    .map_err(|error| format!("middleware JSON 400 was not JSON-RPC: {error}"))?;
            let error = response
                .error
                .ok_or_else(|| "middleware JSON 400 omitted its JSON-RPC error".to_owned())?;
            if response.id != Some(835_i64.into())
                || error.code.as_i32() != Some(MISSING_REQUIRED_CLIENT_CAPABILITY_ERROR_CODE)
                || error.data.as_ref() != Some(&canonical_data)
            {
                return Err(format!(
                    "middleware JSON 400 did not retain canonical capability error: {error:?}"
                ));
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_subscription_middleware_capability_error_is_json_400_before_sse_head() {
        run_live_http_test(|cx| async move {
            let canonical_data = serde_json::json!({
                "requiredCapabilities": {
                    "extensions": { "io.modelcontextprotocol/tasks": {} }
                }
            });
            let bound = Server::new("live-http-subscription-middleware-capability", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .mask_error_details(false)
                .middleware(HttpCapabilityErrorMiddleware {
                    data: canonical_data.clone(),
                    emit_progress: true,
                })
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("live subscription middleware bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("live subscription middleware address failed: {error}"))?;
            let server = Arc::clone(&bound.endpoint.server);
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let request = JsonRpcRequest::new(
                        SUBSCRIPTIONS_LISTEN,
                        Some(serde_json::json!({
                            "_meta": {
                                MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                                FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                                "progressToken": "live-subscription-middleware-progress",
                            },
                            "notifications": { "toolsListChanged": true },
                        })),
                        836_i64,
                    );
                    let body = serde_json::to_vec(&request).map_err(|error| {
                        format!("live subscription middleware request did not serialize: {error}")
                    })?;
                    let response = live_http_exchange(
                        address,
                        live_http_post(
                            "/mcp",
                            &body,
                            &[
                                ("Accept", "text/event-stream"),
                                ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                ("Mcp-Method", SUBSCRIPTIONS_LISTEN),
                            ],
                        ),
                    )
                    .await;
                    caller_cx.cancel_with(
                        CancelKind::User,
                        Some("live subscription middleware capability rejection complete"),
                    );
                    response
                })
                .map_err(|error| {
                    format!("live subscription middleware client admission failed: {error}")
                })?;

            let serve = bound.serve(&cx).await;
            let response = client.join(&cx).await.map_err(|error| {
                format!("live subscription middleware client failed: {error:?}")
            })??;
            let shutdown = serve
                .map_err(|error| format!("live subscription middleware server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "live subscription middleware").await?;

            if !response.starts_with(b"HTTP/1.1 400")
                || live_http_response_header(&response, "content-type")
                    .ok()
                    .as_deref()
                    != Some("application/json")
            {
                return Err(format!(
                    "subscription canonical middleware error did not elect JSON HTTP 400: {response:?}"
                ));
            }
            if response
                .windows(b"event: message".len())
                .any(|window| window == b"event: message")
                || response
                    .windows(b"notifications/subscriptions/acknowledged".len())
                    .any(|window| window == b"notifications/subscriptions/acknowledged")
            {
                return Err(
                    "subscription middleware capability rejection committed an SSE head or event"
                        .to_owned(),
                );
            }
            let response: JsonRpcResponse =
                serde_json::from_slice(live_http_response_body(&response)?).map_err(|error| {
                    format!("subscription middleware JSON 400 was not JSON-RPC: {error}")
                })?;
            let error = response.error.ok_or_else(|| {
                "subscription middleware JSON 400 omitted its JSON-RPC error".to_owned()
            })?;
            if response.id != Some(836_i64.into())
                || error.code.as_i32() != Some(MISSING_REQUIRED_CLIENT_CAPABILITY_ERROR_CODE)
                || error.data.as_ref() != Some(&canonical_data)
            {
                return Err(format!(
                    "subscription middleware JSON 400 did not retain canonical capability error: {error:?}"
                ));
            }
            if !server
                .final_subscriptions
                .inner
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .entries
                .is_empty()
            {
                return Err(
                    "subscription middleware rejection mutated the final subscription registry"
                        .to_owned(),
                );
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_subscription_acknowledgement_precedes_deferred_progress() {
        run_live_http_test(|cx| async move {
            let bound = Server::new("live-http-subscription-acknowledgement-order", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .middleware(HttpSubscriptionProgressMiddleware)
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("subscription ordering bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("subscription ordering address failed: {error}"))?;
            let caller_cx = cx.clone();
            let controller = thread::spawn(move || -> Result<Vec<u8>, String> {
                struct CancelServerOnDrop(Cx);

                impl Drop for CancelServerOnDrop {
                    fn drop(&mut self) {
                        self.0.cancel_with(
                            CancelKind::User,
                            Some("subscription acknowledgement ordering controller finished"),
                        );
                    }
                }

                let shutdown_cx = caller_cx.clone();
                let _server_cancellation = CancelServerOnDrop(caller_cx);
                let listen = JsonRpcRequest::new(
                    SUBSCRIPTIONS_LISTEN,
                    Some(serde_json::json!({
                        "_meta": {
                            MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                            FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                            "progressToken": "subscription-before-ack",
                        },
                        "notifications": {"toolsListChanged": true},
                    })),
                    RequestId::Number(937),
                );
                let body = serde_json::to_vec(&listen).map_err(|error| {
                    format!("subscription ordering request did not serialize: {error}")
                })?;
                let request = live_http_post(
                    "/mcp",
                    &body,
                    &[
                        ("Accept", "text/event-stream"),
                        ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                        ("Mcp-Method", SUBSCRIPTIONS_LISTEN),
                    ],
                );
                let mut stream = std::net::TcpStream::connect(address)
                    .map_err(|error| format!("subscription ordering connect failed: {error}"))?;
                stream
                    .set_read_timeout(Some(Duration::from_secs(2)))
                    .map_err(|error| {
                        format!("subscription ordering timeout setup failed: {error}")
                    })?;
                std::io::Write::write_all(&mut stream, &request)
                    .map_err(|error| format!("subscription ordering write failed: {error}"))?;
                std::io::Write::flush(&mut stream)
                    .map_err(|error| format!("subscription ordering flush failed: {error}"))?;
                stream
                    .shutdown(std::net::Shutdown::Write)
                    .map_err(|error| {
                        format!("subscription ordering write-half close failed: {error}")
                    })?;

                let mut received = Vec::new();
                while !received
                    .windows(b"notifications/subscriptions/acknowledged".len())
                    .any(|window| window == b"notifications/subscriptions/acknowledged")
                    || !received
                        .windows(b"notifications/progress".len())
                        .any(|window| window == b"notifications/progress")
                {
                    let mut chunk = [0_u8; 2048];
                    let count = std::io::Read::read(&mut stream, &mut chunk)
                        .map_err(|error| format!("subscription ordering read failed: {error}"))?;
                    if count == 0 {
                        return Err(
                            "subscription stream closed before acknowledgement and progress"
                                .to_owned(),
                        );
                    }
                    received.extend_from_slice(&chunk[..count]);
                }
                shutdown_cx.cancel_with(
                    CancelKind::User,
                    Some("subscription acknowledgement ordering graceful shutdown requested"),
                );
                std::io::Read::read_to_end(&mut stream, &mut received).map_err(|error| {
                    format!("subscription ordering terminal read failed: {error}")
                })?;
                Ok(received)
            });

            let shutdown = bound
                .serve(&cx)
                .await
                .map_err(|error| format!("subscription ordering server failed: {error}"))?;
            let response = controller
                .join()
                .map_err(|_| "subscription ordering controller panicked".to_owned())??;
            require_quiescent_http_shutdown(shutdown, "subscription acknowledgement ordering")
                .await?;

            let messages = live_http_chunked_sse_messages(&response)?;
            let Some((first, remaining)) = messages.split_first() else {
                return Err("subscription ordering emitted no SSE frames".to_owned());
            };
            let JsonRpcMessage::Request(acknowledgement) = first else {
                return Err("subscription acknowledgement was not the first SSE frame".to_owned());
            };
            if !matches!(
                ServerNotification::decode(acknowledgement),
                Ok(ServerNotification::SubscriptionsAcknowledged(_))
            ) {
                return Err(
                    "first subscription SSE frame was not subscriptions/acknowledged".to_owned(),
                );
            }
            let progress_count = remaining
                .iter()
                .filter(|message| {
                    matches!(
                        message,
                        JsonRpcMessage::Request(notification)
                            if matches!(
                                ServerNotification::decode(notification),
                                Ok(ServerNotification::Progress(progress))
                                    if progress.progress_token
                                        == ProgressMarker::String("subscription-before-ack".to_owned())
                            )
                    )
                })
                .count();
            if progress_count != 1 {
                return Err(format!(
                    "subscription deferred progress was not flushed exactly once after acknowledgement: {messages:?}"
                ));
            }
            if !remaining.iter().any(|message| {
                matches!(
                    message,
                    JsonRpcMessage::Response(response)
                        if response.id == Some(RequestId::Number(937))
                            && final_subscription_completion_response(response)
                )
            }) {
                return Err(
                    "subscription ordering stream omitted its graceful terminal response"
                        .to_owned(),
                );
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_post_admission_canonical_error_is_one_terminal_sse_response() {
        run_live_http_test(|cx| async move {
            let canonical_data = serde_json::json!({
                "requiredCapabilities": {
                    "extensions": { "io.modelcontextprotocol/tasks": {} }
                }
            });
            let bound = Server::new("live-http-post-admission-capability-error", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .mask_error_details(false)
                .middleware(HttpSubscriptionResponseCapabilityErrorMiddleware {
                    data: canonical_data.clone(),
                })
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("post-admission capability bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("post-admission capability address failed: {error}"))?;
            let caller_cx = cx.clone();
            let controller = thread::spawn(move || -> Result<Vec<u8>, String> {
                struct CancelServerOnDrop(Cx);

                impl Drop for CancelServerOnDrop {
                    fn drop(&mut self) {
                        self.0.cancel_with(
                            CancelKind::User,
                            Some("post-admission capability controller finished"),
                        );
                    }
                }

                let shutdown_cx = caller_cx.clone();
                let _server_cancellation = CancelServerOnDrop(caller_cx);
                let listen = JsonRpcRequest::new(
                    SUBSCRIPTIONS_LISTEN,
                    Some(serde_json::json!({
                        "_meta": {
                            MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                            FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                        },
                        "notifications": {"toolsListChanged": true},
                    })),
                    RequestId::Number(938),
                );
                let body = serde_json::to_vec(&listen).map_err(|error| {
                    format!("post-admission capability request did not serialize: {error}")
                })?;
                let request = live_http_post(
                    "/mcp",
                    &body,
                    &[
                        ("Accept", "text/event-stream"),
                        ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                        ("Mcp-Method", SUBSCRIPTIONS_LISTEN),
                    ],
                );
                let mut stream = std::net::TcpStream::connect(address).map_err(|error| {
                    format!("post-admission capability connect failed: {error}")
                })?;
                stream
                    .set_read_timeout(Some(Duration::from_secs(2)))
                    .map_err(|error| {
                        format!("post-admission capability timeout setup failed: {error}")
                    })?;
                std::io::Write::write_all(&mut stream, &request)
                    .map_err(|error| format!("post-admission capability write failed: {error}"))?;
                std::io::Write::flush(&mut stream)
                    .map_err(|error| format!("post-admission capability flush failed: {error}"))?;
                stream
                    .shutdown(std::net::Shutdown::Write)
                    .map_err(|error| {
                        format!("post-admission capability write-half close failed: {error}")
                    })?;
                let mut received = Vec::new();
                while !received
                    .windows(b"notifications/subscriptions/acknowledged".len())
                    .any(|window| window == b"notifications/subscriptions/acknowledged")
                {
                    let mut chunk = [0_u8; 2048];
                    let count = std::io::Read::read(&mut stream, &mut chunk).map_err(|error| {
                        format!("post-admission capability acknowledgement read failed: {error}")
                    })?;
                    if count == 0 {
                        return Err(
                            "post-admission capability stream closed before acknowledgement"
                                .to_owned(),
                        );
                    }
                    received.extend_from_slice(&chunk[..count]);
                }
                shutdown_cx.cancel_with(
                    CancelKind::User,
                    Some("post-admission capability graceful shutdown requested"),
                );
                std::io::Read::read_to_end(&mut stream, &mut received).map_err(|error| {
                    format!("post-admission capability terminal read failed: {error}")
                })?;
                Ok(received)
            });

            let shutdown = bound
                .serve(&cx)
                .await
                .map_err(|error| format!("post-admission capability server failed: {error}"))?;
            let response = controller
                .join()
                .map_err(|_| "post-admission capability controller panicked".to_owned())??;
            require_quiescent_http_shutdown(shutdown, "post-admission canonical error").await?;

            if !response.starts_with(b"HTTP/1.1 200")
                || live_http_response_header(&response, "content-type")
                    .ok()
                    .as_deref()
                    != Some("text/event-stream")
            {
                return Err(format!(
                    "post-admission canonical error did not retain its elected SSE representation: {response:?}"
                ));
            }
            let messages = live_http_chunked_sse_messages(&response)?;
            let [acknowledgement, terminal] = messages.as_slice() else {
                return Err(format!(
                    "post-admission canonical error emitted {} frames instead of acknowledgement plus one terminal response",
                    messages.len()
                ));
            };
            let JsonRpcMessage::Request(acknowledgement) = acknowledgement else {
                return Err(
                    "post-admission canonical stream did not start with acknowledgement".to_owned(),
                );
            };
            if !matches!(
                ServerNotification::decode(acknowledgement),
                Ok(ServerNotification::SubscriptionsAcknowledged(_))
            ) {
                return Err(
                    "post-admission canonical stream first frame was not acknowledgement"
                        .to_owned(),
                );
            }
            let JsonRpcMessage::Response(terminal) = terminal else {
                return Err(
                    "post-admission canonical stream terminal was not a response".to_owned(),
                );
            };
            let Some(error) = terminal.error.as_ref() else {
                return Err("post-admission canonical terminal omitted its error".to_owned());
            };
            if terminal.id != Some(RequestId::Number(938))
                || error.code.as_i32() != Some(MISSING_REQUIRED_CLIENT_CAPABILITY_ERROR_CODE)
                || error.message != "Required client capability is missing"
                || error.data.as_ref() != Some(&canonical_data)
            {
                return Err(format!(
                    "post-admission canonical terminal did not retain the exact error: {terminal:?}"
                ));
            }
            Ok(())
        });
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn live_http_sse_create_task_false_flushes_progress_once_and_completes() {
        run_live_http_test(|cx| async move {
            let calls = Arc::new(AtomicUsize::new(0));
            let delivered = Arc::new(Mutex::new(Vec::new()));
            let bound = Server::new("live-http-task-outcome-sse", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .tool(HttpConditionalTaskOutcomeTool {
                    calls: Arc::clone(&calls),
                })
                .final_tasks(final_tasks_test_runtime(Arc::clone(&delivered)))
                .expect("final Tasks runtime must install for live complete outcome")
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("live createTask:false SSE bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("live createTask:false SSE address failed: {error}"))?;
            let request = final_http_task_outcome_request(false, true);
            let body = serde_json::to_vec(&request).map_err(|error| {
                format!("live createTask:false request did not serialize: {error}")
            })?;
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let response = live_http_exchange(
                        address,
                        live_http_post(
                            "/mcp",
                            &body,
                            &[
                                ("Accept", "text/event-stream"),
                                ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                ("Mcp-Method", "tools/call"),
                                ("Mcp-Name", "durable_final_task"),
                            ],
                        ),
                    )
                    .await;
                    caller_cx.cancel_with(
                        CancelKind::User,
                        Some("live createTask:false SSE response complete"),
                    );
                    response
                })
                .map_err(|error| {
                    format!("live createTask:false SSE client admission failed: {error}")
                })?;

            let serve = bound.serve(&cx).await;
            let response = client
                .join(&cx)
                .await
                .map_err(|error| format!("live createTask:false SSE client failed: {error:?}"))??;
            let shutdown = serve
                .map_err(|error| format!("live createTask:false SSE server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "live createTask:false SSE").await?;

            if !response.starts_with(b"HTTP/1.1 200")
                || live_http_response_header(&response, "content-type")
                    .ok()
                    .as_deref()
                    != Some("text/event-stream")
            {
                return Err(format!(
                    "createTask:false did not elect its normal SSE representation: {response:?}"
                ));
            }
            let messages = live_http_chunked_sse_messages(&response)?;
            let [progress, terminal] = messages.as_slice() else {
                return Err(format!(
                    "createTask:false emitted {} frames instead of one progress and terminal response",
                    messages.len()
                ));
            };
            let JsonRpcMessage::Request(progress) = progress else {
                return Err("createTask:false first frame was not progress".to_owned());
            };
            let ServerNotification::Progress(progress) = ServerNotification::decode(progress)
                .map_err(|error| format!("createTask:false progress frame was invalid: {error}"))?
            else {
                return Err(
                    "createTask:false first frame was not notifications/progress".to_owned(),
                );
            };
            if progress.progress_token
                != ProgressMarker::String("missing-task-capability".to_owned())
            {
                return Err(format!(
                    "createTask:false progress frame was not retained exactly once: {progress:?}"
                ));
            }
            if !matches!(
                terminal,
                JsonRpcMessage::Response(response)
                    if response.id == Some(81_i64.into())
                        && response.error.is_none()
                        && response
                            .result
                            .as_ref()
                            .and_then(|result| result.get("resultType"))
                            == Some(&serde_json::json!("complete"))
            ) {
                return Err("createTask:false terminal frame was not complete".to_owned());
            }
            if calls.load(Ordering::Acquire) != 1
                || !delivered
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .is_empty()
            {
                return Err("createTask:false mutated a Task or skipped its handler".to_owned());
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_sse_write_half_close_before_election_preserves_response() {
        run_live_http_test(|cx| async move {
            const REQUEST_ID: u64 = 815;
            let control = Arc::new(LiveModernControl::default());
            let bound = Server::new("live-http-sse-write-half-close", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .tool(LiveModernControlledTool {
                    control: Arc::clone(&control),
                })
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("write-half SSE bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("write-half SSE address failed: {error}"))?;
            let caller_cx = cx.clone();
            let controller_control = Arc::clone(&control);
            let controller = thread::spawn(move || -> Result<Vec<u8>, String> {
                struct CancelServerOnDrop(Cx);

                impl Drop for CancelServerOnDrop {
                    fn drop(&mut self) {
                        self.0.cancel_with(
                            CancelKind::User,
                            Some("write-half SSE controller finished"),
                        );
                    }
                }

                let _server_cancellation = CancelServerOnDrop(caller_cx);
                let request = JsonRpcRequest::new(
                    "tools/call",
                    Some(serde_json::json!({
                        "name": "live_modern_controlled_tool",
                        "arguments": {},
                        "_meta": {
                            MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                            FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                        },
                    })),
                    REQUEST_ID as i64,
                );
                let body = serde_json::to_vec(&request).map_err(|error| {
                    format!("write-half SSE request did not serialize: {error}")
                })?;
                let request = live_http_post(
                    "/mcp",
                    &body,
                    &[
                        ("Accept", "text/event-stream"),
                        ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                        ("Mcp-Method", "tools/call"),
                        ("Mcp-Name", "live_modern_controlled_tool"),
                    ],
                );
                let mut stream = std::net::TcpStream::connect(address)
                    .map_err(|error| format!("write-half SSE connect failed: {error}"))?;
                std::io::Write::write_all(&mut stream, &request)
                    .map_err(|error| format!("write-half SSE request write failed: {error}"))?;
                std::io::Write::flush(&mut stream)
                    .map_err(|error| format!("write-half SSE request flush failed: {error}"))?;
                if !controller_control.wait_for_started(1, Duration::from_secs(2)) {
                    return Err(
                        "write-half SSE handler did not reach its pre-election gate".to_owned()
                    );
                }
                stream
                    .shutdown(std::net::Shutdown::Write)
                    .map_err(|error| format!("write-half SSE shutdown failed: {error}"))?;
                stream
                    .set_read_timeout(Some(Duration::from_millis(100)))
                    .map_err(|error| {
                        format!("write-half SSE probe timeout setup failed: {error}")
                    })?;
                let mut probe = [0_u8; 1];
                match std::io::Read::read(&mut stream, &mut probe) {
                    Err(error)
                        if matches!(
                            error.kind(),
                            std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock
                        ) => {}
                    Ok(0) => {
                        return Err("write-half SSE body closed before outcome election".to_owned());
                    }
                    Ok(_) => {
                        return Err(
                            "write-half SSE committed a response head before outcome election"
                                .to_owned(),
                        );
                    }
                    Err(error) => {
                        return Err(format!("write-half SSE no-head probe failed: {error}"));
                    }
                }
                if controller_control.was_cancelled(REQUEST_ID) {
                    return Err("write-half EOF cancelled the pending SSE request".to_owned());
                }
                controller_control.release(REQUEST_ID);
                stream
                    .set_read_timeout(Some(Duration::from_secs(2)))
                    .map_err(|error| {
                        format!("write-half SSE response timeout setup failed: {error}")
                    })?;
                let mut response = Vec::new();
                std::io::Read::read_to_end(&mut stream, &mut response)
                    .map_err(|error| format!("write-half SSE response read failed: {error}"))?;
                Ok(response)
            });

            let shutdown = bound
                .serve(&cx)
                .await
                .map_err(|error| format!("write-half SSE server failed: {error}"))?;
            let response = controller
                .join()
                .map_err(|_| "write-half SSE controller panicked".to_owned())??;
            require_quiescent_http_shutdown(shutdown, "write-half SSE response").await?;
            if !response.starts_with(b"HTTP/1.1 200") {
                return Err(format!(
                    "write-half SSE response was unexpected: {response:?}"
                ));
            }
            if !live_http_chunked_sse_messages(&response)?.iter().any(|message| {
                matches!(
                    message,
                    JsonRpcMessage::Response(response)
                        if response.id == Some((REQUEST_ID as i64).into()) && response.error.is_none()
                )
            }) {
                return Err("write-half SSE omitted its terminal response".to_owned());
            }
            if control.was_cancelled(REQUEST_ID) {
                return Err("write-half EOF cancelled the completed SSE request".to_owned());
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_sse_full_disconnect_cancels_after_output_failure() {
        run_live_http_test(|cx| async move {
            let bound = Server::new("live-http-sse-full-disconnect", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("full-disconnect SSE bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("full-disconnect SSE address failed: {error}"))?;
            let server = Arc::clone(&bound.endpoint.server);
            let caller_cx = cx.clone();
            let controller = thread::spawn(move || -> Result<(), String> {
                struct CancelServerOnDrop(Cx);

                impl Drop for CancelServerOnDrop {
                    fn drop(&mut self) {
                        self.0.cancel_with(
                            CancelKind::User,
                            Some("full-disconnect SSE controller finished"),
                        );
                    }
                }

                let _server_cancellation = CancelServerOnDrop(caller_cx);
                let listen = JsonRpcRequest::new(
                    SUBSCRIPTIONS_LISTEN,
                    Some(serde_json::json!({
                        "_meta": {
                            MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                            FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                        },
                        "notifications": {"toolsListChanged": true},
                    })),
                    816_i64,
                );
                let body = serde_json::to_vec(&listen).map_err(|error| {
                    format!("full-disconnect SSE request did not serialize: {error}")
                })?;
                let request = live_http_post(
                    "/mcp",
                    &body,
                    &[
                        ("Accept", "text/event-stream"),
                        ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                        ("Mcp-Method", SUBSCRIPTIONS_LISTEN),
                    ],
                );
                let mut stream = std::net::TcpStream::connect(address)
                    .map_err(|error| format!("full-disconnect SSE connect failed: {error}"))?;
                stream
                    .set_read_timeout(Some(Duration::from_secs(2)))
                    .map_err(|error| {
                        format!("full-disconnect SSE acknowledgement timeout setup failed: {error}")
                    })?;
                std::io::Write::write_all(&mut stream, &request).map_err(|error| {
                    format!("full-disconnect SSE request write failed: {error}")
                })?;
                std::io::Write::flush(&mut stream).map_err(|error| {
                    format!("full-disconnect SSE request flush failed: {error}")
                })?;
                let mut acknowledgement = Vec::new();
                while !acknowledgement
                    .windows(b"notifications/subscriptions/acknowledged".len())
                    .any(|window| window == b"notifications/subscriptions/acknowledged")
                {
                    let mut chunk = [0_u8; 2048];
                    let count = std::io::Read::read(&mut stream, &mut chunk).map_err(|error| {
                        format!("full-disconnect SSE acknowledgement read failed: {error}")
                    })?;
                    if count == 0 {
                        return Err(
                            "full-disconnect SSE closed before subscriptions/acknowledged"
                                .to_owned(),
                        );
                    }
                    acknowledgement.extend_from_slice(&chunk[..count]);
                }

                if server
                    .publish_subscription_notification(ServerNotification::ToolsListChanged(None))
                    .map_err(|error| {
                        format!("full-disconnect initial output publish failed: {error}")
                    })?
                    != 1
                {
                    return Err(
                        "full-disconnect listener did not accept its first output event".to_owned(),
                    );
                }
                // Leave a real server output unread, then close both halves.
                // The next output write, not input EOF, is the peer-loss
                // signal under test.
                std::thread::sleep(Duration::from_millis(20));
                stream
                    .shutdown(std::net::Shutdown::Both)
                    .map_err(|error| format!("full-disconnect SSE shutdown failed: {error}"))?;
                drop(stream);

                let deadline = Instant::now() + Duration::from_secs(2);
                loop {
                    if server
                        .final_subscriptions
                        .inner
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .entries
                        .is_empty()
                    {
                        return Ok(());
                    }
                    if Instant::now() >= deadline {
                        return Err(
                            "full-disconnect SSE did not cancel after output-side failure"
                                .to_owned(),
                        );
                    }
                    let _ = server
                        .publish_subscription_notification(ServerNotification::ToolsListChanged(
                            None,
                        ))
                        .map_err(|error| {
                            format!("full-disconnect follow-up output publish failed: {error}")
                        })?;
                    std::thread::sleep(Duration::from_millis(1));
                }
            });

            let shutdown = bound
                .serve(&cx)
                .await
                .map_err(|error| format!("full-disconnect SSE server failed: {error}"))?;
            controller
                .join()
                .map_err(|_| "full-disconnect SSE controller panicked".to_owned())??;
            require_quiescent_http_shutdown(shutdown, "full-disconnect SSE output failure").await
        });
    }

    #[test]
    fn live_http_dual_accept_rejects_only_four_digit_qvalue_before_handler() {
        run_live_http_test(|cx| async move {
            let calls = Arc::new(AtomicUsize::new(0));
            let bound = Server::new("live-modern-sse-qvalue", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .log_level(Level::Debug)
                .tool(HttpRequestScopedProgressTool {
                    calls: Arc::clone(&calls),
                })
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("live malformed SSE bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("live malformed SSE address failed: {error}"))?;
            let request = JsonRpcRequest::new(
                "tools/call",
                Some(serde_json::json!({
                    "name": "http_request_scoped_progress",
                    "arguments": {},
                    "_meta": {
                        MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                        FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                        "progressToken": "live-http-progress",
                        "io.modelcontextprotocol/logLevel": "info",
                    },
                })),
                813_i64,
            );
            let body = serde_json::to_vec(&request)
                .map_err(|error| format!("live malformed request did not serialize: {error}"))?;
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let request = live_http_post(
                        "/mcp",
                        &body,
                        &[
                            ("Accept", "application/json, text/event-stream; Q=1.0000"),
                            ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                            ("Mcp-Method", "tools/call"),
                            ("Mcp-Name", "http_request_scoped_progress"),
                        ],
                    );
                    let response = live_http_exchange(address, request).await;
                    caller_cx.cancel_with(CancelKind::User, Some("malformed SSE request complete"));
                    response
                })
                .map_err(|error| format!("live malformed client admission failed: {error}"))?;
            let serve = bound.serve(&cx).await;
            let response = client
                .join(&cx)
                .await
                .map_err(|error| format!("live malformed client failed: {error:?}"))??;
            let shutdown =
                serve.map_err(|error| format!("live malformed server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "live malformed").await?;
            if !response.starts_with(b"HTTP/1.1 406") || calls.load(Ordering::Acquire) != 0 {
                return Err(
                    "changing only the SSE qvalue precision must reject before handler entry"
                        .to_owned(),
                );
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_sse_discovery_rejects_preissued_session_without_registry_mutation() {
        run_live_http_test(|cx| async move {
            let bound = Server::new("live-http-sse-discovery-reject", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("SSE discovery rejection bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("SSE discovery rejection address failed: {error}"))?;
            let modern_sessions = Arc::clone(&bound.modern_sessions);
            let discovery = JsonRpcRequest::new(
                SERVER_DISCOVER_METHOD,
                Some(serde_json::json!({
                    "_meta": {
                        MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                        FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                    },
                })),
                RequestId::Number(869),
            );
            let discovery_body = serde_json::to_vec(&discovery)
                .map_err(|error| format!("SSE discovery rejection did not serialize: {error}"))?;
            let request = live_http_post(
                "/mcp",
                &discovery_body,
                &[
                    ("Accept", "text/event-stream"),
                    ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                    ("Mcp-Method", SERVER_DISCOVER_METHOD),
                    ("MCP-Session-Id", "preissued-session"),
                ],
            );
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let response = live_http_exchange(address, request).await;
                    caller_cx.cancel_with(
                        CancelKind::User,
                        Some("SSE discovery preissued-session rejection complete"),
                    );
                    response
                })
                .map_err(|error| {
                    format!("SSE discovery rejection client admission failed: {error}")
                })?;

            let serve = bound.serve(&cx).await;
            let response = client
                .join(&cx)
                .await
                .map_err(|error| format!("SSE discovery rejection client failed: {error:?}"))??;
            let shutdown =
                serve.map_err(|error| format!("SSE discovery rejection server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "SSE discovery rejection").await?;
            if !response.starts_with(b"HTTP/1.1 400")
                || !modern_sessions
                    .sessions
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .is_empty()
            {
                return Err(
                    "preissued SSE discovery session header minted or retained a session"
                        .to_owned(),
                );
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_shutdown_owns_registered_sse_body_before_flushing_terminal() {
        run_live_http_test(|cx| async move {
            let bound = Server::new("live-http-listen-half-close", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("subscription half-close bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("subscription half-close address failed: {error}"))?;
            let server = Arc::clone(&bound.endpoint.server);
            let remaining_modern_sessions = Arc::clone(&bound.modern_sessions);
            let owned_modern_sessions = Arc::clone(&remaining_modern_sessions);
            let caller_cx = cx.clone();
            let controller = thread::spawn(move || -> Result<(), String> {
                struct CancelServerOnDrop(Cx);
                impl Drop for CancelServerOnDrop {
                    fn drop(&mut self) {
                        self.0.cancel_with(
                            CancelKind::User,
                            Some("subscription half-close controller finished"),
                        );
                    }
                }
                let shutdown_cx = caller_cx.clone();
                let _server_cancellation = CancelServerOnDrop(caller_cx);
                let listen = JsonRpcRequest::new(
                    SUBSCRIPTIONS_LISTEN,
                    Some(serde_json::json!({
                        "_meta": {
                            MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                            FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                        },
                        "notifications": {"toolsListChanged": true},
                    })),
                    RequestId::Number(871),
                );
                let listen_body = serde_json::to_vec(&listen)
                    .map_err(|error| format!("listen request did not serialize: {error}"))?;
                let listen_request = live_http_post(
                    "/mcp",
                    &listen_body,
                    &[
                        ("Accept", "text/event-stream"),
                        ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                        ("Mcp-Method", SUBSCRIPTIONS_LISTEN),
                    ],
                );
                let mut stream = std::net::TcpStream::connect(address)
                    .map_err(|error| format!("listen SSE connect failed: {error}"))?;
                stream
                    .set_read_timeout(Some(Duration::from_secs(2)))
                    .map_err(|error| format!("listen SSE timeout setup failed: {error}"))?;
                std::io::Write::write_all(&mut stream, &listen_request)
                    .map_err(|error| format!("listen SSE write failed: {error}"))?;
                std::io::Write::flush(&mut stream)
                    .map_err(|error| format!("listen SSE flush failed: {error}"))?;
                stream
                    .shutdown(std::net::Shutdown::Write)
                    .map_err(|error| format!("listen write-half close failed: {error}"))?;
                let mut received = Vec::new();
                while !received
                    .windows(b"notifications/subscriptions/acknowledged".len())
                    .any(|window| window == b"notifications/subscriptions/acknowledged")
                {
                    let mut chunk = [0_u8; 2048];
                    let count = std::io::Read::read(&mut stream, &mut chunk)
                        .map_err(|error| format!("listen acknowledgement read failed: {error}"))?;
                    if count == 0 {
                        return Err("listen stream closed before acknowledgement".to_owned());
                    }
                    received.extend_from_slice(&chunk[..count]);
                }
                if server
                    .final_subscriptions
                    .inner
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .entries
                    .len()
                    != 1
                {
                    return Err(
                        "request write-half EOF incorrectly cancelled the live response body"
                            .to_owned(),
                    );
                }
                if owned_modern_sessions
                    .sessions
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .len()
                    != 1
                {
                    return Err(
                        "live SSE response body was not registered for listener shutdown"
                            .to_owned(),
                    );
                }
                shutdown_cx.cancel_with(
                    CancelKind::User,
                    Some("subscription graceful shutdown requested"),
                );
                let mut trailing = Vec::new();
                std::io::Read::read_to_end(&mut stream, &mut trailing)
                    .map_err(|error| format!("terminated listen stream did not close: {error}"))?;
                received.extend_from_slice(&trailing);
                if received
                    .windows(b"notifications/cancelled".len())
                    .any(|window| window == b"notifications/cancelled")
                {
                    return Err(
                        "modern HTTP teardown emitted a forbidden cancellation notification"
                            .to_owned(),
                    );
                }
                if !received
                    .windows(b"\"resultType\":\"complete\"".len())
                    .any(|window| window == b"\"resultType\":\"complete\"")
                {
                    return Err("server teardown omitted its terminal complete result".to_owned());
                }
                Ok(())
            });

            let serve = bound.serve(&cx).await;
            controller
                .join()
                .map_err(|_| "subscription half-close controller panicked".to_owned())??;
            let shutdown =
                serve.map_err(|error| format!("subscription half-close server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "subscription half-close").await?;
            if !remaining_modern_sessions
                .sessions
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .is_empty()
            {
                return Err("listener shutdown retained a live SSE session".to_owned());
            }
            if !remaining_modern_sessions
                .retired_dispatches
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .is_empty()
            {
                return Err("listener shutdown detached a live SSE dispatch".to_owned());
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_ordinary_requests_overlap_in_request_owned_blocking_children() {
        let _overlap_lock = http_overlap_lock()
            .lock()
            .expect("live HTTP overlap test lock poisoned");
        reset_http_overlap_metrics();
        let control = http_overlap_control();
        let _control_guard = control.begin();

        run_live_http_test(|cx| async move {
            let bound = Server::new("live-http-request-owned-dispatch", "1.0.0")
                .tool(HttpOverlapTool)
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("request-owned HTTP bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("request-owned HTTP address failed: {error}"))?;
            let request = |id| {
                let request = JsonRpcRequest::new(
                    "tools/call",
                    Some(serde_json::json!({
                        "name": "http_overlap_tool",
                        "arguments": {},
                        "_meta": {
                            MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                            FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                        },
                    })),
                    id,
                );
                let body = serde_json::to_vec(&request)
                    .expect("request-owned HTTP request must serialize");
                live_http_post(
                    "/mcp",
                    &body,
                    &[
                        ("Accept", "application/json"),
                        ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                        ("Mcp-Method", "tools/call"),
                        ("Mcp-Name", "http_overlap_tool"),
                    ],
                )
            };
            let first_request = request(221_i64);
            let second_request = request(222_i64);
            let cancellation = cx.clone();
            let controller = thread::spawn(move || -> Result<(), String> {
                fn exchange(address: SocketAddr, request: Vec<u8>) -> Result<Vec<u8>, String> {
                    let mut stream = std::net::TcpStream::connect(address)
                        .map_err(|error| format!("request-owned HTTP connect failed: {error}"))?;
                    std::io::Write::write_all(&mut stream, &request)
                        .map_err(|error| format!("request-owned HTTP write failed: {error}"))?;
                    std::io::Write::flush(&mut stream)
                        .map_err(|error| format!("request-owned HTTP flush failed: {error}"))?;
                    let mut response = Vec::new();
                    std::io::Read::read_to_end(&mut stream, &mut response)
                        .map_err(|error| format!("request-owned HTTP read failed: {error}"))?;
                    Ok(response)
                }

                let first = thread::spawn(move || exchange(address, first_request));
                let second = thread::spawn(move || exchange(address, second_request));
                let both_entered =
                    http_overlap_control().wait_for_entries(2, Duration::from_secs(2));
                http_overlap_control().release_one();
                http_overlap_control().release_one();
                let first = first
                    .join()
                    .map_err(|_| "first request-owned HTTP client panicked".to_string())??;
                let second = second
                    .join()
                    .map_err(|_| "second request-owned HTTP client panicked".to_string())??;
                cancellation.cancel_with(CancelKind::User, Some("request-owned HTTP complete"));

                if !both_entered {
                    return Err("two ordinary HTTP requests did not enter concurrently".to_string());
                }
                for response in [first, second] {
                    if !response.starts_with(b"HTTP/1.1 200") {
                        return Err(format!("request-owned HTTP response failed: {response:?}"));
                    }
                }
                Ok(())
            });

            let serve = bound.serve(&cx).await;
            let controller = controller
                .join()
                .map_err(|_| "request-owned HTTP controller panicked".to_string())?;
            controller?;
            let shutdown =
                serve.map_err(|error| format!("request-owned HTTP server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "request-owned HTTP").await?;
            Ok(())
        });

        assert!(
            http_overlap_metrics().max.load(Ordering::SeqCst) >= 2,
            "ordinary HTTP requests must overlap in independent request-owned children"
        );
    }

    async fn live_http_modern_json_peer_close_probe(
        cx: &Cx,
        close_originating_peer: bool,
    ) -> Result<(), String> {
        let started = Arc::new(AtomicBool::new(false));
        let release = Arc::new(AtomicBool::new(false));
        let observed_cancellation = Arc::new(AtomicBool::new(false));
        let bound = Server::new("live-http-modern-json-peer-close", "1.0.0")
            .tool(LiveModernHttpPeerCancellationTool {
                started: Arc::clone(&started),
                release: Arc::clone(&release),
                observed_cancellation: Arc::clone(&observed_cancellation),
            })
            .build()
            .bind_http(cx, "127.0.0.1:0")
            .await
            .map_err(|error| format!("modern JSON peer-close HTTP bind failed: {error}"))?;
        let address = bound
            .local_addr()
            .map_err(|error| format!("modern JSON peer-close HTTP address failed: {error}"))?;
        let request = JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({
                "name": "live_modern_http_peer_cancellation_tool",
                "arguments": {},
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                },
            })),
            2_401_i64,
        );
        let body = serde_json::to_vec(&request).map_err(|error| {
            format!("modern JSON peer-close request did not serialize: {error}")
        })?;
        let request = live_http_post(
            "/mcp",
            &body,
            &[
                ("Accept", "application/json"),
                ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                ("Mcp-Method", "tools/call"),
                ("Mcp-Name", "live_modern_http_peer_cancellation_tool"),
            ],
        );
        let caller_cx = cx.clone();
        let started_by_client = Arc::clone(&started);
        let release_by_client = Arc::clone(&release);
        let observed_by_client = Arc::clone(&observed_cancellation);
        let mut client = cx
            .spawn(move |client_cx| async move {
                let deadline = client_cx
                    .now()
                    .saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
                let mut stream =
                    asupersync::time::timeout_at(deadline, AsyncTcpStream::connect(address))
                        .await
                        .map_err(|_| live_http_test_timeout("modern JSON peer-close connection"))?
                        .map_err(|error| {
                            format!("modern JSON peer-close connect failed: {error}")
                        })?;
                asupersync::time::timeout_at(deadline, stream.write_all(&request))
                    .await
                    .map_err(|_| live_http_test_timeout("modern JSON peer-close request write"))?
                    .map_err(|error| format!("modern JSON peer-close write failed: {error}"))?;
                asupersync::time::timeout_at(deadline, stream.flush())
                    .await
                    .map_err(|_| live_http_test_timeout("modern JSON peer-close request flush"))?
                    .map_err(|error| format!("modern JSON peer-close flush failed: {error}"))?;
                wait_for_live_http_flag(
                    &client_cx,
                    &started_by_client,
                    "modern JSON peer-close handler start",
                )
                .await?;

                if close_originating_peer {
                    stream
                        .shutdown(std::net::Shutdown::Write)
                        .map_err(|error| format!("modern JSON write-half close failed: {error}"))?;
                    release_by_client.store(true, Ordering::Release);
                    let mut response = Vec::new();
                    read_live_http_to_end(
                        &mut stream,
                        &mut response,
                        "modern JSON write-half-close positive response EOF",
                    )
                    .await?;
                    if !response.starts_with(b"HTTP/1.1 200") {
                        return Err(format!(
                            "modern JSON write-half-close response was unexpected: {response:?}"
                        ));
                    }
                    if observed_by_client.load(Ordering::Acquire) {
                        return Err(
                            "a write-half-closed modern JSON peer cancelled its handler".to_owned()
                        );
                    }
                } else {
                    release_by_client.store(true, Ordering::Release);
                    let mut response = Vec::new();
                    read_live_http_to_end(
                        &mut stream,
                        &mut response,
                        "modern JSON peer-close positive response EOF",
                    )
                    .await?;
                    if !response.starts_with(b"HTTP/1.1 200") {
                        return Err(format!(
                            "modern JSON peer-close positive response was unexpected: {response:?}"
                        ));
                    }
                    if observed_by_client.load(Ordering::Acquire) {
                        return Err("a connected modern JSON peer cancelled its handler".to_owned());
                    }
                }

                caller_cx.cancel_with(
                    CancelKind::User,
                    Some("modern JSON peer-close probe complete"),
                );
                Ok::<_, String>(())
            })
            .map_err(|error| format!("modern JSON peer-close client was not admitted: {error}"))?;

        let serve = bound.serve(cx).await;
        client
            .join(cx)
            .await
            .map_err(|error| format!("modern JSON peer-close client failed: {error:?}"))??;
        let shutdown =
            serve.map_err(|error| format!("modern JSON peer-close server failed: {error}"))?;
        require_quiescent_http_shutdown(shutdown, "modern JSON peer-close").await?;
        if observed_cancellation.load(Ordering::Acquire) {
            return Err(if close_originating_peer {
                "a write-half-closed modern JSON peer cancelled its handler".to_owned()
            } else {
                "connected modern JSON peer unexpectedly cancelled its handler".to_owned()
            });
        }
        Ok(())
    }

    #[test]
    fn live_http_modern_json_connected_peer_keeps_handler_live() {
        run_live_http_test(
            |cx| async move { live_http_modern_json_peer_close_probe(&cx, false).await },
        );
    }

    #[test]
    fn live_http_modern_json_write_half_close_preserves_handler() {
        // A clean write-half EOF is ordinary H1 request completion. It must
        // not cancel the still-owned JSON response body.
        run_live_http_test(
            |cx| async move { live_http_modern_json_peer_close_probe(&cx, true).await },
        );
    }

    #[test]
    fn live_http_connection_limit_hard_closes_idle_overflow_peers() {
        run_live_http_test(|cx| async move {
            let bound = Server::new("live-http-connection-limit", "1.0.0")
                .http_config(HttpServerConfig::new().max_connections(0))
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("connection-limit bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("connection-limit address failed: {error}"))?;
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    for peer in 0..8 {
                        let mut stream = AsyncTcpStream::connect(address).await.map_err(|error| {
                            format!("overflow peer {peer} failed to connect: {error}")
                        })?;
                        let mut response = Vec::new();
                        read_live_http_to_end(
                            &mut stream,
                            &mut response,
                            &format!("overflow peer {peer} close"),
                        )
                        .await?;
                        if !response.is_empty() {
                            return Err(format!(
                                "overflow peer {peer} received a response instead of an immediate close: {response:?}"
                            ));
                        }
                    }
                    caller_cx.cancel_with(CancelKind::User, Some("connection-limit complete"));
                    Ok::<(), String>(())
                })
                .map_err(|error| format!("connection-limit client admission failed: {error}"))?;

            let serve = bound.serve(&cx).await;
            client
                .join(&cx)
                .await
                .map_err(|error| format!("connection-limit client failed: {error:?}"))??;
            let shutdown =
                serve.map_err(|error| format!("connection-limit server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "connection limit").await?;
            Ok(())
        });
    }

    #[test]
    fn live_http_runs_lifespan_hooks_once() {
        run_live_http_test(|cx| async move {
            let startup = Arc::new(AtomicUsize::new(0));
            let shutdown = Arc::new(AtomicUsize::new(0));
            let startup_hook = Arc::clone(&startup);
            let shutdown_hook = Arc::clone(&shutdown);
            let bound = Server::new("live-http-lifespan", "1.0.0")
                .on_startup(move || {
                    startup_hook.fetch_add(1, Ordering::AcqRel);
                    Ok::<(), std::io::Error>(())
                })
                .on_shutdown(move || {
                    shutdown_hook.fetch_add(1, Ordering::AcqRel);
                })
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("lifespan HTTP bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("lifespan HTTP address failed: {error}"))?;
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let response = live_http_exchange(
                        address,
                        b"GET /health HTTP/1.1\r\nHost: loopback\r\nConnection: close\r\n\r\n"
                            .to_vec(),
                    )
                    .await;
                    caller_cx.cancel_with(CancelKind::User, Some("lifespan HTTP complete"));
                    response
                })
                .map_err(|error| format!("lifespan HTTP client admission failed: {error}"))?;

            let serve = bound.serve(&cx).await;
            let response = client
                .join(&cx)
                .await
                .map_err(|error| format!("lifespan HTTP client failed: {error:?}"))??;
            let server_shutdown =
                serve.map_err(|error| format!("lifespan HTTP server failed: {error}"))?;
            require_quiescent_http_shutdown(server_shutdown, "lifespan HTTP").await?;
            if !response.starts_with(b"HTTP/1.1 200") {
                return Err(format!("lifespan health request failed: {response:?}"));
            }
            if startup.load(Ordering::Acquire) != 1 || shutdown.load(Ordering::Acquire) != 1 {
                return Err(format!(
                    "HTTP lifespan hooks were not run exactly once (startup={}, shutdown={})",
                    startup.load(Ordering::Acquire),
                    shutdown.load(Ordering::Acquire),
                ));
            }
            Ok(())
        });
    }

    /// An idle peer and a byte-trickling peer each lose their connection at
    /// the request-read deadline, releasing the listener's only slot; a peer
    /// that sends a complete request on that same slot is served.
    #[test]
    fn live_http_request_read_timeout_releases_idle_and_trickling_connections() {
        const READ_TIMEOUT: Duration = Duration::from_millis(300);
        run_live_http_test(|cx| async move {
            let bound = Server::new("live-http-request-read-timeout", "1.0.0")
                .http_config(
                    HttpServerConfig::new()
                        .max_connections(1)
                        .request_read_timeout(READ_TIMEOUT),
                )
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("read-timeout bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("read-timeout address failed: {error}"))?;
            let caller_cx = cx.clone();
            let controller = thread::spawn(move || -> Result<Vec<u8>, String> {
                struct CancelServerOnDrop(Cx);

                impl Drop for CancelServerOnDrop {
                    fn drop(&mut self) {
                        self.0.cancel_with(
                            CancelKind::User,
                            Some("request read timeout controller finished"),
                        );
                    }
                }

                let _server_cancellation = CancelServerOnDrop(caller_cx);
                let connect = || -> Result<std::net::TcpStream, String> {
                    let stream = std::net::TcpStream::connect(address)
                        .map_err(|error| format!("read-timeout connect failed: {error}"))?;
                    stream
                        .set_read_timeout(Some(Duration::from_secs(10)))
                        .map_err(|error| format!("read-timeout setup failed: {error}"))?;
                    Ok(stream)
                };
                // Each stalled peer must be closed by the server (EOF, no
                // response bytes), and not before the deadline.
                let closed_at_deadline = |stream: &mut std::net::TcpStream,
                                          started: std::time::Instant,
                                          peer: &str|
                 -> Result<(), String> {
                    let mut received = Vec::new();
                    match std::io::Read::read_to_end(stream, &mut received) {
                        Ok(_) => {}
                        // Bytes written after the server's close draw a reset.
                        Err(error)
                            if matches!(
                                error.kind(),
                                std::io::ErrorKind::ConnectionReset
                                    | std::io::ErrorKind::BrokenPipe
                            ) => {}
                        Err(error) => return Err(format!("{peer} peer was not closed: {error}")),
                    }
                    let elapsed = started.elapsed();
                    if !received.is_empty() || elapsed < READ_TIMEOUT {
                        return Err(format!(
                            "{peer} peer closed after {elapsed:?} with {received:?}"
                        ));
                    }
                    Ok(())
                };

                let started = std::time::Instant::now();
                let mut idle = connect()?;
                closed_at_deadline(&mut idle, started, "idle")?;

                let started = std::time::Instant::now();
                let mut trickling = connect()?;
                for byte in b"GET /health HTTP/1.1\r\nHost: loop" {
                    if std::io::Write::write_all(&mut trickling, &[*byte]).is_err() {
                        break;
                    }
                    thread::sleep(Duration::from_millis(25));
                }
                closed_at_deadline(&mut trickling, started, "trickling")?;

                // Near-identical positive on the same single slot: the
                // complete request is answered.
                let mut complete = connect()?;
                std::io::Write::write_all(
                    &mut complete,
                    b"GET /health HTTP/1.1\r\nHost: loopback\r\nConnection: close\r\n\r\n",
                )
                .map_err(|error| format!("complete request write failed: {error}"))?;
                let mut response = Vec::new();
                std::io::Read::read_to_end(&mut complete, &mut response)
                    .map_err(|error| format!("complete request read failed: {error}"))?;
                Ok(response)
            });

            let shutdown = bound
                .serve(&cx)
                .await
                .map_err(|error| format!("read-timeout server failed: {error}"))?;
            let response = controller
                .join()
                .map_err(|_| "read-timeout controller panicked".to_owned())??;
            require_quiescent_http_shutdown(shutdown, "request read timeout").await?;
            if !response.starts_with(b"HTTP/1.1 200") {
                return Err(format!(
                    "a complete request on the released slot was not served: {:?}",
                    String::from_utf8_lossy(&response)
                ));
            }
            Ok(())
        });
    }

    // Exact-2024 era: legacy HTTP SSE endpoint event.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_http_legacy_sse_advertises_the_request_host_on_wildcard_bind() {
        run_live_http_test(|cx| async move {
            let bound = Server::new("live-http-host-origin", "1.0.0")
                .build()
                .bind_http(&cx, "0.0.0.0:0")
                .await
                .map_err(|error| format!("wildcard HTTP bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("wildcard HTTP address failed: {error}"))?;
            let loopback = SocketAddr::from(([127, 0, 0, 1], address.port()));
            let advertised_host = format!("public.example.test:{}", address.port());
            let expected_endpoint = format!("data: http://{advertised_host}/messages?session_id=");
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let mut stream = AsyncTcpStream::connect(loopback)
                        .await
                        .map_err(|error| format!("wildcard SSE connect failed: {error}"))?;
                    stream
                        .write_all(
                            format!(
                                "GET /sse HTTP/1.1\r\nHost: {advertised_host}\r\nAccept: text/event-stream\r\nConnection: keep-alive\r\n\r\n"
                            )
                            .as_bytes(),
                        )
                        .await
                        .map_err(|error| format!("wildcard SSE write failed: {error}"))?;
                    stream
                        .flush()
                        .await
                        .map_err(|error| format!("wildcard SSE flush failed: {error}"))?;
                    let mut received = Vec::new();
                    read_live_http_until(&mut stream, &mut received, expected_endpoint.as_bytes())
                        .await?;
                    caller_cx.cancel_with(CancelKind::User, Some("wildcard SSE complete"));
                    Ok::<(), String>(())
                })
                .map_err(|error| format!("wildcard SSE client admission failed: {error}"))?;

            let serve = bound.serve(&cx).await;
            client
                .join(&cx)
                .await
                .map_err(|error| format!("wildcard SSE client failed: {error:?}"))??;
            let shutdown = serve.map_err(|error| format!("wildcard SSE server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "wildcard SSE").await?;
            Ok(())
        });
    }

    // Exact-2024 era: legacy HTTP SSE lifecycle.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_http_loopback_preserves_exact_legacy_sse_and_post_lifecycle() {
        run_live_http_test(|cx| async move {
            let bound = Server::new("live-legacy-http", "1.0.0")
                .tool(LiveRuntimeListedTool)
                .http_config(
                    HttpServerConfig::new()
                        .mcp_path("/bridge")
                        .legacy_sse_path("/bridge"),
                )
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("live legacy HTTP bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("live legacy HTTP address failed: {error}"))?;
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let modern = JsonRpcRequest::new(
                        SERVER_DISCOVER_METHOD,
                        Some(serde_json::json!({
                            "_meta": {
                                MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                                FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                            },
                        })),
                        810_i64,
                    );
                    let modern_body = serde_json::to_vec(&modern)
                        .map_err(|error| format!("shared-target modern request failed: {error}"))?;
                    let modern = live_http_exchange(
                        address,
                        live_http_post(
                            "/bridge",
                            &modern_body,
                            &[
                                ("Accept", "application/json"),
                                ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                                ("MCP-Method", SERVER_DISCOVER_METHOD),
                            ],
                        ),
                    )
                    .await?;
                    if !modern.starts_with(b"HTTP/1.1 200") {
                        return Err(format!(
                            "shared-target modern POST did not select final HTTP: {modern:?}"
                        ));
                    }

                    let mut stream = AsyncTcpStream::connect(address)
                        .await
                        .map_err(|error| format!("legacy SSE connect failed: {error}"))?;
                    stream
                        .write_all(
                            format!(
                                "GET /bridge HTTP/1.1\r\nHost: {address}\r\nAccept: text/event-stream\r\nConnection: keep-alive\r\n\r\n"
                            )
                            .as_bytes(),
                        )
                        .await
                        .map_err(|error| format!("legacy SSE request write failed: {error}"))?;
                    stream
                        .flush()
                        .await
                        .map_err(|error| format!("legacy SSE request flush failed: {error}"))?;

                    let mut received = Vec::new();
                    let endpoint_prefix = format!(
                        "data: http://{address}/messages?session_id="
                    );
                    read_live_http_until(&mut stream, &mut received, endpoint_prefix.as_bytes())
                        .await?;
                    let received_text = std::str::from_utf8(&received)
                        .map_err(|error| format!("legacy SSE endpoint was not UTF-8: {error}"))?;
                    let session_id = received_text
                        .split_once(&endpoint_prefix)
                        .and_then(|(_, remainder)| remainder.split_whitespace().next())
                        .ok_or_else(|| "legacy SSE endpoint omitted its session identifier".to_string())?
                        .to_owned();

                    let initialize = JsonRpcRequest::new(
                        "initialize",
                        Some(serde_json::json!({
                            "protocolVersion": LEGACY_PROTOCOL_VERSION,
                            "capabilities": {},
                            "clientInfo": {"name": "loopback-legacy-client", "version": "1.0.0"},
                        })),
                        811_i64,
                    );
                    let initialized = JsonRpcRequest::notification("notifications/initialized", None);
                    let call = JsonRpcRequest::new(
                        "tools/call",
                        Some(serde_json::json!({
                            "name": "live_runtime_listed_tool",
                            "arguments": {},
                        })),
                        812_i64,
                    );
                    for message in [initialize, initialized] {
                        let body = serde_json::to_vec(&message).map_err(|error| {
                            format!("legacy loopback request did not serialize: {error}")
                        })?;
                        let response = live_http_exchange(
                            address,
                            live_http_post(
                                &format!("/messages?session_id={session_id}"),
                                &body,
                                &[],
                            ),
                        )
                        .await?;
                        let response = std::str::from_utf8(&response).map_err(|error| {
                            format!("legacy POST response was not UTF-8: {error}")
                        })?;
                        if !response.starts_with("HTTP/1.1 202") {
                            return Err(format!("legacy POST was not accepted: {response}"));
                        }
                    }

                    let call_body = serde_json::to_vec(&call).map_err(|error| {
                        format!("legacy loopback tool request did not serialize: {error}")
                    })?;
                    let wrong_session = live_http_exchange(
                        address,
                        live_http_post(
                            "/messages?session_id=wrong-session",
                            &call_body,
                            &[],
                        ),
                    )
                    .await?;
                    let wrong_session = std::str::from_utf8(&wrong_session).map_err(|error| {
                        format!("wrong-session legacy response was not UTF-8: {error}")
                    })?;
                    if !wrong_session.starts_with("HTTP/1.1 404") {
                        return Err(format!(
                            "changing only the legacy session ID was not rejected: {wrong_session}"
                        ));
                    }

                    let accepted = live_http_exchange(
                        address,
                        live_http_post(
                            &format!("/messages?session_id={session_id}"),
                            &call_body,
                            &[],
                        ),
                    )
                    .await?;
                    let accepted = std::str::from_utf8(&accepted).map_err(|error| {
                        format!("correct-session legacy response was not UTF-8: {error}")
                    })?;
                    if !accepted.starts_with("HTTP/1.1 202") {
                        return Err(format!(
                            "the unchanged exact legacy session did not accept the valid request: {accepted}"
                        ));
                    }

                    read_live_http_until(&mut stream, &mut received, br#""id":812"#).await?;
                    let received = std::str::from_utf8(&received)
                        .map_err(|error| format!("legacy SSE response was not UTF-8: {error}"))?;
                    if !received.contains(LEGACY_PROTOCOL_VERSION)
                        || !received.contains("live runtime legacy adapter request 812")
                        || received.contains("\"resultType\"")
                    {
                        return Err(format!("legacy SSE lifecycle was not exact: {received}"));
                    }
                    caller_cx.cancel_with(CancelKind::User, Some("legacy loopback complete"));
                    Ok(())
                })
                .map_err(|error| format!("legacy loopback client admission failed: {error}"))?;

            let serve = bound.serve(&cx).await;
            let client = client
                .join(&cx)
                .await
                .map_err(|error| format!("legacy loopback client failed: {error:?}"))?;
            let shutdown =
                serve.map_err(|error| format!("legacy loopback server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "legacy loopback").await?;
            client
        });
    }

    // Exact-2024 era: legacy HTTP SSE reverse responses.
    #[cfg(feature = "legacy-2024-11-05")]
    async fn live_http_legacy_reverse_response_post_probe(
        cx: &Cx,
        wrong_reverse_response_id: bool,
        plant_exact_admission_negatives: bool,
        reverse_response_token: Option<&'static str>,
        async_handler: bool,
    ) -> Result<(), String> {
        const INITIALIZE_ID: i64 = 842;
        const TOOL_CALL_ID: i64 = 843;

        // The synchronous tool bridges `ctx.sample` with `block_on` from its
        // `call` method, which is the obvious user code (bd-6rfrg). The async
        // tool awaits it on the caller-owned path instead.
        let server = Server::new("live-http-legacy-reverse-response", "1.0.0");
        let server = if async_handler {
            server.tool(LiveLegacyReverseResponseAsyncTool)
        } else {
            server.tool(LiveLegacyRuntimeConnectionTool)
        };
        let server = if reverse_response_token.is_some() {
            let verifier = StaticTokenVerifier::new([
                ("alpha", AuthContext::with_subject("alice")),
                ("beta", AuthContext::with_subject("bob")),
            ])
            .map_err(|error| format!("legacy reverse-response verifier failed: {error}"))?
            .with_allowed_schemes(["Bearer"])
            .map_err(|error| format!("legacy reverse-response scheme failed: {error}"))?;
            server.auth_provider(TokenAuthProvider::new(verifier))
        } else {
            server
        };
        let bound = server
            .build()
            .bind_http(cx, "127.0.0.1:0")
            .await
            .map_err(|error| format!("legacy reverse-response HTTP bind failed: {error}"))?;
        let address = bound
            .local_addr()
            .map_err(|error| format!("legacy reverse-response address failed: {error}"))?;
        let caller_cx = cx.clone();
        let mut client = cx
            .spawn(move |client_cx| async move {
                let opener_headers = reverse_response_token
                    .map(|_| vec![("Authorization", "Bearer alpha")])
                    .unwrap_or_default();
                let (mut sse, session_id, mut received) =
                    open_live_legacy_http_session(address, &opener_headers).await?;
                for request in [
                    JsonRpcRequest::new(
                        "initialize",
                        Some(serde_json::json!({
                            "protocolVersion": LEGACY_PROTOCOL_VERSION,
                            "capabilities": {"sampling": {}},
                            "clientInfo": {
                                "name": "legacy-reverse-response-client",
                                "version": "1.0.0"
                            },
                        })),
                        INITIALIZE_ID,
                    ),
                    JsonRpcRequest::notification("notifications/initialized", None),
                ] {
                    let body = serde_json::to_vec(&request).map_err(|error| {
                        format!("legacy reverse-response setup did not serialize: {error}")
                    })?;
                    let response = live_http_exchange(
                        address,
                        live_http_post(
                            &format!("/messages?session_id={session_id}"),
                            &body,
                            &opener_headers,
                        ),
                    )
                    .await?;
                    if !response.starts_with(b"HTTP/1.1 202") {
                        return Err(format!(
                            "legacy reverse-response setup was not accepted: {response:?}"
                        ));
                    }
                }

                let tool_call = JsonRpcRequest::new(
                    "tools/call",
                    Some(serde_json::json!({
                        "name": "live_legacy_runtime_connection_tool",
                        "arguments": {"sample": true},
                    })),
                    TOOL_CALL_ID,
                );
                let tool_call_body = serde_json::to_vec(&tool_call).map_err(|error| {
                    format!("legacy sampling tool call did not serialize: {error}")
                })?;
                let tool_call_request = live_http_post(
                    &format!("/messages?session_id={session_id}"),
                    &tool_call_body,
                    &opener_headers,
                );
                let mut tool_call = client_cx
                    .spawn(move |_tool_call_cx| async move {
                        live_http_exchange(address, tool_call_request).await
                    })
                    .map_err(|error| {
                        format!("legacy sampling tool-call POST was not admitted: {error}")
                    })?;

                read_live_http_until(&mut sse, &mut received, b"\"method\":\"sampling/createMessage\"")
                    .await?;
                let received_text = std::str::from_utf8(&received).map_err(|error| {
                    format!("legacy sampling reverse request was not UTF-8: {error}")
                })?;
                let sampling_offset = received_text
                    .find("\"method\":\"sampling/createMessage\"")
                    .ok_or_else(|| "legacy sampling reverse request was not retained".to_string())?;
                let event_start = received_text[..sampling_offset]
                    .rfind("data: ")
                    .ok_or_else(|| "legacy sampling reverse request omitted SSE data".to_string())?;
                let event = &received_text[event_start + "data: ".len()..];
                let (event, _) = event
                    .split_once("\n\n")
                    .ok_or_else(|| "legacy sampling reverse request was not one SSE event".to_string())?;
                let JsonRpcMessage::Request(reverse_request) = Codec::new()
                    .decode_complete_message(event.as_bytes())
                    .map_err(|error| {
                        format!("legacy sampling reverse request was not JSON-RPC: {error}")
                    })?
                else {
                    return Err("legacy sampling reverse event was not a request".to_string());
                };
                let reverse_request_id = reverse_request
                    .id
                    .ok_or_else(|| "legacy sampling reverse request omitted its ID".to_string())?;
                let response_id = if wrong_reverse_response_id {
                    // The only behavioral change in the near-identical
                    // negative is this correlation ID.
                    RequestId::Number(-2)
                } else {
                    reverse_request_id
                };
                let mut sampling_result = serde_json::to_value(
                    fastmcp_protocol::CreateMessageResult::text(
                        "http-sampled-value",
                        "legacy-http-test-model",
                    ),
                )
                .map_err(|error| format!("legacy sampling response did not serialize: {error}"))?;
                sampling_result["_meta"] =
                    serde_json::json!({"com.example/application": true});

                if plant_exact_admission_negatives {
                    let accepted = serde_json::json!({
                        "jsonrpc": "2.0",
                        "id": response_id.clone(),
                        "result": sampling_result.clone(),
                    });
                    let mut result_type = accepted.clone();
                    result_type["result"]["resultType"] = serde_json::json!("complete");
                    let mut final_metadata = accepted.clone();
                    final_metadata["result"]["_meta"]
                        ["io.modelcontextprotocol/protocolVersion"] =
                        serde_json::json!(LEGACY_PROTOCOL_VERSION);
                    for (dimension, body, headers) in [
                        (
                            "final resultType",
                            serde_json::to_vec(&result_type).map_err(|error| error.to_string())?,
                            Vec::new(),
                        ),
                        (
                            "final reserved metadata",
                            serde_json::to_vec(&final_metadata)
                                .map_err(|error| error.to_string())?,
                            Vec::new(),
                        ),
                        (
                            "modern binding header",
                            serde_json::to_vec(&accepted).map_err(|error| error.to_string())?,
                            vec![("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION)],
                        ),
                    ] {
                        let rejected = live_http_exchange(
                            address,
                            live_http_post(
                                &format!("/messages?session_id={session_id}"),
                                &body,
                                if opener_headers.is_empty() {
                                    &headers
                                } else {
                                    &opener_headers
                                },
                            ),
                        )
                        .await?;
                        if !rejected.starts_with(b"HTTP/1.1 400") {
                            return Err(format!(
                                "{dimension} reached the pending reverse waiter: {rejected:?}"
                            ));
                        }
                    }
                }
                let reverse_response = JsonRpcResponse::success(response_id, sampling_result);
                let reverse_body = serde_json::to_vec(&reverse_response).map_err(|error| {
                    format!("legacy sampling reverse response did not serialize: {error}")
                })?;
                let reverse_authorization = reverse_response_token
                    .map(|token| format!("Bearer {token}"));
                let reverse_headers = reverse_authorization
                    .as_deref()
                    .map(|authorization| vec![("Authorization", authorization)])
                    .unwrap_or_default();
                let reverse_post = live_http_post(
                    &format!("/messages?session_id={session_id}"),
                    &reverse_body,
                    &reverse_headers,
                );
                let mut reverse_post = client_cx
                    .spawn(move |_reverse_cx| async move { live_http_exchange(address, reverse_post).await })
                    .map_err(|error| {
                        format!("legacy sampling reverse-response POST was not admitted: {error}")
                    })?;

                if wrong_reverse_response_id {
                    // Observe the task without entering and then abandoning a
                    // join future. Cancellation of a timed join can itself
                    // alter the child task's authority, which would make this
                    // planted negative interfere with the settlement path it
                    // is meant to verify.
                    asupersync::time::sleep(client_cx.now(), Duration::from_millis(100)).await;
                    if !matches!(tool_call.try_join(), Ok(None)) {
                        caller_cx.cancel_with(
                            CancelKind::User,
                            Some("wrong-ID reverse response probe failed"),
                        );
                        return Err(
                            "wrong-ID reverse response settled the pending handler"
                                .to_string(),
                        );
                    }

                    let cancellation = JsonRpcRequest::notification(
                        "notifications/cancelled",
                        Some(serde_json::json!({
                            "requestId": TOOL_CALL_ID,
                            "reason": "settle wrong-ID reverse-response probe",
                        })),
                    );
                    let cancellation_body = serde_json::to_vec(&cancellation).map_err(|error| {
                        caller_cx.cancel_with(
                            CancelKind::User,
                            Some("cancellation serialization failed"),
                        );
                        format!("legacy sampling cancellation did not serialize: {error}")
                    })?;
                    let cancellation_response = live_http_exchange(
                        address,
                        live_http_post(
                            &format!("/messages?session_id={session_id}"),
                            &cancellation_body,
                            &opener_headers,
                        ),
                    )
                    .await;
                    let cancellation_response = match cancellation_response {
                        Ok(response) => response,
                        Err(error) => {
                            caller_cx.cancel_with(
                                CancelKind::User,
                                Some("cancellation exchange failed"),
                            );
                            return Err(error);
                        }
                    };
                    if !cancellation_response.starts_with(b"HTTP/1.1 202") {
                        caller_cx.cancel_with(
                            CancelKind::User,
                            Some("cancellation not accepted"),
                        );
                        return Err(format!(
                            "legacy sampling cancellation was not accepted: {cancellation_response:?}"
                        ));
                    }
                    let _ = tool_call.join(&client_cx).await.map_err(|error| {
                        caller_cx.cancel_with(
                            CancelKind::User,
                            Some("tool-call join failed"),
                        );
                        format!("legacy sampling cancelled tool-call POST failed: {error:?}")
                    })??;
                    let _ = reverse_post.join(&client_cx).await.map_err(|error| {
                        caller_cx.cancel_with(
                            CancelKind::User,
                            Some("reverse-post join failed"),
                        );
                        format!("wrong-ID reverse-response POST failed after settlement: {error:?}")
                    })??;
                } else {
                    let reverse_response = reverse_post.join(&client_cx).await.map_err(|error| {
                        format!("legacy sampling reverse-response POST failed: {error:?}")
                    })??;
                    if reverse_response_token == Some("beta") {
                        if !reverse_response.starts_with(b"HTTP/1.1 401") {
                            return Err(format!(
                                "foreign-principal reverse response was not rejected before mutation: {reverse_response:?}"
                            ));
                        }
                        asupersync::time::sleep(
                            client_cx.now(),
                            Duration::from_millis(100),
                        )
                        .await;
                        if !matches!(tool_call.try_join(), Ok(None)) {
                            return Err(
                                "foreign-principal reverse response settled the pending handler"
                                    .to_string(),
                            );
                        }
                        let owned_retry = live_http_exchange(
                            address,
                            live_http_post(
                                &format!("/messages?session_id={session_id}"),
                                &reverse_body,
                                &opener_headers,
                            ),
                        )
                        .await?;
                        if !owned_retry.starts_with(b"HTTP/1.1 202") {
                            return Err(format!(
                                "opener-principal reverse-response retry was not accepted: {owned_retry:?}"
                            ));
                        }
                    } else if !reverse_response.starts_with(b"HTTP/1.1 202") {
                        return Err(format!(
                            "matching reverse-response POST was not accepted: {reverse_response:?}"
                        ));
                    }
                    let tool_call_response = tool_call.join(&client_cx).await.map_err(|error| {
                        format!("legacy sampling tool-call POST failed: {error:?}")
                    })??;
                    if !tool_call_response.starts_with(b"HTTP/1.1 202") {
                        return Err(format!(
                            "legacy sampling tool-call POST was not accepted: {tool_call_response:?}"
                        ));
                    }
                    read_live_http_until(
                        &mut sse,
                        &mut received,
                        b"legacy-runtime-1-http-sampled-value",
                    )
                    .await?;
                }

                caller_cx.cancel_with(
                    CancelKind::User,
                    Some("legacy reverse-response POST probe complete"),
                );
                Ok::<_, String>(())
            })
            .map_err(|error| format!("legacy reverse-response client task was not admitted: {error}"))?;

        // Bound only the two outermost awaits, so a stall fails the test by
        // name instead of freezing the binary. Inner joins stay unbounded: a
        // timed join cancels, which would change the authority under test.
        // `serve` spans the whole client exchange, so its bound counts only
        // runnable time: a loaded full suite stretches it, a stall does not.
        let bound_limit = Duration::from_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
        let host = RunnableClock::start();
        let serve_started = host.mark();
        let Some(serve) =
            within_runnable(cx, &host, serve_started, bound_limit, bound.serve(cx)).await
        else {
            // `serve` returns only after the client cancels `caller_cx`, and
            // a client that fails early returns without cancelling. Report
            // its outcome so that failure is not misread as a server stall.
            let client_state = match client.try_join() {
                Ok(None) => "the client is still pending".to_owned(),
                Ok(Some(Ok(()))) => "the client completed and cancelled".to_owned(),
                Ok(Some(Err(error))) => format!("the client failed first: {error}"),
                Err(error) => format!("the client task could not be joined: {error:?}"),
            };
            return Err(format!(
                "legacy reverse-response serve did not finish within {}; {client_state}",
                host.describe(serve_started)
            ));
        };
        let join_started = host.mark();
        within_runnable(cx, &host, join_started, bound_limit, client.join(cx))
            .await
            .ok_or_else(|| {
                format!(
                    "legacy reverse-response client did not finish within {}",
                    host.describe(join_started)
                )
            })?
            .map_err(|error| format!("legacy reverse-response client failed: {error:?}"))??;
        let shutdown =
            serve.map_err(|error| format!("legacy reverse-response server failed: {error}"))?;
        require_quiescent_http_shutdown(shutdown, "legacy reverse-response").await
    }

    // Exact-2024 era: legacy HTTP SSE reverse responses.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_http_legacy_reverse_response_bypasses_the_originating_session_mutex() {
        run_live_http_test(|cx| async move {
            live_http_legacy_reverse_response_post_probe(&cx, false, false, None, false).await
        });
    }

    // Exact-2024 era: legacy HTTP SSE reverse responses.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_http_legacy_reverse_response_reaches_an_async_handler() {
        run_live_http_test(|cx| async move {
            // Differs from the synchronous positive only in the handler's
            // execution mode, which moves dispatch to the caller-owned path.
            live_http_legacy_reverse_response_post_probe(&cx, false, false, None, true).await
        });
    }

    // Exact-2024 era: legacy HTTP SSE reverse responses.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_http_legacy_reverse_response_exact_admission_precedes_pending_mutation() {
        run_live_http_test(|cx| async move {
            live_http_legacy_reverse_response_post_probe(&cx, false, true, None, false).await
        });
    }

    // Exact-2024 era: legacy HTTP SSE reverse responses.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_http_legacy_reverse_response_wrong_id_remains_blocked_until_cancellation() {
        run_live_http_test(|cx| async move {
            // This differs from the positive only in the reverse-response
            // correlation ID, so it must not complete the waiting handler.
            live_http_legacy_reverse_response_post_probe(&cx, true, false, None, false).await
        });
    }

    // Exact-2024 era: legacy HTTP SSE reverse responses.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_http_legacy_reverse_response_accepts_opener_principal() {
        run_live_http_test(|cx| async move {
            live_http_legacy_reverse_response_post_probe(&cx, false, false, Some("alpha"), false)
                .await
        });
    }

    // Exact-2024 era: legacy HTTP SSE reverse responses.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_http_legacy_reverse_response_rejects_foreign_principal_before_pending_mutation() {
        run_live_http_test(|cx| async move {
            // The only behavioral change from the authenticated positive is
            // the bearer principal on the first reverse-response POST.
            live_http_legacy_reverse_response_post_probe(&cx, false, false, Some("beta"), false)
                .await
        });
    }

    // Exact-2024 era: legacy HTTP SSE reverse responses.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_http_legacy_unmatched_response_uses_one_auth_provider_evaluation() {
        run_live_http_test(|cx| async move {
            let provider_calls = Arc::new(AtomicUsize::new(0));
            let bound = Server::new("legacy-response-auth-receipt", "1.0.0")
                .auth_provider(CountingLegacyHttpAuthProvider {
                    calls: Arc::clone(&provider_calls),
                })
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("legacy auth-receipt bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("legacy auth-receipt address failed: {error}"))?;
            let caller_cx = cx.clone();
            let client_provider_calls = Arc::clone(&provider_calls);
            let mut client = cx
                .spawn(move |_client_cx| async move {
                    let (stream, session_id, _) = open_live_legacy_http_session(
                        address,
                        &[("Authorization", "Bearer alpha")],
                    )
                    .await?;
                    if client_provider_calls.load(Ordering::Acquire) != 1 {
                        return Err(
                            "legacy SSE opener did not evaluate its provider exactly once"
                                .to_owned(),
                        );
                    }
                    let unmatched = JsonRpcResponse::success(
                        RequestId::Number(9_999),
                        serde_json::json!({"ignored": true}),
                    );
                    let body = serde_json::to_vec(&unmatched).map_err(|error| {
                        format!("unmatched legacy response did not serialize: {error}")
                    })?;
                    let response = live_http_exchange(
                        address,
                        live_http_post(
                            &format!("/messages?session_id={session_id}"),
                            &body,
                            &[("Authorization", "Bearer alpha")],
                        ),
                    )
                    .await?;
                    if !response.starts_with(b"HTTP/1.1 400") {
                        return Err(format!(
                            "unmatched legacy response did not reach its serialized rejection: {response:?}"
                        ));
                    }
                    if client_provider_calls.load(Ordering::Acquire) != 2 {
                        return Err(
                            "serialized unmatched-response fallback re-evaluated authentication"
                                .to_owned(),
                        );
                    }
                    drop(stream);
                    caller_cx.cancel_with(
                        CancelKind::User,
                        Some("legacy unmatched auth-receipt probe complete"),
                    );
                    Ok::<(), String>(())
                })
                .map_err(|error| format!("legacy auth-receipt client admission failed: {error}"))?;

            let serve = bound.serve(&cx).await;
            client
                .join(&cx)
                .await
                .map_err(|error| format!("legacy auth-receipt client failed: {error:?}"))??;
            let shutdown =
                serve.map_err(|error| format!("legacy auth-receipt server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "legacy unmatched auth receipt").await
        });
    }

    // Exact-2024 era: legacy HTTP blocking dispatch bridge.
    #[cfg(feature = "legacy-2024-11-05")]
    async fn live_http_legacy_blocking_bridge_probe(
        cx: &Cx,
        plant_dispatch_panic: bool,
    ) -> Result<(), String> {
        let endpoint = Server::new("legacy-panic-quarantine", "1.0.0")
            .build_http_endpoint("http://legacy.test")
            .map_err(|error| format!("dual-era endpoint did not build: {error}"))?;
        let mut owned = endpoint
            .open_session(cx)
            .map_err(|error| format!("legacy HTTP session did not open: {error}"))?;
        let ServerHttpEndpointResponse::LegacySse(mut stream) = owned
            .handle_async(cx, HttpRequest::new(HttpMethod::Get, "/sse"))
            .await
            .map_err(|error| format!("legacy SSE admission failed: {error}"))?
        else {
            return Err("legacy GET did not return an SSE response body".to_owned());
        };
        let _ = stream
            .recv_event(cx)
            .map_err(|error| format!("legacy SSE endpoint advertisement failed: {error}"))?;
        let session_id = owned.legacy_session_id().to_owned();
        let shell = Arc::new(LiveHttpSession {
            cancellation: owned.cancellation_control(),
            legacy_pending_requests: Arc::clone(&owned.legacy_pending_requests),
            session: Mutex::new(Some(owned)),
            session_available: Condvar::new(),
            closing: AtomicBool::new(false),
        });
        let sessions = Arc::new(Mutex::new(HashMap::from([(
            session_id.clone(),
            Arc::clone(&shell),
        )])));
        let permit = try_reserve_blocking_dispatch()
            .ok_or_else(|| "legacy blocking bridge test could not reserve capacity".to_owned())?;

        let response = run_live_http_legacy_blocking_dispatch(
            cx,
            &sessions,
            Some(session_id.clone()),
            permit,
            move |_blocking_cx| {
                assert!(
                    !plant_dispatch_panic,
                    "planted legacy HTTP blocking-dispatch panic"
                );
                HttpResponse::ok()
            },
        )
        .await
        .map_err(|()| "legacy blocking bridge region did not settle".to_owned())?;

        let remains_routable = sessions
            .lock()
            .map_err(|_| "quarantine registry lock was poisoned".to_owned())?
            .contains_key(&session_id);
        if plant_dispatch_panic {
            if response.status != HttpStatus::INTERNAL_SERVER_ERROR
                || remains_routable
                || !shell.closing.load(Ordering::Acquire)
                || shell.cancellation.legacy_lifecycle.is_live()
                || stream.try_recv_event(cx).is_ok()
                || !matches!(
                    take_live_http_session(cx, &shell, None),
                    LiveHttpSessionTake::Unavailable
                )
            {
                return Err(
                    "panicked bridge did not map to 500 and quarantine only its session shell"
                        .to_owned(),
                );
            }
        } else if response.status != HttpStatus::OK
            || !remains_routable
            || shell.closing.load(Ordering::Acquire)
        {
            return Err("successful bridge dispatch mutated session admission state".to_owned());
        }
        drop(stream);
        Ok(())
    }

    // Exact-2024 era: legacy HTTP blocking dispatch bridge.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_http_legacy_blocking_bridge_returns_dispatch_response() {
        run_live_http_test(
            |cx| async move { live_http_legacy_blocking_bridge_probe(&cx, false).await },
        );
    }

    // Exact-2024 era: legacy HTTP blocking dispatch bridge.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_http_legacy_blocking_bridge_maps_panic_and_quarantines_session_shell() {
        run_live_http_test(|cx| async move {
            // This differs from the positive only in the closure's planted
            // panic, exercising the production pool/catch/settlement path.
            live_http_legacy_blocking_bridge_probe(&cx, true).await
        });
    }

    // Exact-2024 era: drives both eras over one HTTP listener.
    #[cfg(feature = "legacy-2024-11-05")]
    async fn live_bound_http_cross_era_transcript(
        cx: &Cx,
        policy: ProtocolPolicy,
    ) -> Result<(Vec<u8>, Vec<u8>), String> {
        let bound = Server::new("live-http-cross-era", "1.0.0")
            .protocol_policy(policy)
            .map_err(|error| format!("cross-era HTTP policy rejected: {error}"))?
            .build()
            .bind_http(cx, "127.0.0.1:0")
            .await
            .map_err(|error| format!("cross-era HTTP bind failed: {error}"))?;
        let address = bound
            .local_addr()
            .map_err(|error| format!("cross-era HTTP address failed: {error}"))?;
        let caller_cx = cx.clone();
        let mut client = cx
            .spawn(move |client_cx| async move {
                let legacy_request = format!(
                    "GET /sse HTTP/1.1\r\nHost: {address}\r\nAccept: text/event-stream\r\nConnection: close\r\n\r\n"
                )
                .into_bytes();
                let deadline = client_cx
                    .now()
                    .saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
                let mut legacy = asupersync::time::timeout_at(
                    deadline,
                    AsyncTcpStream::connect(address),
                )
                    .await
                    .map_err(|_| live_http_test_timeout("cross-era legacy connection"))?
                    .map_err(|error| format!("cross-era legacy connect failed: {error}"))?;
                asupersync::time::timeout_at(deadline, legacy.write_all(&legacy_request))
                    .await
                    .map_err(|_| live_http_test_timeout("cross-era legacy request write"))?
                    .map_err(|error| format!("cross-era legacy write failed: {error}"))?;
                asupersync::time::timeout_at(deadline, legacy.flush())
                    .await
                    .map_err(|_| live_http_test_timeout("cross-era legacy request flush"))?
                    .map_err(|error| format!("cross-era legacy flush failed: {error}"))?;

                let modern = JsonRpcRequest::new(
                    SERVER_DISCOVER_METHOD,
                    Some(serde_json::json!({
                        "_meta": {
                            MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                            FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                        },
                    })),
                    891_i64,
                );
                let modern_body = serde_json::to_vec(&modern)
                    .map_err(|error| format!("cross-era modern request did not serialize: {error}"))?;
                let modern_request = live_http_post(
                    "/mcp",
                    &modern_body,
                    &[
                        ("Accept", "application/json"),
                        ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                        ("Mcp-Method", SERVER_DISCOVER_METHOD),
                    ],
                );

                let mut legacy_bytes = Vec::new();
                if matches!(policy, ProtocolPolicy::Auto) {
                    let endpoint_prefix = format!("data: http://{address}/messages?session_id=");
                    read_live_http_until(&mut legacy, &mut legacy_bytes, endpoint_prefix.as_bytes())
                        .await?;
                } else {
                    read_live_http_to_end(
                        &mut legacy,
                        &mut legacy_bytes,
                        "cross-era legacy rejection EOF",
                    )
                    .await?;
                }

                let modern_response = live_http_exchange(address, modern_request).await?;
                caller_cx.cancel_with(CancelKind::User, Some("cross-era HTTP transcript complete"));
                Ok::<_, String>((legacy_bytes, modern_response))
            })
            .map_err(|error| format!("cross-era HTTP client admission failed: {error}"))?;

        let serve = bound.serve(cx).await;
        let transcript = client
            .join(cx)
            .await
            .map_err(|error| format!("cross-era HTTP client failed: {error:?}"))??;
        let shutdown = serve.map_err(|error| format!("cross-era HTTP server failed: {error}"))?;
        require_quiescent_http_shutdown(shutdown, "cross-era HTTP").await?;
        Ok(transcript)
    }

    // Exact-2024 era: used only by the cross-era HTTP transcript.
    #[cfg(feature = "legacy-2024-11-05")]
    fn assert_cross_era_modern_discovery(response: &[u8]) -> Result<(), String> {
        if !response.starts_with(b"HTTP/1.1 200") {
            return Err(format!(
                "cross-era modern request did not receive HTTP 200: {response:?}"
            ));
        }
        let response: JsonRpcResponse = serde_json::from_slice(live_http_response_body(response)?)
            .map_err(|error| format!("cross-era modern response was invalid: {error}"))?;
        if response.id != Some(891_i64.into()) || response.error.is_some() {
            return Err(format!(
                "cross-era modern request was rejected: {response:?}"
            ));
        }
        if response.result.as_ref().and_then(|result| {
            result["_meta"][fastmcp_protocol::SERVER_DISCOVER_SERVER_INFO_META_KEY]["name"].as_str()
        }) != Some("live-http-cross-era")
        {
            return Err(format!(
                "cross-era modern discovery result changed its server identity: {response:?}"
            ));
        }
        Ok(())
    }

    async fn live_non_sse_shutdown_fence_transcript(
        cx: &Cx,
        cancel_before_response: bool,
    ) -> Result<Vec<u8>, String> {
        const REQUEST_ID: i64 = 892;

        let control = Arc::new(LiveModernControl::default());
        control.install_shutdown_cx(cx.clone());
        let bound = Server::new("live-http-shutdown-fence", "1.0.0")
            .tool(LiveModernControlledTool {
                control: Arc::clone(&control),
            })
            .build()
            .bind_http(cx, "127.0.0.1:0")
            .await
            .map_err(|error| format!("shutdown-fence HTTP bind failed: {error}"))?;
        let address = bound
            .local_addr()
            .map_err(|error| format!("shutdown-fence HTTP address failed: {error}"))?;
        let request = JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({
                "name": "live_modern_controlled_tool",
                "arguments": {},
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                },
            })),
            REQUEST_ID,
        );
        let request = live_http_post(
            "/mcp",
            &serde_json::to_vec(&request)
                .map_err(|error| format!("shutdown-fence request did not serialize: {error}"))?,
            &[
                // Streamable HTTP POSTs must accept both JSON and SSE; the
                // server still commits this exchange as an ordinary non-SSE
                // JSON response.
                ("Accept", "application/json, text/event-stream"),
                ("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION),
                ("Mcp-Method", "tools/call"),
                ("Mcp-Name", "live_modern_controlled_tool"),
            ],
        );
        let shutdown_applied = Arc::new(AtomicBool::new(false));
        let relay_control = Arc::clone(&control);
        let relay_applied = Arc::clone(&shutdown_applied);
        let caller_cx = cx.clone();
        let mut cancellation_relay = cx
            .spawn(move |_relay_cx| async move {
                while !relay_control.shutdown_requested.load(Ordering::Acquire) {
                    asupersync::runtime::yield_now().await;
                }
                let reason = if cancel_before_response {
                    "shutdown-fence cancellation before H1 response"
                } else {
                    "shutdown-fence response committed"
                };
                caller_cx.cancel_with(CancelKind::Shutdown, Some(reason));
                // The parked accept only wakes on I/O; poke the listener so
                // the serve loop observes the shutdown cancellation.
                let _ = std::net::TcpStream::connect(address);
                relay_applied.store(true, Ordering::Release);
            })
            .map_err(|error| format!("shutdown-fence relay admission failed: {error}"))?;
        let controller = Arc::clone(&control);
        let client_shutdown_applied = Arc::clone(&shutdown_applied);
        let client = thread::spawn(move || -> Result<Vec<u8>, String> {
            struct SignalShutdownOnDrop(Arc<LiveModernControl>);

            impl Drop for SignalShutdownOnDrop {
                fn drop(&mut self) {
                    self.0.request_shutdown();
                }
            }

            let _shutdown_on_drop = SignalShutdownOnDrop(Arc::clone(&controller));
            let mut stream = std::net::TcpStream::connect(address)
                .map_err(|error| format!("shutdown-fence client connect failed: {error}"))?;
            stream
                .set_read_timeout(Some(Duration::from_secs(2)))
                .map_err(|error| format!("shutdown-fence client timeout setup failed: {error}"))?;
            std::io::Write::write_all(&mut stream, &request)
                .map_err(|error| format!("shutdown-fence client write failed: {error}"))?;
            std::io::Write::flush(&mut stream)
                .map_err(|error| format!("shutdown-fence client flush failed: {error}"))?;
            if !controller.wait_for_started(1, Duration::from_secs(2)) {
                return Err("shutdown-fence tool did not enter before its deadline".to_owned());
            }
            if cancel_before_response {
                controller.request_shutdown();
                let deadline = Instant::now() + Duration::from_secs(2);
                while !client_shutdown_applied.load(Ordering::Acquire) {
                    if Instant::now() >= deadline {
                        return Err(
                            "shutdown-fence runtime relay did not apply cancellation".to_owned()
                        );
                    }
                    thread::yield_now();
                }
            } else {
                controller.release(REQUEST_ID as u64);
            }

            let mut response = Vec::new();
            match std::io::Read::read_to_end(&mut stream, &mut response) {
                Ok(_) => {}
                Err(error)
                    if cancel_before_response
                        && response.is_empty()
                        && matches!(
                            error.kind(),
                            std::io::ErrorKind::ConnectionAborted
                                | std::io::ErrorKind::ConnectionReset
                                | std::io::ErrorKind::UnexpectedEof
                                | std::io::ErrorKind::TimedOut
                                | std::io::ErrorKind::WouldBlock
                        ) => {}
                Err(error) => {
                    return Err(format!("shutdown-fence client read failed: {error}"));
                }
            }
            if !cancel_before_response {
                controller.request_shutdown();
            }
            Ok(response)
        });

        let serve = bound.serve(cx).await;
        cancellation_relay
            .join(cx)
            .await
            .map_err(|error| format!("shutdown-fence cancellation relay failed: {error:?}"))?;
        let response = client
            .join()
            .map_err(|_| "shutdown-fence client panicked".to_owned())??;
        let shutdown = serve.map_err(|error| format!("shutdown-fence server failed: {error}"))?;
        require_quiescent_http_shutdown(shutdown, "shutdown fence").await?;
        Ok(response)
    }

    // Exact-2024 era: tests Auto classification over HTTP.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_bound_http_auto_coexists_with_exact_legacy_and_modern_requests() {
        run_live_http_test(|cx| async move {
            let (legacy, modern) =
                live_bound_http_cross_era_transcript(&cx, ProtocolPolicy::Auto).await?;
            if !legacy.starts_with(b"HTTP/1.1 200")
                || !legacy
                    .windows(b"/messages?session_id=".len())
                    .any(|window| window == b"/messages?session_id=")
            {
                return Err(format!(
                    "Auto did not retain the exact legacy SSE route: {legacy:?}"
                ));
            }
            assert_cross_era_modern_discovery(&modern)?;
            Ok(())
        });
    }

    // Exact-2024 era: a dual-era build's ModernOnly refusal of its legacy route.
    // A no-legacy build has no such route; see
    // no_legacy_http_routes_are_not_found_without_pinning_or_adapter_admission.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_bound_http_modern_only_rejects_the_identical_legacy_half() {
        run_live_http_test(|cx| async move {
            // This transcript differs from the Auto positive only in the
            // policy selected at server construction.
            let (legacy, modern) =
                live_bound_http_cross_era_transcript(&cx, ProtocolPolicy::ModernOnly).await?;
            if !legacy.starts_with(b"HTTP/1.1 400") {
                return Err(format!(
                    "ModernOnly admitted the legacy SSE route: {legacy:?}"
                ));
            }
            assert_cross_era_modern_discovery(&modern)?;
            Ok(())
        });
    }

    #[test]
    fn live_http_non_sse_response_commits_before_shutdown() {
        run_live_http_test(|cx| async move {
            let response = live_non_sse_shutdown_fence_transcript(&cx, false).await?;
            if !response.starts_with(b"HTTP/1.1 200")
                || !response
                    .windows(b"modern request 892".len())
                    .any(|window| window == b"modern request 892")
            {
                return Err(format!(
                    "a non-SSE response did not commit before shutdown: {response:?}"
                ));
            }
            Ok(())
        });
    }

    #[test]
    fn live_http_non_sse_shutdown_suppresses_the_pending_response() {
        run_live_http_test(|cx| async move {
            // This differs from the positive only by cancelling after the
            // handler enters and before the ordinary H1 response can commit.
            let response = live_non_sse_shutdown_fence_transcript(&cx, true).await?;
            if !response.is_empty() {
                return Err(format!(
                    "shutdown wrote a non-SSE response after cancellation: {response:?}"
                ));
            }
            Ok(())
        });
    }

    // Exact-2024 era: legacy HTTP SSE session registry.
    #[cfg(feature = "legacy-2024-11-05")]
    async fn live_http_legacy_admission_cancellation_probe(
        cx: &Cx,
        cancellation_request_id: i64,
    ) -> Result<usize, String> {
        const INITIALIZE_ID: i64 = 830;
        const BLOCKER_ID: i64 = 831;
        const TARGET_ID: i64 = 832;

        let gate = Arc::new(LiveLegacyRequestGate::default());
        let target_calls = Arc::new(AtomicUsize::new(0));
        let bound = Server::new("live-http-legacy-admission-cancellation", "1.0.0")
            .tool(LiveLegacyAdmissionBlocker {
                gate: Arc::clone(&gate),
            })
            .tool(LiveLegacyAdmissionTarget {
                calls: Arc::clone(&target_calls),
            })
            .build()
            .bind_http(cx, "127.0.0.1:0")
            .await
            .map_err(|error| format!("legacy admission HTTP bind failed: {error}"))?;
        let address = bound
            .local_addr()
            .map_err(|error| format!("legacy admission HTTP address failed: {error}"))?;
        let legacy_sessions = Arc::clone(&bound.legacy_sessions);
        let caller_cx = cx.clone();
        let gate_for_client = Arc::clone(&gate);
        let target_calls_for_client = Arc::clone(&target_calls);
        let mut client = cx
            .spawn(move |client_cx| async move {
                struct CancelServerOnDrop(Cx);

                impl Drop for CancelServerOnDrop {
                    fn drop(&mut self) {
                        self.0.cancel_with(
                            CancelKind::User,
                            Some("legacy admission client exited"),
                        );
                    }
                }

                let _server_cancellation = CancelServerOnDrop(caller_cx.clone());
                let (mut sse, session_id, mut received) =
                    open_live_legacy_http_session(address, &[]).await?;
                let session = legacy_sessions
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .get(&session_id)
                    .cloned()
                    .ok_or_else(|| "legacy admission session was not registered".to_string())?;

                for request in [
                    JsonRpcRequest::new(
                        "initialize",
                        Some(serde_json::json!({
                            "protocolVersion": LEGACY_PROTOCOL_VERSION,
                            "capabilities": {},
                            "clientInfo": {"name": "legacy-admission-client", "version": "1.0.0"},
                        })),
                        INITIALIZE_ID,
                    ),
                    JsonRpcRequest::notification("notifications/initialized", None),
                ] {
                    let body = serde_json::to_vec(&request).map_err(|error| {
                        format!("legacy admission setup request did not serialize: {error}")
                    })?;
                    let response = live_http_exchange(
                        address,
                        live_http_post(&format!("/messages?session_id={session_id}"), &body, &[]),
                    )
                    .await?;
                    if !response.starts_with(b"HTTP/1.1 202") {
                        return Err(format!(
                            "legacy admission setup request was not accepted: {response:?}"
                        ));
                    }
                }

                let blocker = JsonRpcRequest::new(
                    "tools/call",
                    Some(serde_json::json!({
                        "name": "live_legacy_admission_blocker",
                        "arguments": {},
                    })),
                    BLOCKER_ID,
                );
                let blocker_body = serde_json::to_vec(&blocker).map_err(|error| {
                    format!("legacy admission blocker request did not serialize: {error}")
                })?;
                let blocker_request = live_http_post(
                    &format!("/messages?session_id={session_id}"),
                    &blocker_body,
                    &[],
                );
                let mut blocker = client_cx
                    .spawn(move |_blocker_cx| async move {
                        live_http_exchange(address, blocker_request).await
                    })
                    .map_err(|error| {
                        format!("legacy admission blocker task was not admitted: {error}")
                    })?;
                let _release_blocker = LiveLegacyRequestGateRelease {
                    gate: Arc::clone(&gate_for_client),
                };

                let blocker_deadline = client_cx
                    .now()
                    .saturating_add_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
                while !gate_for_client.entered.load(Ordering::Acquire) {
                    client_cx
                        .checkpoint()
                        .map_err(|error| format!("legacy admission client stopped: {error}"))?;
                    asupersync::time::timeout_at(
                        blocker_deadline,
                        asupersync::time::sleep(client_cx.now(), Duration::from_millis(1)),
                    )
                    .await
                    .map_err(|_| live_http_test_timeout("legacy admission blocker entry"))?;
                }

                let target_id = RequestId::Number(TARGET_ID);
                let target = JsonRpcRequest::new(
                    "tools/call",
                    Some(serde_json::json!({
                        "name": "live_legacy_admission_target",
                        "arguments": {},
                    })),
                    TARGET_ID,
                );
                let target_body = serde_json::to_vec(&target).map_err(|error| {
                    format!("legacy admission target request did not serialize: {error}")
                })?;
                let target_request = live_http_post(
                    &format!("/messages?session_id={session_id}"),
                    &target_body,
                    &[],
                );
                let mut target = client_cx
                    .spawn(move |_target_cx| async move {
                        live_http_exchange(address, target_request).await
                    })
                    .map_err(|error| {
                        format!("legacy admission target task was not admitted: {error}")
                    })?;
                wait_for_live_http_legacy_admission(&client_cx, &session, &target_id).await?;

                let cancellation = JsonRpcRequest::notification(
                    "notifications/cancelled",
                    Some(serde_json::json!({
                        "requestId": cancellation_request_id,
                        "reason": "legacy HTTP admission cancellation",
                    })),
                );
                let cancellation_body = serde_json::to_vec(&cancellation).map_err(|error| {
                    format!("legacy admission cancellation did not serialize: {error}")
                })?;
                let cancellation_response = live_http_exchange(
                    address,
                    live_http_post(
                        &format!("/messages?session_id={session_id}"),
                        &cancellation_body,
                        &[],
                    ),
                )
                .await?;
                if !cancellation_response.starts_with(b"HTTP/1.1 202") {
                    return Err(format!(
                        "legacy admission cancellation control POST was not accepted: {cancellation_response:?}"
                    ));
                }

                gate_for_client.release();
                let blocker_response = blocker
                    .join(&client_cx)
                    .await
                    .map_err(|error| format!("legacy admission blocker task failed: {error:?}"))??;
                if !blocker_response.starts_with(b"HTTP/1.1 202") {
                    return Err(format!(
                        "legacy admission blocker acknowledgement was unexpected: {blocker_response:?}"
                    ));
                }
                let target_response = target
                    .join(&client_cx)
                    .await
                    .map_err(|error| format!("legacy admission target task failed: {error:?}"))??;
                if !target_response.starts_with(b"HTTP/1.1 202") {
                    return Err(format!(
                        "legacy admission target acknowledgement was unexpected: {target_response:?}"
                    ));
                }

                let blocker_marker = format!("\"id\":{BLOCKER_ID}");
                read_live_http_until(&mut sse, &mut received, blocker_marker.as_bytes()).await?;
                let target_marker = format!("\"id\":{TARGET_ID}");
                if cancellation_request_id == TARGET_ID {
                    if target_calls_for_client.load(Ordering::Acquire) != 0
                        || received
                            .windows(target_marker.len())
                            .any(|window| window == target_marker.as_bytes())
                    {
                        return Err(
                            "a cancellation admitted before the session mutex still entered its target"
                                .to_string(),
                        );
                    }
                    let probe_deadline = client_cx
                        .now()
                        .saturating_add_nanos(100_000_000);
                    let mut chunk = [0_u8; 1024];
                    match asupersync::time::timeout_at(probe_deadline, sse.read(&mut chunk)).await {
                        Err(_) => {}
                        Ok(Ok(0)) => {
                            return Err(
                                "legacy admission SSE stream closed before the bounded silence probe"
                                    .to_string(),
                            );
                        }
                        Ok(Ok(read)) => {
                            received.extend_from_slice(&chunk[..read]);
                            return Err(format!(
                                "cancelled queued legacy request emitted an SSE frame: {received:?}"
                            ));
                        }
                        Ok(Err(error)) => {
                            return Err(format!(
                                "legacy admission SSE silence probe failed: {error}"
                            ));
                        }
                    }
                } else {
                    read_live_http_until(&mut sse, &mut received, target_marker.as_bytes()).await?;
                    if target_calls_for_client.load(Ordering::Acquire) != 1 {
                        return Err(
                            "one-ID-negative cancellation altered the exact target request"
                                .to_string(),
                        );
                    }
                }

                caller_cx.cancel_with(CancelKind::User, Some("legacy admission probe complete"));
                Ok::<_, String>(())
            })
            .map_err(|error| format!("legacy admission client task was not admitted: {error}"))?;

        let serve = bound.serve(cx).await;
        client
            .join(cx)
            .await
            .map_err(|error| format!("legacy admission client task failed: {error:?}"))??;
        let shutdown =
            serve.map_err(|error| format!("legacy admission HTTP server failed: {error}"))?;
        require_quiescent_http_shutdown(shutdown, "legacy admission HTTP").await?;
        Ok(target_calls.load(Ordering::Acquire))
    }

    // Exact-2024 era: legacy HTTP SSE session registry.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_http_legacy_cancellation_survives_admission_to_active_transition() {
        run_live_http_test(|cx| async move {
            let calls = live_http_legacy_admission_cancellation_probe(&cx, 832).await?;
            if calls != 0 {
                return Err(format!(
                    "cancelled queued legacy HTTP request entered its handler {calls} time(s)"
                ));
            }
            Ok(())
        });
    }

    // Exact-2024 era: legacy HTTP SSE session registry.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_http_legacy_cancellation_rejects_the_one_id_negative() {
        run_live_http_test(|cx| async move {
            // This differs from the positive only in the cancellation request
            // ID. It must not affect the queued request with ID 832.
            let calls = live_http_legacy_admission_cancellation_probe(&cx, 833).await?;
            if calls != 1 {
                return Err(format!(
                    "one-ID-negative cancellation changed target handler calls to {calls}"
                ));
            }
            Ok(())
        });
    }

    // Exact-2024 era: legacy HTTP SSE session registry.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_http_legacy_initialize_is_peer_cancellation_protected() {
        run_live_http_test(|cx| async move {
            const INITIALIZE_ID: i64 = 834;

            let bound = Server::new("live-http-legacy-initialize-protection", "1.0.0")
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("legacy initialize HTTP bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("legacy initialize HTTP address failed: {error}"))?;
            let legacy_sessions = Arc::clone(&bound.legacy_sessions);
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |client_cx| async move {
                    let (mut sse, session_id, mut received) =
                        open_live_legacy_http_session(address, &[]).await?;
                    let session = legacy_sessions
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .get(&session_id)
                        .cloned()
                        .ok_or_else(|| "legacy initialize session was not registered".to_string())?;
                    let mut session_hold = LiveHttpSessionMutexHold::new(Arc::clone(&session))?;
                    let initialize = JsonRpcRequest::new(
                        "initialize",
                        Some(serde_json::json!({
                            "protocolVersion": LEGACY_PROTOCOL_VERSION,
                            "capabilities": {},
                            "clientInfo": {"name": "legacy-initialize-client", "version": "1.0.0"},
                        })),
                        INITIALIZE_ID,
                    );
                    let initialize_body = serde_json::to_vec(&initialize).map_err(|error| {
                        format!("legacy initialize request did not serialize: {error}")
                    })?;
                    let initialize_request = live_http_post(
                        &format!("/messages?session_id={session_id}"),
                        &initialize_body,
                        &[],
                    );
                    let mut initialize = client_cx
                        .spawn(move |_initialize_cx| async move {
                            live_http_exchange(address, initialize_request).await
                        })
                        .map_err(|error| {
                            format!("legacy initialize task was not admitted: {error}")
                        })?;
                    let initialize_id = RequestId::Number(INITIALIZE_ID);
                    wait_for_live_http_legacy_admission(&client_cx, &session, &initialize_id).await?;

                    let cancellation = JsonRpcRequest::notification(
                        "notifications/cancelled",
                        Some(serde_json::json!({
                            "requestId": INITIALIZE_ID,
                            "reason": "initialize must be peer-cancellation protected",
                        })),
                    );
                    let cancellation_body = serde_json::to_vec(&cancellation).map_err(|error| {
                        format!("legacy initialize cancellation did not serialize: {error}")
                    })?;
                    let cancellation_response = live_http_exchange(
                        address,
                        live_http_post(
                            &format!("/messages?session_id={session_id}"),
                            &cancellation_body,
                            &[],
                        ),
                    )
                    .await?;
                    if !cancellation_response.starts_with(b"HTTP/1.1 202") {
                        return Err(format!(
                            "legacy initialize cancellation control POST was not accepted: {cancellation_response:?}"
                        ));
                    }

                    session_hold.release()?;
                    let initialize_response = initialize
                        .join(&client_cx)
                        .await
                        .map_err(|error| format!("legacy initialize task failed: {error:?}"))??;
                    if !initialize_response.starts_with(b"HTTP/1.1 202") {
                        return Err(format!(
                            "legacy initialize acknowledgement was unexpected: {initialize_response:?}"
                        ));
                    }
                    let initialize_marker = format!("\"id\":{INITIALIZE_ID}");
                    read_live_http_until(&mut sse, &mut received, initialize_marker.as_bytes())
                        .await?;
                    let received = std::str::from_utf8(&received).map_err(|error| {
                        format!("legacy initialize SSE response was not UTF-8: {error}")
                    })?;
                    if !received.contains(LEGACY_PROTOCOL_VERSION) {
                        return Err(
                            "peer cancellation suppressed the exact legacy initialize response"
                                .to_string(),
                        );
                    }
                    caller_cx.cancel_with(
                        CancelKind::User,
                        Some("legacy initialize protection probe complete"),
                    );
                    Ok::<_, String>(())
                })
                .map_err(|error| {
                    format!("legacy initialize client task was not admitted: {error}")
                })?;

            let serve = bound.serve(&cx).await;
            client
                .join(&cx)
                .await
                .map_err(|error| format!("legacy initialize client task failed: {error:?}"))??;
            let shutdown =
                serve.map_err(|error| format!("legacy initialize HTTP server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "legacy initialize HTTP").await?;
            Ok(())
        });
    }

    // Exact-2024 era: legacy HTTP SSE session registry.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_http_legacy_cancellation_bypasses_the_busy_session_lock() {
        run_live_http_test(|cx| async move {
            let started = Arc::new(AtomicBool::new(false));
            let observed_cancellation = Arc::new(AtomicBool::new(false));
            let observed_by_server = Arc::clone(&observed_cancellation);
            let bound = Server::new("live-http-legacy-cancellation", "1.0.0")
                .tool(LiveLegacyCancellationTool {
                    started: Arc::clone(&started),
                    observed_cancellation: Arc::clone(&observed_cancellation),
                })
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("legacy cancellation HTTP bind failed: {error}"))?;
            let address = bound
                .local_addr()
                .map_err(|error| format!("legacy cancellation HTTP address failed: {error}"))?;
            let legacy_sessions = Arc::clone(&bound.legacy_sessions);
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |client_cx| async move {
                    struct CancelServerOnDrop(Cx);

                    impl Drop for CancelServerOnDrop {
                        fn drop(&mut self) {
                            self.0.cancel_with(
                                CancelKind::User,
                                Some("legacy cancellation client exited"),
                            );
                        }
                    }

                    let _server_cancellation = CancelServerOnDrop(caller_cx.clone());
                    let mut stream = AsyncTcpStream::connect(address)
                        .await
                        .map_err(|error| format!("legacy cancellation SSE connect failed: {error}"))?;
                    stream
                        .write_all(
                            format!(
                                "GET /sse HTTP/1.1\r\nHost: {address}\r\nAccept: text/event-stream\r\nConnection: keep-alive\r\n\r\n"
                            )
                            .as_bytes(),
                        )
                        .await
                        .map_err(|error| format!("legacy cancellation SSE write failed: {error}"))?;
                    stream
                        .flush()
                        .await
                        .map_err(|error| format!("legacy cancellation SSE flush failed: {error}"))?;

                    let mut received = Vec::new();
                    let endpoint_prefix = format!("data: http://{address}/messages?session_id=");
                    read_live_http_until(&mut stream, &mut received, endpoint_prefix.as_bytes())
                        .await?;
                    let received_text = std::str::from_utf8(&received).map_err(|error| {
                        format!("legacy cancellation SSE endpoint was not UTF-8: {error}")
                    })?;
                    let session_id = received_text
                        .split_once(&endpoint_prefix)
                        .and_then(|(_, remainder)| remainder.split_whitespace().next())
                        .ok_or_else(|| {
                            "legacy cancellation SSE endpoint omitted its session identifier"
                                .to_string()
                        })?
                        .to_owned();
                    let live_session = legacy_sessions
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .get(&session_id)
                        .cloned()
                        .ok_or_else(|| {
                            "legacy cancellation session was not registered".to_string()
                        })?;

                    for request in [
                        JsonRpcRequest::new(
                            "initialize",
                            Some(serde_json::json!({
                                "protocolVersion": LEGACY_PROTOCOL_VERSION,
                                "capabilities": {},
                                "clientInfo": {"name": "legacy-cancellation-client", "version": "1.0.0"},
                            })),
                            821_i64,
                        ),
                        JsonRpcRequest::notification("notifications/initialized", None),
                    ] {
                        let body = serde_json::to_vec(&request).map_err(|error| {
                            format!("legacy cancellation setup request did not serialize: {error}")
                        })?;
                        let response = live_http_exchange(
                            address,
                            live_http_post(
                                &format!("/messages?session_id={session_id}"),
                                &body,
                                &[],
                            ),
                        )
                        .await?;
                        if !response.starts_with(b"HTTP/1.1 202") {
                            return Err(format!(
                                "legacy cancellation setup request was not accepted: {response:?}"
                            ));
                        }
                    }

                    let call = JsonRpcRequest::new(
                        "tools/call",
                        Some(serde_json::json!({
                            "name": "live_legacy_cancellation_tool",
                            "arguments": {},
                        })),
                        822_i64,
                    );
                    let call_body = serde_json::to_vec(&call).map_err(|error| {
                        format!("legacy cancellation call did not serialize: {error}")
                    })?;
                    let call_request = live_http_post(
                        &format!("/messages?session_id={session_id}"),
                        &call_body,
                        &[],
                    );
                    let mut call = client_cx
                        .spawn(move |_call_cx| async move {
                            live_http_exchange(address, call_request).await
                        })
                        .map_err(|error| {
                            format!("legacy cancellation call admission failed: {error}")
                        })?;

                    let deadline =
                        Instant::now() + Duration::from_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS);
                    while !started.load(Ordering::Acquire) && Instant::now() < deadline {
                        client_cx
                            .checkpoint()
                            .map_err(|error| format!("legacy cancellation client stopped: {error}"))?;
                        asupersync::time::sleep(client_cx.now(), Duration::from_millis(1)).await;
                    }
                    if !started.load(Ordering::Acquire) {
                        return Err("legacy cancellation handler did not start".to_string());
                    }
                    if !live_session
                        .cancellation
                        .admissions
                        .contains(&RequestId::Number(822))
                    {
                        return Err(
                            "running legacy cancellation target lost its admission authority"
                                .to_string(),
                        );
                    }

                    let cancelled = JsonRpcRequest::notification(
                        "notifications/cancelled",
                        Some(serde_json::json!({
                            "requestId": 822,
                            "reason": "live HTTP cancellation",
                            "_meta": {"com.example/application": true},
                        })),
                    );
                    let mut final_metadata = serde_json::to_value(&cancelled).map_err(|error| {
                        format!("legacy cancellation negative did not serialize: {error}")
                    })?;
                    final_metadata["params"]["_meta"]
                        ["io.modelcontextprotocol/subscriptionId"] = serde_json::json!("final");
                    for (dimension, body, headers) in [
                        (
                            "final reserved metadata",
                            serde_json::to_vec(&final_metadata)
                                .map_err(|error| error.to_string())?,
                            Vec::new(),
                        ),
                        (
                            "modern binding header",
                            serde_json::to_vec(&cancelled)
                                .map_err(|error| error.to_string())?,
                            vec![("MCP-Protocol-Version", MODERN_PROTOCOL_VERSION)],
                        ),
                    ] {
                        let rejected = live_http_exchange(
                            address,
                            live_http_post(
                                &format!("/messages?session_id={session_id}"),
                                &body,
                                &headers,
                            ),
                        )
                        .await?;
                        if !rejected.starts_with(b"HTTP/1.1 400") {
                            return Err(format!(
                                "{dimension} cancellation reached mutable state: {rejected:?}"
                            ));
                        }
                        if observed_by_server.load(Ordering::Acquire) {
                            return Err(format!(
                                "{dimension} cancellation reached the running handler"
                            ));
                        }
                        if !matches!(call.try_join(), Ok(None)) {
                            return Err(format!(
                                "{dimension} cancellation settled the target request"
                            ));
                        }
                    }
                    let cancelled_body = serde_json::to_vec(&cancelled).map_err(|error| {
                        format!("legacy cancellation notification did not serialize: {error}")
                    })?;
                    let cancelled = live_http_exchange(
                        address,
                        live_http_post(
                            &format!("/messages?session_id={session_id}"),
                            &cancelled_body,
                            &[],
                        ),
                    )
                    .await?;
                    if !cancelled.starts_with(b"HTTP/1.1 202") {
                        return Err(format!(
                            "legacy cancellation control POST was not accepted while request ran: {cancelled:?}"
                        ));
                    }
                    let call_response = call
                        .join(&client_cx)
                        .await
                        .map_err(|error| {
                            format!("legacy cancellation call task failed: {error:?}")
                        })??;
                    if !call_response.starts_with(b"HTTP/1.1 202") {
                        return Err(format!(
                            "legacy cancellation call acknowledgement was unexpected: {call_response:?}"
                        ));
                    }
                    if !observed_by_server.load(Ordering::Acquire) {
                        return Err(
                            "legacy cancellation notification did not reach the running handler"
                                .to_string(),
                        );
                    }
                    caller_cx.cancel_with(CancelKind::User, Some("legacy cancellation complete"));
                    Ok(())
                })
                .map_err(|error| format!("legacy cancellation client admission failed: {error}"))?;

            let serve = bound.serve(&cx).await;
            client
                .join(&cx)
                .await
                .map_err(|error| format!("legacy cancellation client failed: {error:?}"))??;
            let shutdown =
                serve.map_err(|error| format!("legacy cancellation server failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "legacy cancellation").await?;
            if !observed_cancellation.load(Ordering::Acquire) {
                return Err("live HTTP legacy handler did not observe cancellation".to_string());
            }
            Ok(())
        });
    }

    // Exact-2024 era: legacy HTTP SSE peer close.
    #[cfg(feature = "legacy-2024-11-05")]
    async fn live_http_legacy_sse_peer_close_probe(
        cx: &Cx,
        close_originating_peer: bool,
    ) -> Result<(), String> {
        const INITIALIZE_ID: i64 = 835;
        const TOOL_CALL_ID: i64 = 836;

        let started = Arc::new(AtomicBool::new(false));
        let observed_cancellation = Arc::new(AtomicBool::new(false));
        let observed_by_handler = Arc::clone(&observed_cancellation);
        let bound = Server::new("live-http-legacy-peer-close", "1.0.0")
            .tool(LiveLegacyCancellationTool {
                started: Arc::clone(&started),
                observed_cancellation: Arc::clone(&observed_cancellation),
            })
            .build()
            .bind_http(cx, "127.0.0.1:0")
            .await
            .map_err(|error| format!("legacy peer-close HTTP bind failed: {error}"))?;
        let address = bound
            .local_addr()
            .map_err(|error| format!("legacy peer-close HTTP address failed: {error}"))?;
        let caller_cx = cx.clone();
        let mut client = cx
            .spawn(move |client_cx| async move {
                let (originating_sse, session_id, _) =
                    open_live_legacy_http_session(address, &[]).await?;
                let (other_sse, _, _) = open_live_legacy_http_session(address, &[]).await?;
                for request in [
                    JsonRpcRequest::new(
                        "initialize",
                        Some(serde_json::json!({
                            "protocolVersion": LEGACY_PROTOCOL_VERSION,
                            "capabilities": {},
                            "clientInfo": {
                                "name": "legacy-peer-close-client",
                                "version": "1.0.0"
                            },
                        })),
                        INITIALIZE_ID,
                    ),
                    JsonRpcRequest::notification("notifications/initialized", None),
                ] {
                    let body = serde_json::to_vec(&request).map_err(|error| {
                        format!("legacy peer-close setup request did not serialize: {error}")
                    })?;
                    let response = live_http_exchange(
                        address,
                        live_http_post(&format!("/messages?session_id={session_id}"), &body, &[]),
                    )
                    .await?;
                    if !response.starts_with(b"HTTP/1.1 202") {
                        return Err(format!(
                            "legacy peer-close setup request was not accepted: {response:?}"
                        ));
                    }
                }

                let call = JsonRpcRequest::new(
                    "tools/call",
                    Some(serde_json::json!({
                        "name": "live_legacy_cancellation_tool",
                        "arguments": {},
                    })),
                    TOOL_CALL_ID,
                );
                let call_body = serde_json::to_vec(&call).map_err(|error| {
                    format!("legacy peer-close tool call did not serialize: {error}")
                })?;
                let mut call = client_cx
                    .spawn(move |_call_cx| async move {
                        live_http_exchange(
                            address,
                            live_http_post(
                                &format!("/messages?session_id={session_id}"),
                                &call_body,
                                &[],
                            ),
                        )
                        .await
                    })
                    .map_err(|error| {
                        format!("legacy peer-close tool call was not admitted: {error}")
                    })?;
                wait_for_live_http_flag(&client_cx, &started, "legacy peer-close handler start")
                    .await?;

                let mut originating_sse = Some(originating_sse);
                if close_originating_peer {
                    drop(originating_sse.take());
                    wait_for_live_http_flag(
                        &client_cx,
                        &observed_by_handler,
                        "originating legacy SSE peer close cancellation",
                    )
                    .await?;
                    drop(other_sse);
                } else {
                    // The near-identical negative closes only the unrelated
                    // SSE peer.  Its deadline proves cancellation remains
                    // isolated to the originating exact-2024 session.
                    drop(other_sse);
                    let deadline = client_cx.now().saturating_add_nanos(100_000_000);
                    if asupersync::time::timeout_at(
                        deadline,
                        wait_for_live_http_flag(
                            &client_cx,
                            &observed_by_handler,
                            "unrelated legacy SSE peer close",
                        ),
                    )
                    .await
                    .is_ok()
                    {
                        return Err(
                            "unrelated legacy SSE peer close cancelled the active request"
                                .to_string(),
                        );
                    }
                    drop(originating_sse.take());
                    wait_for_live_http_flag(
                        &client_cx,
                        &observed_by_handler,
                        "originating legacy SSE peer close after isolation check",
                    )
                    .await?;
                }

                let call_response = call
                    .join(&client_cx)
                    .await
                    .map_err(|error| format!("legacy peer-close tool call failed: {error:?}"))??;
                if !call_response.starts_with(b"HTTP/1.1 202") {
                    return Err(format!(
                        "legacy peer-close tool acknowledgement was unexpected: {call_response:?}"
                    ));
                }
                caller_cx.cancel_with(CancelKind::User, Some("legacy peer-close probe complete"));
                Ok::<_, String>(())
            })
            .map_err(|error| format!("legacy peer-close client was not admitted: {error}"))?;

        let serve = bound.serve(cx).await;
        let client_result = client
            .join(cx)
            .await
            .map_err(|error| format!("legacy peer-close client failed: {error:?}"));
        client_result??;
        let shutdown =
            serve.map_err(|error| format!("legacy peer-close server failed: {error}"))?;
        require_quiescent_http_shutdown(shutdown, "legacy peer-close").await?;
        if !observed_cancellation.load(Ordering::Acquire) {
            return Err("originating legacy peer close did not cancel its request".to_string());
        }
        Ok(())
    }

    // Exact-2024 era: legacy HTTP SSE peer close.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_http_legacy_sse_peer_close_cancels_its_busy_request() {
        run_live_http_test(
            |cx| async move { live_http_legacy_sse_peer_close_probe(&cx, true).await },
        );
    }

    // Exact-2024 era: legacy HTTP SSE peer close.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_http_legacy_sse_peer_close_does_not_cancel_another_session() {
        run_live_http_test(|cx| async move {
            // This differs from the positive only in the SSE peer that closes.
            live_http_legacy_sse_peer_close_probe(&cx, false).await
        });
    }

    // Exact-2024 era: hosts its child in a legacy HTTP SSE session.
    #[cfg(feature = "legacy-2024-11-05")]
    async fn live_http_shutdown_ownership_probe(
        cx: &Cx,
        cooperate_with_cancellation: bool,
    ) -> Result<(), String> {
        struct ReleaseOnExit(Arc<AtomicBool>);

        impl Drop for ReleaseOnExit {
            fn drop(&mut self) {
                self.0.store(true, Ordering::Release);
            }
        }

        let started = Arc::new(AtomicBool::new(false));
        let cancellation_observed = Arc::new(AtomicBool::new(false));
        let release = Arc::new(AtomicBool::new(false));
        // A failed observation must release the deliberately parked handler
        // before runtime teardown joins its blocking thread.
        let _release_on_exit = ReleaseOnExit(Arc::clone(&release));
        let finished = Arc::new(AtomicBool::new(false));
        let tool_name = if cooperate_with_cancellation {
            "live_http_cooperative_shutdown_tool"
        } else {
            "live_http_noncooperative_shutdown_tool"
        };
        let bound = Server::new("live-http-shutdown-ownership", "1.0.0")
            .tool(LiveHttpShutdownTool {
                name: tool_name,
                cooperate_with_cancellation,
                started: Arc::clone(&started),
                cancellation_observed: Arc::clone(&cancellation_observed),
                release: Arc::clone(&release),
                finished: Arc::clone(&finished),
            })
            .build()
            .bind_http(cx, "127.0.0.1:0")
            .await
            .map_err(|error| format!("shutdown-ownership HTTP bind failed: {error}"))?;
        let address = bound
            .local_addr()
            .map_err(|error| format!("shutdown-ownership HTTP address failed: {error}"))?;
        let caller_cx = cx.clone();
        let started_by_client = Arc::clone(&started);
        let mut client = cx
            .spawn(move |client_cx| async move {
                let (sse, session_id, _) = open_live_legacy_http_session(address, &[]).await?;
                for request in [
                    JsonRpcRequest::new(
                        "initialize",
                        Some(serde_json::json!({
                            "protocolVersion": LEGACY_PROTOCOL_VERSION,
                            "capabilities": {},
                            "clientInfo": {
                                "name": "shutdown-ownership-client",
                                "version": "1.0.0"
                            },
                        })),
                        841_i64,
                    ),
                    JsonRpcRequest::notification("notifications/initialized", None),
                ] {
                    let body = serde_json::to_vec(&request).map_err(|error| {
                        format!("shutdown-ownership setup request did not serialize: {error}")
                    })?;
                    let response = live_http_exchange(
                        address,
                        live_http_post(&format!("/messages?session_id={session_id}"), &body, &[]),
                    )
                    .await?;
                    if !response.starts_with(b"HTTP/1.1 202") {
                        return Err(format!(
                            "shutdown-ownership setup request was not accepted: {response:?}"
                        ));
                    }
                }
                let call = JsonRpcRequest::new(
                    "tools/call",
                    Some(serde_json::json!({"name": tool_name, "arguments": {}})),
                    842_i64,
                );
                let call_body = serde_json::to_vec(&call).map_err(|error| {
                    format!("shutdown-ownership tool call did not serialize: {error}")
                })?;
                let call = client_cx
                    .spawn(move |_call_cx| async move {
                        live_http_exchange(
                            address,
                            live_http_post(
                                &format!("/messages?session_id={session_id}"),
                                &call_body,
                                &[],
                            ),
                        )
                        .await
                    })
                    .map_err(|error| {
                        format!("shutdown-ownership tool call was not admitted: {error}")
                    })?;
                wait_for_live_http_flag(
                    &client_cx,
                    &started_by_client,
                    "shutdown-ownership handler start",
                )
                .await?;
                caller_cx.cancel_with(
                    CancelKind::User,
                    Some("live HTTP shutdown ownership probe complete"),
                );
                Ok::<_, String>((sse, call))
            })
            .map_err(|error| format!("shutdown-ownership client was not admitted: {error}"))?;

        // This probe deliberately cancels the caller. A timeout_at wrapper
        // would mistake its cancellation-aware timer's early completion for
        // deadline expiry while the server is still settling its children.
        let shutdown = bound
            .serve(cx)
            .await
            .map_err(|error| format!("shutdown-ownership server failed: {error}"))?;
        let (_sse, _call) = client
            .join(cx)
            .await
            .map_err(|error| format!("shutdown-ownership client failed: {error:?}"))??;
        if !cancellation_observed.load(Ordering::Acquire) {
            return Err("live HTTP shutdown did not reach the busy handler".to_owned());
        }

        match (cooperate_with_cancellation, shutdown) {
            (true, HttpServerShutdown::Quiescent) if finished.load(Ordering::Acquire) => Ok(()),
            (true, HttpServerShutdown::Quiescent) => {
                Err("cooperative HTTP handler was joined before recording completion".to_owned())
            }
            (true, HttpServerShutdown::Nonquiescent(mut shutdown)) => {
                let initial = shutdown.poll_settlement();
                let settled = shutdown.settle_for(Duration::from_secs(1)).await;
                Err(format!(
                    "cooperative HTTP shutdown unexpectedly retained children: initial={initial:?}, after bounded settlement={settled:?}"
                ))
            }
            (false, HttpServerShutdown::Quiescent) => {
                Err("non-cooperative HTTP handler was falsely reported as quiescent".to_owned())
            }
            (false, HttpServerShutdown::Nonquiescent(mut shutdown)) => {
                if finished.load(Ordering::Acquire) {
                    return Err(
                        "non-cooperative HTTP handler completed before its retained outcome"
                            .to_owned(),
                    );
                }
                if !matches!(
                    shutdown.poll_settlement(),
                    HttpShutdownSettlement::Pending { remaining } if remaining > 0
                ) {
                    return Err(
                        "non-cooperative HTTP shutdown did not return its live child handle"
                            .to_owned(),
                    );
                }
                release.store(true, Ordering::Release);
                let deadline = Instant::now() + Duration::from_secs(1);
                while !finished.load(Ordering::Acquire) {
                    if Instant::now() >= deadline {
                        return Err(
                            "released non-cooperative HTTP handler did not complete".to_owned()
                        );
                    }
                    asupersync::runtime::yield_now().await;
                }
                shutdown
                    .settle(cx)
                    .await
                    .map_err(|error| format!("caller-owned HTTP child join failed: {error}"))
            }
        }
    }

    // Exact-2024 era: hosts its child in a legacy HTTP SSE session.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_http_shutdown_joins_a_cooperative_child() {
        run_live_http_test(|cx| async move { live_http_shutdown_ownership_probe(&cx, true).await });
    }

    // Exact-2024 era: hosts its child in a legacy HTTP SSE session.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_http_shutdown_returns_caller_owned_noncooperative_child_for_later_join() {
        run_live_http_test(|cx| async move {
            // This differs from the positive only in the handler's
            // cancellation cooperation, preserving the same live HTTP path.
            live_http_shutdown_ownership_probe(&cx, false).await
        });
    }

    #[test]
    fn live_http_cancellation_wakes_idle_listener_and_connection_read() {
        run_live_http_test(|cx| async move {
            let listener_wait_before = live_http_listener_wait_count();
            let listener = Server::new("idle-listener-http", "1.0.0")
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("idle listener bind failed: {error}"))?;
            let caller_cx = cx.clone();
            let mut canceller = cx
                .spawn(move |canceller_cx| async move {
                    if let Err(error) = wait_for_live_http_probe(
                        &canceller_cx,
                        listener_wait_before,
                        live_http_listener_wait_count,
                    )
                    .await
                    {
                        caller_cx
                            .cancel_with(CancelKind::User, Some("idle listener probe timed out"));
                        return Err(error);
                    }
                    caller_cx.cancel_with(CancelKind::User, Some("idle listener cancellation"));
                    Ok(())
                })
                .map_err(|error| format!("idle listener canceller admission failed: {error}"))?;
            let shutdown = listener
                .serve(&cx)
                .await
                .map_err(|error| format!("idle listener serve failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "idle listener").await?;
            canceller
                .join(&cx)
                .await
                .map_err(|error| format!("idle listener canceller failed: {error:?}"))??;
            Ok(())
        });

        run_live_http_test(|cx| async move {
            let read_wait_before = live_http_connection_read_wait_count();
            let listener = Server::new("idle-connection-http", "1.0.0")
                .build()
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("idle connection bind failed: {error}"))?;
            let address = listener
                .local_addr()
                .map_err(|error| format!("idle connection address failed: {error}"))?;
            let caller_cx = cx.clone();
            let mut client = cx
                .spawn(move |client_cx| async move {
                    let mut stream = AsyncTcpStream::connect(address)
                        .await
                        .map_err(|error| format!("idle client connect failed: {error}"))?;
                    stream
                        .write_all(b"POST /mcp HTTP/1.1\r\nHost: loopback\r\n")
                        .await
                        .map_err(|error| format!("idle client partial write failed: {error}"))?;
                    stream
                        .flush()
                        .await
                        .map_err(|error| format!("idle client partial flush failed: {error}"))?;
                    if let Err(error) = wait_for_live_http_probe(
                        &client_cx,
                        read_wait_before,
                        live_http_connection_read_wait_count,
                    )
                    .await
                    {
                        caller_cx.cancel_with(
                            CancelKind::User,
                            Some("idle connection probe timed out"),
                        );
                        return Err(error);
                    }
                    caller_cx.cancel_with(CancelKind::User, Some("idle connection cancellation"));

                    let mut byte = [0_u8; 1];
                    match stream.read(&mut byte).await {
                        Ok(0) | Err(_) => Ok(()),
                        Ok(read) => Err(format!(
                            "idle connection remained live after server cancellation ({read} byte response)"
                        )),
                    }
                })
                .map_err(|error| format!("idle connection client admission failed: {error}"))?;
            let shutdown = listener
                .serve(&cx)
                .await
                .map_err(|error| format!("idle connection serve failed: {error}"))?;
            require_quiescent_http_shutdown(shutdown, "idle connection").await?;
            client
                .join(&cx)
                .await
                .map_err(|error| format!("idle connection client failed: {error:?}"))??;
            Ok(())
        });
    }

    // Exact-2024 era: legacy HTTP SSE lifecycle.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn builder_http_endpoint_dispatches_exact_legacy_lifecycle_end_to_end() {
        let cx = Cx::for_testing();
        let endpoint = Server::new("legacy-http-endpoint", "1.0.0")
            .tool(LiveRuntimeListedTool)
            .build_http_endpoint("http://legacy.test")
            .expect("builder must construct the configured dual-era endpoint");
        let mut session = endpoint
            .open_session(&cx)
            .expect("endpoint must open a bounded live session");
        let stream = block_on(session.handle_async(&cx, HttpRequest::new(HttpMethod::Get, "/sse")))
            .expect("legacy SSE route must open");
        let ServerHttpEndpointResponse::LegacySse(mut stream) = stream else {
            panic!("legacy GET must open an exact SSE stream");
        };
        assert_eq!(
            stream
                .recv_event(&cx)
                .expect("legacy stream must advertise its exact POST endpoint")
                .data,
            format!(
                "http://legacy.test/messages?session_id={}",
                session.legacy_session_id()
            )
        );

        let legacy_session_id = session.legacy_session_id().to_owned();
        let post = |message: JsonRpcRequest| {
            HttpRequest::new(HttpMethod::Post, "/messages")
                .with_header("content-type", "application/json")
                .with_query("session_id", legacy_session_id.clone())
                .with_body(serde_json::to_vec(&message).expect("legacy request must serialize"))
        };
        let initialize = JsonRpcRequest::new(
            "initialize",
            Some(serde_json::json!({
                "protocolVersion": LEGACY_PROTOCOL_VERSION,
                "capabilities": {},
                "clientInfo": {"name": "legacy-http-client", "version": "1.0.0"},
            })),
            211_i64,
        );
        let initialized = JsonRpcRequest::notification("notifications/initialized", None);
        let call = JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({
                "name": "live_runtime_listed_tool",
                "arguments": {},
            })),
            212_i64,
        );

        for request in [initialize, initialized, call] {
            let response = block_on(session.handle_async(&cx, post(request)))
                .expect("advertised legacy POST must be dispatched");
            let ServerHttpEndpointResponse::Immediate(response) = response else {
                panic!("legacy POST acknowledgement must be immediate");
            };
            assert_eq!(response.status, HttpStatus::ACCEPTED);
        }

        let codec = Codec::new();
        let initialize = stream
            .recv_event(&cx)
            .expect("legacy initialize response must stream over the open SSE session");
        assert!(matches!(
            codec
                .decode_complete_message(initialize.data.as_bytes())
                .expect("initialize event must remain JSON-RPC"),
            JsonRpcMessage::Response(response)
                if response.id == Some(211_i64.into())
                    && response
                        .result
                        .as_ref()
                        .and_then(|result| result["protocolVersion"].as_str())
                        == Some(LEGACY_PROTOCOL_VERSION)
        ));
        let call = stream
            .recv_event(&cx)
            .expect("legacy tool response must stream over the exact SSE session");
        assert!(matches!(
            codec
                .decode_complete_message(call.data.as_bytes())
                .expect("tool event must remain JSON-RPC"),
            JsonRpcMessage::Response(response)
                if response.id == Some(212_i64.into())
                    && response
                        .result
                        .as_ref()
                        .is_some_and(|result| result.get("resultType").is_none())
        ));
    }

    // Exact-2024 era: legacy HTTP SSE opener binding.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn public_http_legacy_sse_binds_opener_principal_before_post() {
        let cx = Cx::for_testing();
        let verifier = StaticTokenVerifier::new([
            ("alpha", AuthContext::with_subject("alice")),
            ("beta", AuthContext::with_subject("bob")),
        ])
        .expect("valid verifier configuration")
        .with_allowed_schemes(["Bearer"])
        .expect("valid scheme configuration");
        // The session binds the context the installed provider admits. For
        // these subject-only contexts that includes the owner the provider
        // derives (756719c3), in a namespace its clones share. So derive each
        // expected fingerprint by admitting the credential through it.
        let provider = TokenAuthProvider::new(verifier);
        let admitted_fingerprint = |token: &str| {
            let authorization = format!("Bearer {token}");
            let admitted = provider
                .authenticate(
                    &McpContext::new(cx.clone(), 0),
                    AuthRequest {
                        method: "initialize",
                        params: None,
                        transport_authorization: Some(&authorization),
                        request_id: 0,
                    },
                )
                .expect("the installed provider admits its own credential");
            crate::auth::principal_fingerprint(Some(&admitted)).expect("admitted fingerprint")
        };
        let alice = admitted_fingerprint("alpha");
        let bob = admitted_fingerprint("beta");
        let endpoint = Server::new("legacy-sse-owner", "1.0.0")
            .tool(LiveRuntimeListedTool)
            .auth_provider(provider.clone())
            .build_http_endpoint("http://legacy.test")
            .expect("dual-era endpoint must build");
        let mut session = endpoint
            .open_session(&cx)
            .expect("endpoint must open a bounded live session");

        let denied = block_on(session.handle_async(&cx, HttpRequest::new(HttpMethod::Get, "/sse")))
            .expect("unauthenticated GET must be answered");
        assert!(
            matches!(
                denied,
                ServerHttpEndpointResponse::Immediate(response)
                    if response.status == HttpStatus::UNAUTHORIZED
            ),
            "GET /sse without a token must fail closed when a verifier is installed"
        );

        let stream = block_on(session.handle_async(
            &cx,
            HttpRequest::new(HttpMethod::Get, "/sse").with_header("Authorization", "Bearer alpha"),
        ))
        .expect("authenticated GET must open");
        let ServerHttpEndpointResponse::LegacySse(mut stream) = stream else {
            panic!("authenticated GET must open an exact SSE stream");
        };
        assert!(
            session
                .legacy_session
                .principal_binding()
                .verify_existing(alice),
            "GET /sse must bind the opener before any POST"
        );
        assert!(
            !session
                .legacy_session
                .principal_binding()
                .verify_existing(bob),
            "GET /sse must not bind a different principal"
        );

        let _ = stream
            .recv_event(&cx)
            .expect("legacy stream must advertise its exact POST endpoint");
        let legacy_session_id = session.legacy_session_id().to_owned();
        let post = |message: JsonRpcRequest, token: &str| {
            HttpRequest::new(HttpMethod::Post, "/messages")
                .with_header("content-type", "application/json")
                .with_header("Authorization", format!("Bearer {token}"))
                .with_query("session_id", legacy_session_id.clone())
                .with_body(serde_json::to_vec(&message).expect("legacy request must serialize"))
        };
        let initialize = JsonRpcRequest::new(
            "initialize",
            Some(serde_json::json!({
                "protocolVersion": LEGACY_PROTOCOL_VERSION,
                "capabilities": {},
                "clientInfo": {"name": "legacy-http-client", "version": "1.0.0"},
            })),
            311_i64,
        );
        let initialized = JsonRpcRequest::notification("notifications/initialized", None);
        let foreign_call = JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({
                "name": "live_runtime_listed_tool",
                "arguments": {},
            })),
            312_i64,
        );
        let owned_call = JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({
                "name": "live_runtime_listed_tool",
                "arguments": {},
            })),
            313_i64,
        );

        for request in [initialize, initialized] {
            let response = block_on(session.handle_async(&cx, post(request, "alpha")))
                .expect("opener POST must be dispatched");
            let ServerHttpEndpointResponse::Immediate(response) = response else {
                panic!("legacy POST acknowledgement must be immediate");
            };
            assert_eq!(response.status, HttpStatus::ACCEPTED);
        }
        let codec = Codec::new();
        let initialize_event = stream
            .recv_event(&cx)
            .expect("opener initialize response must stream");
        assert!(matches!(
            codec
                .decode_complete_message(initialize_event.data.as_bytes())
                .expect("initialize event must remain JSON-RPC"),
            JsonRpcMessage::Response(response)
                if response.id == Some(311_i64.into()) && response.error.is_none()
        ));

        let foreign = block_on(session.handle_async(&cx, post(foreign_call, "beta")))
            .expect("foreign POST must be answered");
        let ServerHttpEndpointResponse::Immediate(foreign) = foreign else {
            panic!("foreign legacy POST acknowledgement must be immediate");
        };
        assert_eq!(foreign.status, HttpStatus::ACCEPTED);
        let foreign_event = stream
            .recv_event(&cx)
            .expect("foreign tool response must stream");
        assert!(matches!(
            codec
                .decode_complete_message(foreign_event.data.as_bytes())
                .expect("foreign tool event must remain JSON-RPC"),
            JsonRpcMessage::Response(response)
                if response.id == Some(312_i64.into()) && response.error.is_some()
        ));

        let owned = block_on(session.handle_async(&cx, post(owned_call, "alpha")))
            .expect("opener tool call must be dispatched");
        let ServerHttpEndpointResponse::Immediate(owned) = owned else {
            panic!("opener tool call acknowledgement must be immediate");
        };
        assert_eq!(owned.status, HttpStatus::ACCEPTED);
        let owned_event = stream
            .recv_event(&cx)
            .expect("opener tool response must stream");
        assert!(matches!(
            codec
                .decode_complete_message(owned_event.data.as_bytes())
                .expect("opener tool event must remain JSON-RPC"),
            JsonRpcMessage::Response(response)
                if response.id == Some(313_i64.into())
                    && response.error.is_none()
                    && response
                        .result
                        .as_ref()
                        .is_some_and(|result| result.get("resultType").is_none())
        ));
    }

    // Exact-2024 era: legacy HTTP SSE session runtime.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn legacy_http_runtime_retains_session_state_progress_and_log_level() {
        let cx = Cx::for_testing();
        let endpoint = Server::new("legacy-http-runtime", "1.0.0")
            .log_level(Level::Debug)
            .tool(LiveLegacyRuntimeConnectionTool)
            .build_http_endpoint("http://legacy.test")
            .expect("builder must construct the configured dual-era endpoint");
        let mut session = endpoint
            .open_session(&cx)
            .expect("endpoint must open a bounded live session");
        let ServerHttpEndpointResponse::LegacySse(mut stream) =
            block_on(session.handle_async(&cx, HttpRequest::new(HttpMethod::Get, "/sse")))
                .expect("legacy SSE route must open")
        else {
            panic!("legacy GET must open an exact SSE stream");
        };
        let _endpoint = stream
            .recv_event(&cx)
            .expect("legacy stream must advertise its POST endpoint");
        let session_id = session.legacy_session_id().to_owned();
        let post = |message: JsonRpcRequest| {
            HttpRequest::new(HttpMethod::Post, "/messages")
                .with_header("content-type", "application/json")
                .with_query("session_id", session_id.clone())
                .with_body(serde_json::to_vec(&message).expect("message must serialize"))
        };

        for request in [
            JsonRpcRequest::new(
                "initialize",
                Some(serde_json::json!({
                    "protocolVersion": LEGACY_PROTOCOL_VERSION,
                    "capabilities": {},
                    "clientInfo": {"name": "legacy-http-client", "version": "1.0.0"},
                })),
                231_i64,
            ),
            JsonRpcRequest::notification("notifications/initialized", None),
            JsonRpcRequest::new(
                "logging/setLevel",
                Some(serde_json::json!({"level": "debug"})),
                232_i64,
            ),
        ] {
            assert!(matches!(
                block_on(session.handle_async(&cx, post(request))),
                Ok(ServerHttpEndpointResponse::Immediate(response)) if response.status == HttpStatus::ACCEPTED
            ));
        }
        let codec = Codec::new();
        let _initialize = stream
            .recv_event(&cx)
            .expect("initialize response must be delivered");
        let _set_level = stream
            .recv_event(&cx)
            .expect("logging response must be delivered");

        for id in [233_i64, 234_i64] {
            let call = JsonRpcRequest::new(
                "tools/call",
                Some(serde_json::json!({
                    "name": "live_legacy_runtime_connection_tool",
                    "arguments": {"sample": false},
                    "_meta": {"progressToken": "legacy-http-runtime-progress"},
                })),
                id,
            );
            assert!(matches!(
                block_on(session.handle_async(&cx, post(call))),
                Ok(ServerHttpEndpointResponse::Immediate(response)) if response.status == HttpStatus::ACCEPTED
            ));
        }

        let mut progress_count = 0;
        let mut log_count = 0;
        let mut results = Vec::new();
        for _ in 0..6 {
            let event = stream
                .recv_event(&cx)
                .expect("each legacy handler output must reach the same SSE stream");
            match codec
                .decode_complete_message(event.data.as_bytes())
                .expect("legacy runtime output must remain JSON-RPC")
            {
                JsonRpcMessage::Request(notification)
                    if notification.method == "notifications/progress" =>
                {
                    progress_count += 1;
                }
                JsonRpcMessage::Request(notification)
                    if notification.method == "notifications/message" =>
                {
                    log_count += 1;
                }
                JsonRpcMessage::Response(response) => {
                    results.push(
                        response
                            .result
                            .and_then(|result| {
                                result["content"][0]["text"].as_str().map(str::to_owned)
                            })
                            .expect("tool response must preserve the runtime counter text"),
                    );
                }
                message => panic!("unexpected legacy HTTP runtime message: {message:?}"),
            }
        }
        assert_eq!(progress_count, 2);
        assert_eq!(log_count, 2);
        assert_eq!(
            results,
            [
                "legacy-runtime-1-without-sampling".to_owned(),
                "legacy-runtime-2-without-sampling".to_owned(),
            ]
        );
        assert_eq!(session.legacy_session.log_level(), Some(LogLevel::Debug));
    }

    // Exact-2024 era: legacy resource subscriptions over HTTP SSE.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn legacy_http_delivers_resource_updates_only_to_the_subscribed_uri() {
        // resources/subscribe admits only URIs the router can resolve, so the
        // subscribed target must exist as a registered resource.
        struct SubscribedFileResource;

        impl crate::ResourceHandler for SubscribedFileResource {
            fn definition(&self) -> Resource {
                Resource {
                    uri: "file:///subscribed.txt".to_string(),
                    name: "subscribed".to_string(),
                    description: None,
                    mime_type: Some("text/plain".to_string()),
                    icon: None,
                    version: None,
                    tags: vec![],
                }
            }

            fn read(&self, _ctx: &McpContext) -> McpResult<Vec<fastmcp_protocol::ResourceContent>> {
                Ok(vec![fastmcp_protocol::ResourceContent {
                    uri: "file:///subscribed.txt".to_string(),
                    mime_type: Some("text/plain".to_string()),
                    text: Some("subscribed".to_string()),
                    blob: None,
                }])
            }
        }

        let cx = Cx::for_testing();
        let endpoint = Server::new("legacy-http-resource-update", "1.0.0")
            .resource(SubscribedFileResource)
            .resource_subscriptions()
            .build_http_endpoint("http://legacy.test")
            .expect("builder must construct the configured dual-era endpoint");
        let mut session = endpoint
            .open_session(&cx)
            .expect("endpoint must open a bounded live session");
        let ServerHttpEndpointResponse::LegacySse(mut stream) =
            block_on(session.handle_async(&cx, HttpRequest::new(HttpMethod::Get, "/sse")))
                .expect("legacy SSE route must open")
        else {
            panic!("legacy GET must open an exact SSE stream");
        };
        let _endpoint = stream.recv_event(&cx).expect("legacy endpoint event");
        let session_id = session.legacy_session_id().to_owned();
        let post = |message: JsonRpcRequest| {
            HttpRequest::new(HttpMethod::Post, "/messages")
                .with_header("content-type", "application/json")
                .with_query("session_id", session_id.clone())
                .with_body(serde_json::to_vec(&message).expect("message must serialize"))
        };
        for request in [
            JsonRpcRequest::new(
                "initialize",
                Some(serde_json::json!({
                    "protocolVersion": LEGACY_PROTOCOL_VERSION,
                    "capabilities": {},
                    "clientInfo": {"name": "legacy-http-client", "version": "1.0.0"},
                })),
                241_i64,
            ),
            JsonRpcRequest::notification("notifications/initialized", None),
            JsonRpcRequest::new(
                "resources/subscribe",
                Some(serde_json::json!({"uri": "file:///subscribed.txt"})),
                242_i64,
            ),
        ] {
            assert!(matches!(
                block_on(session.handle_async(&cx, post(request))),
                Ok(ServerHttpEndpointResponse::Immediate(response)) if response.status == HttpStatus::ACCEPTED
            ));
        }
        let _initialize = stream.recv_event(&cx).expect("initialize response");
        let _subscribe = stream.recv_event(&cx).expect("subscribe response");

        assert!(session.notify_legacy_resource_updated("file:///subscribed.txt"));
        let update = stream
            .recv_event(&cx)
            .expect("subscribed update must stream");
        assert!(matches!(
            Codec::new()
                .decode_complete_message(update.data.as_bytes())
                .expect("resource update must remain JSON-RPC"),
            JsonRpcMessage::Request(notification)
                if notification.method == "notifications/resources/updated"
                    && notification.params == Some(serde_json::json!({"uri": "file:///subscribed.txt"}))
        ));

        let before = session
            .legacy_adapter
            .as_ref()
            .expect("subscription retains the exact adapter")
            .snapshot();
        assert!(
            !session.notify_legacy_resource_updated("file:///other.txt"),
            "changing only the URI must not emit a resource update"
        );
        assert_eq!(
            session
                .legacy_adapter
                .as_ref()
                .expect("negative must retain the exact adapter")
                .snapshot(),
            before,
            "the rejected URI must leave subscription state unchanged"
        );
        assert!(
            stream
                .try_recv_event(&cx)
                .expect("unsubscribed update check must not fail")
                .is_none()
        );
    }

    /// The live exact-2024 HTTP handler serves requests only through its async
    /// hook; its synchronous hook refuses instead of blocking on the request.
    // Exact-2024 era: legacy HTTP SSE session runtime.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn legacy_http_runtime_handler_serves_requests_only_through_the_async_hook() {
        struct ListedResource;

        impl crate::ResourceHandler for ListedResource {
            fn definition(&self) -> Resource {
                Resource {
                    uri: "file:///listed.txt".to_string(),
                    name: "listed".to_string(),
                    description: None,
                    mime_type: Some("text/plain".to_string()),
                    icon: None,
                    version: None,
                    tags: vec![],
                }
            }

            fn read(&self, _ctx: &McpContext) -> McpResult<Vec<fastmcp_protocol::ResourceContent>> {
                Ok(vec![])
            }
        }

        let cx = Cx::for_testing();
        let endpoint = Server::new("legacy-http-async-hook", "1.0.0")
            .resource(ListedResource)
            .build_http_endpoint("http://legacy.test")
            .expect("builder must construct the configured dual-era endpoint");
        let mut session = endpoint
            .open_session(&cx)
            .expect("endpoint must open a bounded live session");
        let ServerHttpEndpointResponse::LegacySse(mut stream) =
            block_on(session.handle_async(&cx, HttpRequest::new(HttpMethod::Get, "/sse")))
                .expect("legacy SSE route must open")
        else {
            panic!("legacy GET must open an exact SSE stream");
        };
        let _endpoint = stream.recv_event(&cx).expect("legacy endpoint event");
        let session_id = session.legacy_session_id().to_owned();
        let post = |message: JsonRpcRequest| {
            HttpRequest::new(HttpMethod::Post, "/messages")
                .with_header("content-type", "application/json")
                .with_query("session_id", session_id.clone())
                .with_body(serde_json::to_vec(&message).expect("message must serialize"))
        };
        let list = |id: i64| JsonRpcRequest::new("resources/list", Some(serde_json::json!({})), id);
        for request in [
            JsonRpcRequest::new(
                "initialize",
                Some(serde_json::json!({
                    "protocolVersion": LEGACY_PROTOCOL_VERSION,
                    "capabilities": {},
                    "clientInfo": {"name": "legacy-http-client", "version": "1.0.0"},
                })),
                251_i64,
            ),
            JsonRpcRequest::notification("notifications/initialized", None),
            list(252),
        ] {
            assert!(matches!(
                block_on(session.handle_async(&cx, post(request))),
                Ok(ServerHttpEndpointResponse::Immediate(response)) if response.status == HttpStatus::ACCEPTED
            ));
        }
        let _initialize = stream.recv_event(&cx).expect("initialize response");
        let listed = stream.recv_event(&cx).expect("resources/list response");
        let JsonRpcMessage::Response(listed) = Codec::new()
            .decode_complete_message(listed.data.as_bytes())
            .expect("the listing must remain JSON-RPC")
        else {
            panic!("resources/list must answer with a response");
        };
        assert!(listed.error.is_none(), "{listed:?}");
        assert_eq!(
            listed.result.as_ref().expect("listing result")["resources"][0]["uri"],
            "file:///listed.txt"
        );

        // Near-identical negative: the same request on the same adapter's
        // synchronous entry point is refused instead of being dispatched.
        let binding = session.legacy_binding;
        let wire = serde_json::to_value(list(253)).expect("request must serialize");
        let refused = session
            .legacy_adapter
            .as_mut()
            .expect("the session installed its exact adapter")
            .receive(binding, wire)
            .expect("a handler refusal is answered on the wire");
        let Legacy2024Outbound::Response(refused) = refused else {
            panic!("a request must be answered: {refused:?}");
        };
        assert_eq!(refused["error"]["code"], -32603, "{refused}");
        assert_eq!(
            refused["error"]["message"], LIVE_LEGACY_SYNC_DISPATCH_REFUSED,
            "{refused}"
        );
    }

    // Exact-2024 era: legacy roots provider over HTTP SSE.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn legacy_http_roots_provider_requires_only_the_roots_capability() {
        let cx = Cx::for_testing();
        let endpoint = Server::new("legacy-http-roots", "1.0.0")
            .build_http_endpoint("http://legacy.test")
            .expect("builder must construct the configured dual-era endpoint");
        let mut session = endpoint
            .open_session(&cx)
            .expect("endpoint must open a bounded live session");
        let ServerHttpEndpointResponse::LegacySse(mut stream) =
            block_on(session.handle_async(&cx, HttpRequest::new(HttpMethod::Get, "/sse")))
                .expect("legacy SSE route must open")
        else {
            panic!("legacy GET must open an exact SSE stream");
        };
        let _endpoint = stream.recv_event(&cx).expect("legacy endpoint event");
        let session_id = session.legacy_session_id().to_owned();
        let post = |message: JsonRpcRequest| {
            HttpRequest::new(HttpMethod::Post, "/messages")
                .with_header("content-type", "application/json")
                .with_query("session_id", session_id.clone())
                .with_body(serde_json::to_vec(&message).expect("message must serialize"))
        };
        for request in [
            JsonRpcRequest::new(
                "initialize",
                Some(serde_json::json!({
                    "protocolVersion": LEGACY_PROTOCOL_VERSION,
                    "capabilities": {"roots": {}},
                    "clientInfo": {"name": "legacy-http-client", "version": "1.0.0"},
                })),
                251_i64,
            ),
            JsonRpcRequest::notification("notifications/initialized", None),
        ] {
            assert!(matches!(
                block_on(session.handle_async(&cx, post(request))),
                Ok(ServerHttpEndpointResponse::Immediate(response)) if response.status == HttpStatus::ACCEPTED
            ));
        }
        let _initialize = stream.recv_event(&cx).expect("initialize response");

        let provider = session
            .legacy_roots_provider()
            .expect("roots capability must expose the shipped provider");
        let roots_task = std::thread::spawn(move || block_on(provider.list_roots()));
        let request = stream
            .recv_event(&cx)
            .expect("roots provider must emit a reverse request");
        let JsonRpcMessage::Request(request) = Codec::new()
            .decode_complete_message(request.data.as_bytes())
            .expect("roots reverse request must remain JSON-RPC")
        else {
            panic!("roots provider must emit a request");
        };
        assert_eq!(request.method, "roots/list");
        let response = JsonRpcResponse::success(
            request.id.expect("roots request must have an ID"),
            serde_json::json!({"roots": [{"uri": "file:///work", "name": "work"}]}),
        );
        let response_post = HttpRequest::new(HttpMethod::Post, "/messages")
            .with_header("content-type", "application/json")
            .with_query("session_id", session.legacy_session_id())
            .with_body(serde_json::to_vec(&response).expect("response must serialize"));
        assert!(matches!(
            block_on(session.handle_async(&cx, response_post)),
            Ok(ServerHttpEndpointResponse::Immediate(response)) if response.status == HttpStatus::ACCEPTED
        ));
        let roots = roots_task
            .join()
            .expect("roots task must not panic")
            .expect("routed roots response must complete the provider");
        assert_eq!(roots.len(), 1);
        assert_eq!(roots[0].uri, "file:///work");
    }

    // Exact-2024 era: legacy roots provider over HTTP SSE.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn legacy_http_roots_provider_is_absent_without_roots_capability() {
        let cx = Cx::for_testing();
        let endpoint = Server::new("legacy-http-roots", "1.0.0")
            .build_http_endpoint("http://legacy.test")
            .expect("builder must construct the configured dual-era endpoint");
        let mut session = endpoint
            .open_session(&cx)
            .expect("endpoint must open a bounded live session");
        let ServerHttpEndpointResponse::LegacySse(mut stream) =
            block_on(session.handle_async(&cx, HttpRequest::new(HttpMethod::Get, "/sse")))
                .expect("legacy SSE route must open")
        else {
            panic!("legacy GET must open an exact SSE stream");
        };
        let _endpoint = stream.recv_event(&cx).expect("legacy endpoint event");
        let session_id = session.legacy_session_id().to_owned();
        let post = |message: JsonRpcRequest| {
            HttpRequest::new(HttpMethod::Post, "/messages")
                .with_header("content-type", "application/json")
                .with_query("session_id", session_id.clone())
                .with_body(serde_json::to_vec(&message).expect("message must serialize"))
        };
        for request in [
            JsonRpcRequest::new(
                "initialize",
                Some(serde_json::json!({
                    "protocolVersion": LEGACY_PROTOCOL_VERSION,
                    "capabilities": {},
                    "clientInfo": {"name": "legacy-http-client", "version": "1.0.0"},
                })),
                251_i64,
            ),
            JsonRpcRequest::notification("notifications/initialized", None),
        ] {
            assert!(matches!(
                block_on(session.handle_async(&cx, post(request))),
                Ok(ServerHttpEndpointResponse::Immediate(response)) if response.status == HttpStatus::ACCEPTED
            ));
        }
        let _initialize = stream.recv_event(&cx).expect("initialize response");
        assert!(
            session.legacy_roots_provider().is_none(),
            "changing only the negotiated roots capability must withhold the provider"
        );
        assert!(
            stream
                .try_recv_event(&cx)
                .expect("capability negative check must not fail")
                .is_none()
        );
    }

    // Exact-2024 era: legacy HTTP SSE session lifecycle.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn legacy_http_wrong_session_rejection_leaves_the_live_lifecycle_unchanged() {
        let cx = Cx::for_testing();
        let endpoint = Server::new("legacy-http-wrong-session", "1.0.0")
            .tool(LiveRuntimeListedTool)
            .build_http_endpoint("http://legacy.test")
            .expect("builder must construct the configured dual-era endpoint");
        let mut session = endpoint
            .open_session(&cx)
            .expect("endpoint must open a bounded live session");
        let stream = block_on(session.handle_async(&cx, HttpRequest::new(HttpMethod::Get, "/sse")))
            .expect("legacy SSE route must open");
        let ServerHttpEndpointResponse::LegacySse(mut stream) = stream else {
            panic!("legacy GET must open an exact SSE stream");
        };
        let _endpoint = stream
            .recv_event(&cx)
            .expect("legacy stream must advertise its exact POST endpoint");

        let initialize = JsonRpcRequest::new(
            "initialize",
            Some(serde_json::json!({
                "protocolVersion": LEGACY_PROTOCOL_VERSION,
                "capabilities": {},
                "clientInfo": {"name": "legacy-http-client", "version": "1.0.0"},
            })),
            221_i64,
        );
        let initialize_response = block_on(
            session.handle_async(
                &cx,
                HttpRequest::new(HttpMethod::Post, "/messages")
                    .with_header("content-type", "application/json")
                    .with_query("session_id", session.legacy_session_id())
                    .with_body(
                        serde_json::to_vec(&initialize)
                            .expect("legacy initialize request must serialize"),
                    ),
            ),
        )
        .expect("correct-session initialize must dispatch");
        assert!(matches!(
            initialize_response,
            ServerHttpEndpointResponse::Immediate(response) if response.status == HttpStatus::ACCEPTED
        ));
        let _initialize = stream
            .recv_event(&cx)
            .expect("initialize response must be streamed before lifecycle advance");
        let initialized = JsonRpcRequest::notification("notifications/initialized", None);
        let initialized_response = block_on(
            session.handle_async(
                &cx,
                HttpRequest::new(HttpMethod::Post, "/messages")
                    .with_header("content-type", "application/json")
                    .with_query("session_id", session.legacy_session_id())
                    .with_body(
                        serde_json::to_vec(&initialized)
                            .expect("legacy initialized notification must serialize"),
                    ),
            ),
        )
        .expect("correct-session initialized notification must dispatch");
        assert!(matches!(
            initialized_response,
            ServerHttpEndpointResponse::Immediate(response) if response.status == HttpStatus::ACCEPTED
        ));

        let valid = JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({
                "name": "live_runtime_listed_tool",
                "arguments": {},
            })),
            222_i64,
        );
        let mut wrong_session = HttpRequest::new(HttpMethod::Post, "/messages")
            .with_header("content-type", "application/json")
            .with_query("session_id", session.legacy_session_id())
            .with_body(serde_json::to_vec(&valid).expect("legacy tool request must serialize"));
        wrong_session
            .query
            .insert("session_id".to_string(), "wrong-session".to_string());
        let before = session
            .legacy_adapter
            .as_ref()
            .expect("initialize installs the exact legacy adapter")
            .snapshot();
        let rejected = block_on(session.handle_async(&cx, wrong_session))
            .expect("wrong session must become an HTTP rejection");
        assert!(matches!(
            rejected,
            ServerHttpEndpointResponse::Immediate(response) if response.status == HttpStatus::NOT_FOUND
        ));
        assert_eq!(
            session
                .legacy_adapter
                .as_ref()
                .expect("wrong session must not remove the adapter")
                .snapshot(),
            before,
            "changing only the session ID must not mutate the live exact lifecycle"
        );

        let accepted = block_on(
            session.handle_async(
                &cx,
                HttpRequest::new(HttpMethod::Post, "/messages")
                    .with_header("content-type", "application/json")
                    .with_query("session_id", session.legacy_session_id())
                    .with_body(
                        serde_json::to_vec(&valid).expect("legacy tool request must serialize"),
                    ),
            ),
        )
        .expect("the otherwise identical correct-session request must dispatch");
        assert!(matches!(
            accepted,
            ServerHttpEndpointResponse::Immediate(response) if response.status == HttpStatus::ACCEPTED
        ));
        let call = stream
            .recv_event(&cx)
            .expect("the unchanged lifecycle must still dispatch the valid call");
        assert!(matches!(
            Codec::new()
                .decode_complete_message(call.data.as_bytes())
                .expect("valid call event must remain JSON-RPC"),
            JsonRpcMessage::Response(response) if response.id == Some(222_i64.into())
        ));
    }

    // Exact-2024 era: legacy HTTP SSE cancellation admissions.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn legacy_http_closed_stream_rejects_cancellation_before_authority_mutation() {
        let cx = Cx::for_testing();
        let endpoint = Server::new("legacy-http-closed-cancellation", "1.0.0")
            .build_http_endpoint("http://legacy.test")
            .expect("dual-era endpoint must build");
        let mut session = endpoint
            .open_session(&cx)
            .expect("endpoint must open a bounded session");
        let ServerHttpEndpointResponse::LegacySse(stream) =
            block_on(session.handle_async(&cx, HttpRequest::new(HttpMethod::Get, "/sse")))
                .expect("legacy SSE route must open")
        else {
            panic!("legacy GET must return a live body");
        };

        let request_id = RequestId::Number(2_223);
        let target = JsonRpcRequest::new("tools/list", None, request_id.clone());
        let _admission = session
            .legacy_admissions
            .admit(
                &target,
                &session.legacy_session.principal_binding(),
                auth::principal_fingerprint(None).expect("anonymous principal is admissible"),
            )
            .expect("target request admission must remain structurally valid")
            .expect("correlated target must allocate cancellation authority");
        let target_cancellation = session
            .legacy_admissions
            .admitted_request_cancellation(&request_id)
            .expect("target authority must be observable before peer close");
        let control = session.cancellation_control();
        drop(stream);

        let cancellation = JsonRpcRequest::notification(
            "notifications/cancelled",
            Some(serde_json::json!({
                "requestId": request_id,
                "_meta": {"com.example/application": true},
            })),
        );
        let rejected = control
            .handle(
                &cx,
                &HttpRequest::new(HttpMethod::Post, "/messages")
                    .with_header("content-type", "application/json")
                    .with_query("session_id", session.legacy_session_id())
                    .with_body(
                        serde_json::to_vec(&cancellation)
                            .expect("legacy cancellation must serialize"),
                    ),
            )
            .expect("the exact cancellation route owns the HTTP response");
        assert_eq!(rejected.status, HttpStatus::SERVICE_UNAVAILABLE);
        assert!(!target_cancellation.is_cancel_requested());
        assert!(
            session
                .legacy_admissions
                .contains(&RequestId::Number(2_223))
        );
        assert!(
            session
                .endpoint_session
                .lock()
                .expect("transport session lock must remain healthy")
                .take_legacy_request()
                .is_none(),
            "closed-stream cancellation rejection cannot enqueue work"
        );
    }

    // Exact-2024 era: scripts legacy cancellation by original wire ID.
    #[cfg(feature = "legacy-2024-11-05")]
    struct LiveLegacyActiveCancellationRecv {
        phase: usize,
        started: Arc<AtomicBool>,
        observed_cancellation: Arc<AtomicBool>,
        responses: Arc<LiveModernResponses>,
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl TransportRecvHalf for LiveLegacyActiveCancellationRecv {
        fn recv(&mut self, _cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
            let phase = self.phase;
            self.phase = self.phase.saturating_add(1);
            match phase {
                0 => Ok(exact_legacy_initialize_request(
                    71,
                    serde_json::json!("1.0.0"),
                )),
                1 => Ok(JsonRpcMessage::Request(JsonRpcRequest::notification(
                    "notifications/initialized",
                    None,
                ))),
                2 => Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                    "tools/call",
                    Some(serde_json::json!({
                        "name": "live_legacy_cancellation_tool",
                        "arguments": {},
                    })),
                    72_i64,
                ))),
                3 => {
                    let deadline = Instant::now() + Duration::from_secs(1);
                    while !self.started.load(Ordering::Acquire) && Instant::now() < deadline {
                        std::thread::yield_now();
                    }
                    if !self.started.load(Ordering::Acquire) {
                        return Err(TransportError::Timeout);
                    }
                    Ok(JsonRpcMessage::Request(JsonRpcRequest::notification(
                        "notifications/cancelled",
                        Some(serde_json::json!({
                            "requestId": 72,
                            "reason": "test cancellation",
                        })),
                    )))
                }
                4 => {
                    let deadline = Instant::now() + Duration::from_secs(1);
                    while !self.observed_cancellation.load(Ordering::Acquire)
                        && Instant::now() < deadline
                    {
                        std::thread::yield_now();
                    }
                    if self.observed_cancellation.load(Ordering::Acquire) {
                        Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                            "ping", None, 73_i64,
                        )))
                    } else {
                        Err(TransportError::Timeout)
                    }
                }
                _ => {
                    if self
                        .responses
                        .wait_for_responses(&[73], Duration::from_secs(1))
                    {
                        Err(TransportError::Closed)
                    } else {
                        Err(TransportError::Timeout)
                    }
                }
            }
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            Ok(())
        }
    }

    // Exact-2024 era: legacy cancellation by original wire ID.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_runtime_cancels_exact_legacy_tool_by_its_original_wire_id() {
        run_live_legacy_active_cancellation(false);
    }

    // Exact-2024 era: legacy application tool content option.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn legacy_application_content_preserves_active_wire_cancellation() {
        run_live_legacy_active_cancellation(true);
    }

    // Exact-2024 era: legacy cancellation by original wire ID.
    #[cfg(feature = "legacy-2024-11-05")]
    fn run_live_legacy_active_cancellation(application_content: bool) {
        let started = Arc::new(AtomicBool::new(false));
        let observed_cancellation = Arc::new(AtomicBool::new(false));
        let responses = Arc::new(LiveModernResponses::default());

        run_live_split_transport(
            Duration::from_secs(20),
            Server::new("live-legacy-cancellation", "1.0.0")
                .legacy_application_tool_content(application_content)
                .protocol_policy(ProtocolPolicy::Auto)
                .expect("Auto must be available to this test build")
                .tool(LiveLegacyCancellationTool {
                    started: Arc::clone(&started),
                    observed_cancellation: Arc::clone(&observed_cancellation),
                })
                .build(),
            LiveLegacyActiveCancellationRecv {
                phase: 0,
                started: Arc::clone(&started),
                observed_cancellation: Arc::clone(&observed_cancellation),
                responses: Arc::clone(&responses),
            },
            LiveModernSplitSend {
                responses: Arc::clone(&responses),
            },
        )
        .expect("accepted active cancellation must close the public transport cleanly");

        assert!(observed_cancellation.load(Ordering::Acquire));
        assert_eq!(responses.response_count(71), 1);
        assert_eq!(responses.response_count(72), 0);
        assert_eq!(responses.response_count(73), 1);
        assert!(
            responses
                .response(73)
                .is_some_and(|response| response.error.is_none())
        );
    }

    // Exact-2024 era: scripts legacy queued cancellation.
    #[cfg(feature = "legacy-2024-11-05")]
    struct LiveLegacyQueuedCancellationRecv {
        phase: usize,
        cancelled_request_id: i64,
        initialize_send_started: Arc<BoundedTestSignal>,
        initialize_send_release: Arc<BoundedTestSignal>,
        control: Arc<LiveModernControl>,
        responses: Arc<LiveModernResponses>,
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl TransportRecvHalf for LiveLegacyQueuedCancellationRecv {
        fn recv(&mut self, _cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
            let phase = self.phase;
            self.phase = self.phase.saturating_add(1);
            match phase {
                0 => Ok(exact_legacy_initialize_request(
                    75,
                    serde_json::json!("1.0.0"),
                )),
                1 => Ok(JsonRpcMessage::Request(JsonRpcRequest::notification(
                    "notifications/initialized",
                    None,
                ))),
                2 => {
                    // Hold the initialization response attempt so request 80
                    // is certainly the first queued application request when
                    // its cancellation reaches the receive pump.
                    if self.initialize_send_started.wait(Duration::from_secs(2)) {
                        Ok(legacy_controlled_tool_request(80))
                    } else {
                        Err(TransportError::Timeout)
                    }
                }
                3 => Ok(JsonRpcMessage::Request(JsonRpcRequest::notification(
                    "notifications/cancelled",
                    Some(serde_json::json!({
                        "requestId": self.cancelled_request_id,
                        "reason": "queued cancellation",
                    })),
                ))),
                4 => {
                    // `recv` is called again only after the cancellation frame
                    // from phase 3 has been authenticated and applied.
                    self.initialize_send_release.raise();
                    Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                        "ping", None, 82_i64,
                    )))
                }
                5 => {
                    if self.cancelled_request_id == 80 {
                        if !self
                            .responses
                            .wait_for_responses(&[82], Duration::from_secs(2))
                        {
                            return Err(TransportError::Timeout);
                        }
                    } else {
                        if !self.control.wait_for_started(1, Duration::from_secs(2)) {
                            return Err(TransportError::Timeout);
                        }
                        self.control.release(80);
                        if !self
                            .responses
                            .wait_for_responses(&[80, 82], Duration::from_secs(2))
                        {
                            return Err(TransportError::Timeout);
                        }
                    }
                    Err(TransportError::Closed)
                }
                _ => Err(TransportError::Closed),
            }
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            Ok(())
        }
    }

    // Exact-2024 era: records legacy queued-cancellation output.
    #[cfg(feature = "legacy-2024-11-05")]
    struct LiveLegacyFirstQueuedSend {
        initialize_send_started: Arc<BoundedTestSignal>,
        initialize_send_release: Arc<BoundedTestSignal>,
        responses: Arc<LiveModernResponses>,
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl TransportSendHalf for LiveLegacyFirstQueuedSend {
        fn send(&mut self, _cx: &Cx, message: &JsonRpcMessage) -> Result<(), TransportError> {
            self.responses.record(message.clone());
            if matches!(
                message,
                JsonRpcMessage::Response(response) if response.id == Some(75_i64.into())
            ) {
                self.initialize_send_started.raise();
                if !self.initialize_send_release.wait(Duration::from_secs(2)) {
                    return Err(TransportError::Timeout);
                }
            }
            Ok(())
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            Ok(())
        }
    }

    // Exact-2024 era: scripts legacy queued cancellation.
    #[cfg(feature = "legacy-2024-11-05")]
    fn live_legacy_queued_cancellation_transcript(
        cancelled_request_id: i64,
    ) -> (
        McpResult<()>,
        Arc<LiveModernControl>,
        Arc<LiveModernResponses>,
    ) {
        let control = Arc::new(LiveModernControl::default());
        let responses = Arc::new(LiveModernResponses::default());
        let initialize_send_started = Arc::new(BoundedTestSignal::default());
        let initialize_send_release = Arc::new(BoundedTestSignal::default());

        let result = run_live_split_transport(
            Duration::from_secs(20),
            Server::new("live-legacy-queued-cancellation", "1.0.0")
                .protocol_policy(ProtocolPolicy::Auto)
                .expect("Auto must be available to this test build")
                .tool(LiveModernControlledTool {
                    control: Arc::clone(&control),
                })
                .build(),
            LiveLegacyQueuedCancellationRecv {
                phase: 0,
                cancelled_request_id,
                initialize_send_started: Arc::clone(&initialize_send_started),
                initialize_send_release: Arc::clone(&initialize_send_release),
                control: Arc::clone(&control),
                responses: Arc::clone(&responses),
            },
            LiveLegacyFirstQueuedSend {
                initialize_send_started,
                initialize_send_release,
                responses: Arc::clone(&responses),
            },
        )
        .map_err(McpError::internal_error);

        (result, control, responses)
    }

    // Exact-2024 era: legacy queued cancellation after a legacy opening.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_exact_legacy_first_queued_cancellation_suppresses_only_the_target_response() {
        let (result, control, responses) = live_legacy_queued_cancellation_transcript(80);

        result.expect("accepted queued cancellation must close the public transport cleanly");
        assert_eq!(responses.response_count(75), 1);
        assert_eq!(responses.response_count(80), 0);
        assert_eq!(responses.response_count(82), 1);
        assert_eq!(control.max_active(), 0);
        assert!(!control.was_cancelled(80));
        assert!(
            responses
                .response(82)
                .is_some_and(|response| response.error.is_none())
        );
    }

    // Exact-2024 era: legacy queued cancellation after a legacy opening.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_exact_legacy_first_queued_unknown_cancellation_preserves_the_request() {
        // This differs from the positive only in the cancellation request ID.
        let (result, control, responses) = live_legacy_queued_cancellation_transcript(83);

        result.expect("unknown queued cancellation must leave the public transport usable");
        assert_eq!(responses.response_count(75), 1);
        assert_eq!(responses.response_count(80), 1);
        assert_eq!(responses.response_count(82), 1);
        assert_eq!(control.max_active(), 1);
        assert!(!control.was_cancelled(80));
        assert!(
            responses
                .response(80)
                .is_some_and(|response| response.error.is_none())
        );
        assert!(
            responses
                .response(82)
                .is_some_and(|response| response.error.is_none())
        );
    }

    #[test]
    fn live_modern_stdio_requests_overlap_and_emit_one_response_per_id() {
        let control = Arc::new(LiveModernControl::default());
        let responses = Arc::new(LiveModernResponses::default());
        let control_for_receive = Arc::clone(&control);
        let responses_for_receive = Arc::clone(&responses);
        let phase = Arc::new(AtomicUsize::new(0));
        let phase_for_receive = Arc::clone(&phase);

        let exit_code = run_live_modern_pump(
            Server::new("live-modern-overlap", "1.0.0")
                .protocol_policy(build_default_protocol_policy())
                .expect("the build's default policy must be available")
                .tool(LiveModernControlledTool {
                    control: Arc::clone(&control),
                })
                .build(),
            move |_cx, _worker_failed| match phase_for_receive.fetch_add(1, Ordering::AcqRel) {
                0 => Ok(modern_discovery_opening_request()),
                1 => Ok(modern_controlled_tool_request(100)),
                2 => {
                    if control_for_receive.wait_for_started(1, Duration::from_secs(2)) {
                        Ok(modern_controlled_tool_request(101))
                    } else {
                        Err(TransportError::Timeout)
                    }
                }
                3 => {
                    if !control_for_receive.wait_for_started(2, Duration::from_secs(2)) {
                        return Err(TransportError::Timeout);
                    }
                    control_for_receive.release(100);
                    control_for_receive.release(101);
                    if responses_for_receive.wait_for_responses(&[100, 101], Duration::from_secs(2))
                    {
                        Err(TransportError::Closed)
                    } else {
                        Err(TransportError::Timeout)
                    }
                }
                _ => Err(TransportError::Closed),
            },
            Arc::clone(&responses),
        );

        assert_eq!(exit_code, 0);
        assert!(
            control.max_active() >= 2,
            "two independent modern requests must be live before either is released"
        );
        assert_eq!(responses.response_count(100), 1);
        assert_eq!(responses.response_count(101), 1);
    }

    #[test]
    fn live_modern_split_transport_requests_overlap_and_emit_one_response_per_id() {
        let control = Arc::new(LiveModernControl::default());
        let responses = Arc::new(LiveModernResponses::default());

        let run_result = run_live_split_transport(
            Duration::from_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS),
            Server::new("live-modern-split-overlap", "1.0.0")
                .protocol_policy(build_default_protocol_policy())
                .expect("the build's default policy must be available")
                .tool(LiveModernControlledTool {
                    control: Arc::clone(&control),
                })
                .build(),
            LiveModernSplitRecv {
                phase: 0,
                control: Arc::clone(&control),
                responses: Arc::clone(&responses),
            },
            LiveModernSplitSend {
                responses: Arc::clone(&responses),
            },
        );

        assert!(
            control.max_active() >= 2,
            "two split-transport modern requests must overlap before release; \
             run_result={run_result:?}, response_1200={}, response_1201={}",
            responses.response_count(1200),
            responses.response_count(1201),
        );
        assert_eq!(
            responses.response_count(1200),
            1,
            "first split-transport response count; run_result={run_result:?}"
        );
        assert_eq!(
            responses.response_count(1201),
            1,
            "second split-transport response count; run_result={run_result:?}"
        );
        run_result.expect("split transport must drain both independently owned modern requests");
    }

    // Exact-2024 era: selects LegacyOnly, which a no-legacy build refuses.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn live_modern_split_transport_legacy_only_policy_rejects_before_children_start() {
        let control = Arc::new(LiveModernControl::default());
        let responses = Arc::new(LiveModernResponses::default());

        // This differs from the overlap-positive setup only in protocol policy.
        run_live_split_transport(
            Duration::from_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS),
            Server::new("live-modern-split-overlap", "1.0.0")
                .protocol_policy(ProtocolPolicy::LegacyOnly)
                .expect("LegacyOnly must be available to this test build")
                .tool(LiveModernControlledTool {
                    control: Arc::clone(&control),
                })
                .build(),
            LiveModernSplitRecv {
                phase: 0,
                control: Arc::clone(&control),
                responses: Arc::clone(&responses),
            },
            LiveModernSplitSend {
                responses: Arc::clone(&responses),
            },
        )
        .expect_err("LegacyOnly must reject the identical modern split stream");

        assert_eq!(control.max_active(), 0);
        assert_eq!(responses.response_count(905), 1);
        assert_eq!(responses.response_count(1200), 0);
        assert_eq!(responses.response_count(1201), 0);
    }

    #[test]
    fn split_returning_modern_progress_write_success_quiesces() {
        split_returning_modern_progress_write_case(false);
    }

    #[test]
    fn split_returning_modern_progress_write_failure_survives_successful_terminal_write() {
        split_returning_modern_progress_write_case(true);
    }

    fn split_returning_modern_progress_write_case(fail_progress_write: bool) {
        const REQUEST_ID: i64 = 1210;

        #[derive(Default)]
        struct Probe {
            control: Arc<LiveModernControl>,
            responses: Arc<LiveModernResponses>,
            receive_waiting: BoundedTestSignal,
            progress_attempted: BoundedTestSignal,
            progress_attempts: AtomicUsize,
            receive_calls: AtomicUsize,
            closed_after_terminal: AtomicUsize,
            timeout_returns: AtomicUsize,
            receive_closes: AtomicUsize,
            send_closes: AtomicUsize,
        }

        struct ProgressWriteRecv {
            probe: Arc<Probe>,
        }

        impl TransportRecvHalf for ProgressWriteRecv {
            fn recv(&mut self, _cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
                match self.probe.receive_calls.fetch_add(1, Ordering::AcqRel) {
                    0 => Ok(modern_discovery_opening_request()),
                    1 => {
                        if !self
                            .probe
                            .responses
                            .wait_for_responses(&[905], Duration::from_secs(2))
                        {
                            self.probe.timeout_returns.fetch_add(1, Ordering::AcqRel);
                            return Err(TransportError::Timeout);
                        }
                        Ok(modern_controlled_tool_progress_request(REQUEST_ID))
                    }
                    2 => {
                        // Keep the receive operation open until both the progress
                        // attempt and the terminal write finish. This exercises
                        // the failure latch even when EOF wins the next observation.
                        self.probe.receive_waiting.raise();
                        if !self.probe.progress_attempted.wait(Duration::from_secs(2)) {
                            self.probe.control.release_all();
                            self.probe.timeout_returns.fetch_add(1, Ordering::AcqRel);
                            return Err(TransportError::Timeout);
                        }
                        self.probe.control.release(REQUEST_ID as u64);
                        if self
                            .probe
                            .responses
                            .wait_for_responses(&[REQUEST_ID], Duration::from_secs(2))
                        {
                            self.probe
                                .closed_after_terminal
                                .fetch_add(1, Ordering::AcqRel);
                            Err(TransportError::Closed)
                        } else {
                            self.probe.timeout_returns.fetch_add(1, Ordering::AcqRel);
                            Err(TransportError::Timeout)
                        }
                    }
                    _ => Err(TransportError::Closed),
                }
            }

            fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
                self.probe.receive_closes.fetch_add(1, Ordering::AcqRel);
                Ok(())
            }
        }

        struct ProgressWriteSend {
            probe: Arc<Probe>,
            fail_progress_write: bool,
        }

        impl TransportSendHalf for ProgressWriteSend {
            fn send(&mut self, _cx: &Cx, message: &JsonRpcMessage) -> Result<(), TransportError> {
                if matches!(message, JsonRpcMessage::Request(notification)
                    if notification.method == "notifications/progress")
                {
                    if !self.probe.receive_waiting.wait(Duration::from_secs(2)) {
                        self.probe.timeout_returns.fetch_add(1, Ordering::AcqRel);
                        return Err(TransportError::Timeout);
                    }
                    self.probe.progress_attempts.fetch_add(1, Ordering::AcqRel);
                    self.probe.progress_attempted.raise();
                    // The sole changed input between the paired cases is the
                    // result of this progress write. All responses still succeed.
                    if self.fail_progress_write {
                        return Err(TransportError::Io(std::io::Error::other(
                            "progress write failed",
                        )));
                    }
                }
                self.probe.responses.record(message.clone());
                Ok(())
            }

            fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
                self.probe.send_closes.fetch_add(1, Ordering::AcqRel);
                Ok(())
            }
        }

        let probe = Arc::new(Probe::default());
        let server = Server::new("split-progress-write", "1.0.0")
            .protocol_policy(build_default_protocol_policy())
            .expect("the build's default policy must be available")
            .tool(LiveModernControlledTool {
                control: Arc::clone(&probe.control),
            })
            .build();
        let active_requests = Arc::clone(&server.active_requests);
        let result = run_live_split_transport(
            Duration::from_nanos(LIVE_HTTP_TEST_TIMEOUT_NANOS),
            server,
            ProgressWriteRecv {
                probe: Arc::clone(&probe),
            },
            ProgressWriteSend {
                probe: Arc::clone(&probe),
                fail_progress_write,
            },
        );

        assert_eq!(probe.receive_calls.load(Ordering::Acquire), 3);
        assert_eq!(
            probe.closed_after_terminal.load(Ordering::Acquire),
            1,
            "receive must return clean EOF only after observing the terminal write"
        );
        assert_eq!(
            probe.timeout_returns.load(Ordering::Acquire),
            0,
            "a fixture timeout must never substitute for the notification failure"
        );
        assert_eq!(probe.progress_attempts.load(Ordering::Acquire), 1);
        assert_eq!(probe.responses.response_count(905), 1);
        assert_eq!(probe.responses.response_count(REQUEST_ID), 1);
        assert_eq!(probe.receive_closes.load(Ordering::Acquire), 1);
        assert_eq!(probe.send_closes.load(Ordering::Acquire), 1);
        assert!(probe.control.has_started(REQUEST_ID as u64));
        assert_eq!(
            probe
                .control
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .active,
            0,
            "handler cleanup must finish before the returning runner settles"
        );
        assert!(
            active_requests
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .is_empty(),
            "the runner must retire every request owner"
        );
        let progress_writes = probe
            .responses
            .messages()
            .iter()
            .filter(|message| {
                matches!(message, JsonRpcMessage::Request(notification)
                if notification.method == "notifications/progress")
            })
            .count();
        let terminal = probe
            .responses
            .response(REQUEST_ID)
            .expect("the terminal response write succeeds in both cases");
        if fail_progress_write {
            assert_eq!(progress_writes, 0);
            assert!(terminal.result.is_none());
            assert_eq!(
                terminal.error.and_then(|error| error.code.as_i32()),
                Some(i32::from(McpErrorCode::RequestCancelled))
            );
            let error = result.expect_err(
                "a successful cancellation response cannot erase the progress-write failure",
            );
            assert!(error.contains("Server transport loop failed"), "{error}");
        } else {
            assert_eq!(progress_writes, 1);
            assert!(terminal.error.is_none());
            let result_body = terminal.result.expect("successful tool result");
            assert_eq!(result_body["resultType"], "complete");
            assert_eq!(result_body["content"][0]["text"], "modern request 1210");
            result.expect("successful progress and response writes must quiesce cleanly");
        }
    }

    #[test]
    fn live_modern_stdio_metadata_free_cancellation_isolated_to_the_matching_request() {
        let control = Arc::new(LiveModernControl::default());
        let responses = Arc::new(LiveModernResponses::default());
        let control_for_receive = Arc::clone(&control);
        let responses_for_receive = Arc::clone(&responses);
        let phase = Arc::new(AtomicUsize::new(0));
        let phase_for_receive = Arc::clone(&phase);

        let exit_code = run_live_modern_pump(
            Server::new("live-modern-cancellation", "1.0.0")
                .protocol_policy(build_default_protocol_policy())
                .expect("the build's default policy must be available")
                .tool(LiveModernControlledTool {
                    control: Arc::clone(&control),
                })
                .build(),
            move |_cx, _worker_failed| match phase_for_receive.fetch_add(1, Ordering::AcqRel) {
                0 => Ok(modern_discovery_opening_request()),
                1 => Ok(modern_controlled_tool_request(200)),
                2 => {
                    if control_for_receive.wait_for_started(1, Duration::from_secs(2)) {
                        Ok(modern_controlled_tool_request(201))
                    } else {
                        Err(TransportError::Timeout)
                    }
                }
                3 => {
                    if control_for_receive.wait_for_started(2, Duration::from_secs(2)) {
                        Ok(modern_cancelled_notification(200))
                    } else {
                        Err(TransportError::Timeout)
                    }
                }
                4 => {
                    if !control_for_receive.wait_for_cancellation(200, Duration::from_secs(2)) {
                        return Err(TransportError::Timeout);
                    }
                    control_for_receive.release(201);
                    if responses_for_receive.wait_for_responses(&[200, 201], Duration::from_secs(2))
                    {
                        Err(TransportError::Closed)
                    } else {
                        Err(TransportError::Timeout)
                    }
                }
                _ => Err(TransportError::Closed),
            },
            Arc::clone(&responses),
        );

        assert_eq!(
            exit_code,
            0,
            "modern cancellation pump failed: phase={}, started200={}, started201={}, \
             cancelled200={}, cancelled201={}, max_active={}, response200={:?}, response201={:?}",
            phase.load(Ordering::Acquire),
            control.has_started(200),
            control.has_started(201),
            control.was_cancelled(200),
            control.was_cancelled(201),
            control.max_active(),
            responses.response(200),
            responses.response(201),
        );
        assert!(control.was_cancelled(200));
        assert!(!control.was_cancelled(201));
        assert_eq!(
            control
                .state
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .active,
            0,
            "all controlled calls must finish cleanup before the pump returns"
        );
        assert_eq!(responses.response_count(200), 1);
        assert_eq!(responses.response_count(201), 1);
        assert_eq!(
            responses
                .response(200)
                .and_then(|response| response.error)
                .and_then(|error| error.code.as_i32()),
            Some(i32::from(McpErrorCode::RequestCancelled))
        );
        assert!(
            responses
                .response(201)
                .is_some_and(|response| response.error.is_none())
        );
    }

    #[test]
    fn public_stdio_final_progress_flushes_during_work_before_log_and_terminal_response() {
        const REQUEST_ID: i64 = 206;
        let control = Arc::new(LiveModernControl::default());
        let responses = Arc::new(LiveModernResponses::default());
        let control_for_receive = Arc::clone(&control);
        let responses_for_receive = Arc::clone(&responses);
        let phase = Arc::new(AtomicUsize::new(0));
        let phase_for_receive = Arc::clone(&phase);

        let exit_code = run_live_modern_pump(
            Server::new("public-stdio-final-progress", "1.0.0")
                .protocol_policy(build_default_protocol_policy())
                .expect("the build's default policy must be available")
                .log_level(Level::Debug)
                .tool(LiveModernControlledTool {
                    control: Arc::clone(&control),
                })
                .build(),
            move |_cx, _worker_failed| match phase_for_receive.fetch_add(1, Ordering::AcqRel) {
                0 => Ok(modern_discovery_opening_request()),
                1 => Ok(modern_controlled_tool_progress_request(REQUEST_ID)),
                2 => {
                    if !control_for_receive.wait_for_started(1, Duration::from_secs(2)) {
                        return Err(TransportError::Timeout);
                    }
                    if !responses_for_receive
                        .wait_for_notification("notifications/progress", Duration::from_secs(2))
                        || responses_for_receive.response_count(REQUEST_ID) != 0
                    {
                        return Err(TransportError::Timeout);
                    }
                    control_for_receive.release(REQUEST_ID as u64);
                    if responses_for_receive
                        .wait_for_responses(&[REQUEST_ID], Duration::from_secs(2))
                    {
                        Err(TransportError::Closed)
                    } else {
                        Err(TransportError::Timeout)
                    }
                }
                _ => Err(TransportError::Closed),
            },
            Arc::clone(&responses),
        );

        assert_eq!(exit_code, 0);
        let messages = responses.messages();
        let progress = messages
            .iter()
            .enumerate()
            .find_map(|(index, message)| match message {
                JsonRpcMessage::Request(notification)
                    if notification.method == "notifications/progress" =>
                {
                    Some((index, notification))
                }
                _ => None,
            })
            .expect("the public stdio request must emit its coalesced progress");
        assert_eq!(
            messages
                .iter()
                .filter(|message| matches!(
                    message,
                    JsonRpcMessage::Request(notification)
                        if notification.method == "notifications/progress"
                ))
                .count(),
            1,
            "the outer final-progress runtime must retain only its latest update"
        );
        let progress_wire = serde_json::to_string(
            progress
                .1
                .params
                .as_ref()
                .expect("coalesced progress must have parameters"),
        )
        .expect("coalesced progress parameters must serialize");
        assert!(progress_wire.contains("\"progressToken\":\"public-stdio-final-progress\""));
        assert!(progress_wire.contains("\"progress\":12000"));
        assert!(progress_wire.contains("\"total\":11999"));
        assert!(progress_wire.contains("\"message\":\"latest\""));
        let log_index = messages
            .iter()
            .position(|message| {
                matches!(message, JsonRpcMessage::Request(notification) if notification.method == "notifications/message")
            })
            .expect("the final log must be written after progress");
        let response_index = messages
            .iter()
            .position(|message| {
                matches!(
                    message,
                    JsonRpcMessage::Response(response)
                        if response.id == Some(REQUEST_ID.into()) && response.error.is_none()
                )
            })
            .expect("the terminal response must be written");
        assert!(
            progress.0 < log_index && log_index < response_index,
            "the rate-flushed progress must precede the final log and terminal response"
        );
    }

    #[test]
    fn public_stdio_final_progress_cancellation_suppresses_post_cancellation_frames() {
        const REQUEST_ID: i64 = 207;
        let control = Arc::new(LiveModernControl::default());
        let responses = Arc::new(LiveModernResponses::default());
        let control_for_receive = Arc::clone(&control);
        let responses_for_receive = Arc::clone(&responses);
        let phase = Arc::new(AtomicUsize::new(0));
        let phase_for_receive = Arc::clone(&phase);

        let exit_code = run_live_modern_pump(
            Server::new("public-stdio-final-progress-cancel", "1.0.0")
                .protocol_policy(build_default_protocol_policy())
                .expect("the build's default policy must be available")
                .log_level(Level::Debug)
                .tool(LiveModernControlledTool {
                    control: Arc::clone(&control),
                })
                .build(),
            move |_cx, _worker_failed| match phase_for_receive.fetch_add(1, Ordering::AcqRel) {
                0 => Ok(modern_discovery_opening_request()),
                1 => Ok(modern_controlled_tool_progress_request(REQUEST_ID)),
                2 => {
                    if control_for_receive.wait_for_started(1, Duration::from_secs(2)) {
                        if responses_for_receive
                            .wait_for_notification("notifications/progress", Duration::from_secs(2))
                        {
                            Ok(modern_cancelled_notification(REQUEST_ID as u64))
                        } else {
                            Err(TransportError::Timeout)
                        }
                    } else {
                        Err(TransportError::Timeout)
                    }
                }
                3 => {
                    if !control_for_receive
                        .wait_for_cancellation(REQUEST_ID as u64, Duration::from_secs(2))
                    {
                        return Err(TransportError::Timeout);
                    }
                    if responses_for_receive
                        .wait_for_responses(&[REQUEST_ID], Duration::from_secs(2))
                    {
                        Err(TransportError::Closed)
                    } else {
                        Err(TransportError::Timeout)
                    }
                }
                _ => Err(TransportError::Closed),
            },
            Arc::clone(&responses),
        );

        assert_eq!(exit_code, 0);
        assert!(control.was_cancelled(REQUEST_ID as u64));
        let messages = responses.messages();
        let progress_index = messages
            .iter()
            .position(|message| {
                matches!(message, JsonRpcMessage::Request(notification) if notification.method == "notifications/progress")
            })
            .expect("the rate timer must flush progress before the one-variable cancellation");
        assert_eq!(
            responses
                .response(REQUEST_ID)
                .and_then(|response| response.error)
                .and_then(|error| error.code.as_i32()),
            Some(i32::from(McpErrorCode::RequestCancelled))
        );
        assert!(
            !messages[progress_index.saturating_add(1)..]
                .iter()
                .any(|message| matches!(
                    message,
                    JsonRpcMessage::Request(notification)
                        if notification.method == "notifications/progress"
                            || notification.method == "notifications/message"
                )),
            "once cancellation wins, no final progress or log frame may follow it"
        );
    }

    #[test]
    fn public_stdio_cancellation_fence_drops_interleaved_progress_before_commit() {
        const REQUEST_ID: i64 = 208;
        let control = Arc::new(LiveModernControl::default());
        let responses = Arc::new(LiveModernResponses::default());
        let interlock = install_stdio_progress_commit_interlock(REQUEST_ID as u64);
        let control_for_receive = Arc::clone(&control);
        let responses_for_receive = Arc::clone(&responses);
        let interlock_for_receive = Arc::clone(&interlock);
        let phase = Arc::new(AtomicUsize::new(0));
        let phase_for_receive = Arc::clone(&phase);

        let exit_code = run_live_modern_pump(
            Server::new("public-stdio-progress-cancellation-fence", "1.0.0")
                .protocol_policy(build_default_protocol_policy())
                .expect("the build's default policy must be available")
                .log_level(Level::Debug)
                .tool(LiveModernControlledTool {
                    control: Arc::clone(&control),
                })
                .build(),
            move |_cx, _worker_failed| match phase_for_receive.fetch_add(1, Ordering::AcqRel) {
                0 => Ok(modern_discovery_opening_request()),
                1 => Ok(modern_controlled_tool_progress_request(REQUEST_ID)),
                2 => {
                    if interlock_for_receive.wait_until_entered(Duration::from_secs(2)) {
                        // The progress callback is now stopped immediately
                        // before acquiring the writer. The receiver commits
                        // this sole changed input under the same writer fence.
                        Ok(modern_cancelled_notification(REQUEST_ID as u64))
                    } else {
                        Err(TransportError::Timeout)
                    }
                }
                3 => {
                    release_stdio_progress_commit_interlock();
                    if !control_for_receive
                        .wait_for_cancellation(REQUEST_ID as u64, Duration::from_secs(2))
                    {
                        return Err(TransportError::Timeout);
                    }
                    if responses_for_receive
                        .wait_for_responses(&[REQUEST_ID], Duration::from_secs(2))
                    {
                        Err(TransportError::Closed)
                    } else {
                        Err(TransportError::Timeout)
                    }
                }
                _ => Err(TransportError::Closed),
            },
            Arc::clone(&responses),
        );
        release_stdio_progress_commit_interlock();

        assert_eq!(exit_code, 0);
        assert!(control.was_cancelled(REQUEST_ID as u64));
        assert_eq!(
            responses
                .response(REQUEST_ID)
                .and_then(|response| response.error)
                .and_then(|error| error.code.as_i32()),
            Some(i32::from(McpErrorCode::RequestCancelled))
        );
        assert!(
            !responses.messages().iter().any(|message| matches!(
                message,
                JsonRpcMessage::Request(notification)
                    if notification.method == "notifications/progress"
                        || notification.method == "notifications/message"
            )),
            "a cancellation that owns the writer fence must suppress interleaved progress and final logs"
        );
    }

    #[test]
    fn live_modern_stdio_shutdown_cancels_an_in_flight_notification() {
        let control = Arc::new(LiveModernNotificationControl::default());
        let control_for_receive = Arc::clone(&control);
        let phase = Arc::new(AtomicUsize::new(0));
        let phase_for_receive = Arc::clone(&phase);

        let exit_code = run_live_modern_pump(
            Server::new("live-modern-notification-shutdown", "1.0.0")
                .protocol_policy(build_default_protocol_policy())
                .expect("the build's default policy must be available")
                .middleware(LiveModernBlockingNotificationMiddleware {
                    control: Arc::clone(&control),
                })
                .build(),
            move |_cx, _worker_failed| match phase_for_receive.fetch_add(1, Ordering::AcqRel) {
                0 => Ok(modern_discovery_opening_request()),
                1 => Ok(modern_initialized_notification()),
                2 => {
                    if control_for_receive.wait_for_started(Duration::from_secs(2)) {
                        Err(TransportError::Closed)
                    } else {
                        Err(TransportError::Timeout)
                    }
                }
                _ => Err(TransportError::Closed),
            },
            Arc::new(LiveModernResponses::default()),
        );

        assert_eq!(exit_code, 0);
        assert!(
            control.was_cancelled(),
            "stdio shutdown must cancel a modern notification without a request id"
        );
    }

    #[test]
    fn live_modern_stdio_rejects_the_one_request_beyond_bounded_capacity() {
        let control = Arc::new(LiveModernControl::default());
        let responses = Arc::new(LiveModernResponses::default());
        let control_for_receive = Arc::clone(&control);
        let responses_for_receive = Arc::clone(&responses);
        let phase = Arc::new(AtomicUsize::new(0));
        let phase_for_receive = Arc::clone(&phase);

        let exit_code = run_live_modern_pump(
            Server::new("live-modern-backpressure", "1.0.0")
                .protocol_policy(build_default_protocol_policy())
                .expect("the build's default policy must be available")
                .tool(LiveModernControlledTool {
                    control: Arc::clone(&control),
                })
                .build(),
            move |_cx, _worker_failed| {
                let phase = phase_for_receive.fetch_add(1, Ordering::AcqRel);
                match phase {
                    0 => Ok(modern_discovery_opening_request()),
                    1 => {
                        if responses_for_receive.wait_for_responses(&[905], Duration::from_secs(2))
                        {
                            Ok(modern_controlled_tool_request(1001))
                        } else {
                            Err(TransportError::Timeout)
                        }
                    }
                    2..=65 => Ok(modern_controlled_tool_request(1000 + phase as i64)),
                    66 => {
                        if !responses_for_receive
                            .wait_for_responses(&[1065], Duration::from_secs(2))
                        {
                            return Err(TransportError::Timeout);
                        }
                        control_for_receive.release_all();
                        let admitted = (1001..=1064).collect::<Vec<_>>();
                        if responses_for_receive
                            .wait_for_responses(&admitted, Duration::from_secs(5))
                        {
                            Err(TransportError::Closed)
                        } else {
                            Err(TransportError::Timeout)
                        }
                    }
                    _ => Err(TransportError::Closed),
                }
            },
            Arc::clone(&responses),
        );

        assert_eq!(exit_code, 0);
        assert_eq!(responses.response_count(1065), 1);
        assert_eq!(
            responses
                .response(1065)
                .and_then(|response| response.error)
                .and_then(|error| error.code.as_i32()),
            Some(RESOURCE_EXHAUSTED_ERROR_CODE)
        );
        for id in 1001..=1064 {
            assert_eq!(
                responses.response_count(id),
                1,
                "accepted id {id} must finalize once"
            );
        }
    }

    #[test]
    fn reality_check_regression_returning_transport_treats_clean_stop_as_success() {
        for receive in [
            ReturningProbeReceive::Closed,
            ReturningProbeReceive::Cancelled,
        ] {
            Server::new("returning-clean-stop-test", "1.0.0")
                .build()
                .run_transport_returning_with_cx(
                    &Cx::for_testing(),
                    ReturningProbeTransport {
                        receive,
                        fail_send: false,
                        fail_close: false,
                        close_calls: Arc::new(AtomicUsize::new(0)),
                    },
                )
                .expect("clean EOF and transport cancellation must return success");
        }
    }

    #[test]
    fn reality_check_regression_returning_transport_propagates_fatal_receive_error() {
        let error = Server::new("returning-receive-failure-test", "1.0.0")
            .build()
            .run_transport_returning_with_cx(
                &Cx::for_testing(),
                ReturningProbeTransport {
                    receive: ReturningProbeReceive::Timeout,
                    fail_send: false,
                    fail_close: false,
                    close_calls: Arc::new(AtomicUsize::new(0)),
                },
            )
            .expect_err("fatal transport receive failure must propagate");

        assert_eq!(error.code, McpErrorCode::InternalError);
        assert_eq!(
            error.data.as_ref().and_then(|data| data["stage"].as_str()),
            Some("receive")
        );
        assert_eq!(
            error.data.as_ref().and_then(|data| data["kind"].as_str()),
            Some("timeout")
        );
    }

    // Exact-2024 era: answers an un-negotiated ping, which only the dual-era loop admits.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn reality_check_regression_returning_transport_propagates_response_send_error() {
        let error = Server::new("returning-send-failure-test", "1.0.0")
            .build()
            .run_transport_returning_with_cx(
                &Cx::for_testing(),
                ReturningProbeTransport {
                    receive: ReturningProbeReceive::PingThenClosed,
                    fail_send: true,
                    fail_close: false,
                    close_calls: Arc::new(AtomicUsize::new(0)),
                },
            )
            .expect_err("response send failure must propagate");

        assert_eq!(error.code, McpErrorCode::InternalError);
        assert_eq!(
            error.data.as_ref().and_then(|data| data["stage"].as_str()),
            Some("send")
        );
        assert_eq!(
            error.data.as_ref().and_then(|data| data["kind"].as_str()),
            Some("io")
        );
    }

    #[test]
    fn reality_check_regression_returning_transport_closes_and_propagates_close_failure() {
        let close_calls = Arc::new(AtomicUsize::new(0));
        let error = Server::new("returning-close-failure-test", "1.0.0")
            .build()
            .run_transport_returning_with_cx(
                &Cx::for_testing(),
                ReturningProbeTransport {
                    receive: ReturningProbeReceive::Closed,
                    fail_send: false,
                    fail_close: true,
                    close_calls: Arc::clone(&close_calls),
                },
            )
            .expect_err("transport close failure must propagate");

        assert_eq!(close_calls.load(Ordering::Acquire), 1);
        assert_eq!(
            error.data.as_ref().and_then(|data| data["stage"].as_str()),
            Some("close")
        );
        assert_eq!(
            error.data.as_ref().and_then(|data| data["kind"].as_str()),
            Some("io")
        );
    }

    #[test]
    fn shared_transport_close_retires_io_once_positive() {
        let recv_calls = Arc::new(AtomicUsize::new(0));
        let send_calls = Arc::new(AtomicUsize::new(0));
        let close_calls = Arc::new(AtomicUsize::new(0));
        let transport = SharedTransport::new(SharedTransportCountingTransport {
            recv_calls: Arc::clone(&recv_calls),
            send_calls: Arc::clone(&send_calls),
            close_calls: Arc::clone(&close_calls),
            fail_close: false,
        });
        let message = JsonRpcMessage::Request(JsonRpcRequest::new("ping", None, 1_i64));

        assert!(transport.send(&Cx::for_testing(), &message).is_ok());
        assert_eq!(send_calls.load(Ordering::Acquire), 1);
        let cx = Cx::for_testing();
        assert!(transport.close(&cx).is_ok());
        assert!(matches!(
            transport.send(&Cx::for_testing(), &message),
            Err(TransportError::Closed)
        ));
        assert!(matches!(
            transport.recv(&Cx::for_testing()),
            Err(TransportError::Closed)
        ));
        assert!(transport.close(&cx).is_ok());
        assert_eq!(send_calls.load(Ordering::Acquire), 1);
        assert_eq!(recv_calls.load(Ordering::Acquire), 0);
        assert_eq!(close_calls.load(Ordering::Acquire), 1);

        let sibling_send_calls = Arc::new(AtomicUsize::new(0));
        let sibling = SharedTransport::new(SharedTransportCountingTransport {
            recv_calls: Arc::new(AtomicUsize::new(0)),
            send_calls: Arc::clone(&sibling_send_calls),
            close_calls: Arc::new(AtomicUsize::new(0)),
            fail_close: false,
        });
        assert!(sibling.send(&Cx::for_testing(), &message).is_ok());
        assert_eq!(sibling_send_calls.load(Ordering::Acquire), 1);
    }

    #[test]
    fn shared_transport_close_failure_keeps_io_retired_negative() {
        let recv_calls = Arc::new(AtomicUsize::new(0));
        let send_calls = Arc::new(AtomicUsize::new(0));
        let close_calls = Arc::new(AtomicUsize::new(0));
        let transport = SharedTransport::new(SharedTransportCountingTransport {
            recv_calls: Arc::clone(&recv_calls),
            send_calls: Arc::clone(&send_calls),
            close_calls: Arc::clone(&close_calls),
            fail_close: true,
        });
        let message = JsonRpcMessage::Request(JsonRpcRequest::new("ping", None, 1_i64));

        assert!(transport.send(&Cx::for_testing(), &message).is_ok());
        assert_eq!(send_calls.load(Ordering::Acquire), 1);
        let cx = Cx::for_testing();
        assert!(transport.close(&cx).is_err());
        assert!(matches!(
            transport.send(&Cx::for_testing(), &message),
            Err(TransportError::Closed)
        ));
        assert!(matches!(
            transport.recv(&Cx::for_testing()),
            Err(TransportError::Closed)
        ));
        assert!(transport.close(&cx).is_ok());
        assert_eq!(send_calls.load(Ordering::Acquire), 1);
        assert_eq!(recv_calls.load(Ordering::Acquire), 0);
        assert_eq!(close_calls.load(Ordering::Acquire), 1);

        let sibling_send_calls = Arc::new(AtomicUsize::new(0));
        let sibling = SharedTransport::new(SharedTransportCountingTransport {
            recv_calls: Arc::new(AtomicUsize::new(0)),
            send_calls: Arc::clone(&sibling_send_calls),
            close_calls: Arc::new(AtomicUsize::new(0)),
            fail_close: false,
        });
        assert!(sibling.send(&Cx::for_testing(), &message).is_ok());
        assert_eq!(sibling_send_calls.load(Ordering::Acquire), 1);
    }

    /// Unsplit transport whose `recv` blocks until the test releases it, and
    /// which records each written method with whether `recv` had returned.
    struct BlockingRecvTransport {
        entered: std::sync::mpsc::Sender<()>,
        release: std::sync::mpsc::Receiver<()>,
        recv_returned: bool,
        fail_send: bool,
        written: Arc<Mutex<Vec<(String, bool)>>>,
    }

    impl Transport for BlockingRecvTransport {
        fn send(&mut self, _cx: &Cx, message: &JsonRpcMessage) -> Result<(), TransportError> {
            let JsonRpcMessage::Request(request) = message else {
                panic!("this fixture only writes requests");
            };
            self.written
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push((request.method.clone(), self.recv_returned));
            if self.fail_send {
                return Err(TransportError::Io(std::io::Error::new(
                    std::io::ErrorKind::BrokenPipe,
                    "peer closed",
                )));
            }
            Ok(())
        }

        fn recv(&mut self, _cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
            self.entered.send(()).expect("test observes recv entry");
            self.release.recv().expect("test releases recv");
            self.recv_returned = true;
            Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                "ping", None, 1_i64,
            )))
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            Ok(())
        }
    }

    /// bd-8bcfq: sends issued while an unsplit transport's `recv` blocks must
    /// neither fail nor wait for it; they are written in order once it returns.
    /// Returns what was written, the latched output failure, and the result of
    /// one more send issued after `recv` returned.
    fn shared_transport_send_during_blocked_recv_case(
        fail_send: bool,
    ) -> (Vec<(String, bool)>, bool, Result<(), TransportError>) {
        let (entered_tx, entered_rx) = std::sync::mpsc::channel();
        let (release_tx, release_rx) = std::sync::mpsc::channel();
        let written = Arc::new(Mutex::new(Vec::new()));
        let failure = Arc::new(AtomicBool::new(false));
        let shared = SharedTransport::with_output_failure(
            BlockingRecvTransport {
                entered: entered_tx,
                release: release_rx,
                recv_returned: false,
                fail_send,
                written: Arc::clone(&written),
            },
            Arc::clone(&failure),
        );
        let receiver = shared.clone();
        let pump = std::thread::spawn(move || receiver.recv(&Cx::for_testing()));
        entered_rx
            .recv_timeout(Duration::from_secs(5))
            .expect("recv must be entered");

        let sender = shared.clone();
        let (sent_tx, sent_rx) = std::sync::mpsc::channel();
        let writer = std::thread::spawn(move || {
            for method in ["notifications/first", "notifications/second"] {
                let notification =
                    JsonRpcMessage::Request(JsonRpcRequest::notification(method, None));
                sent_tx
                    .send(sender.send(&Cx::for_testing(), &notification))
                    .expect("test collects send results");
            }
        });
        for _ in 0..2 {
            let sent = sent_rx
                .recv_timeout(Duration::from_secs(5))
                .expect("a send must not wait for a blocked recv");
            assert!(sent.is_ok(), "{sent:?}");
        }
        writer.join().expect("writer thread");
        assert!(
            written
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .is_empty(),
            "nothing can be written while recv owns the handle"
        );
        assert!(!failure.load(Ordering::Acquire));

        release_tx.send(()).expect("recv is still blocked");
        let received = pump.join().expect("pump thread");
        assert!(matches!(received, Ok(JsonRpcMessage::Request(_))));

        let after = shared.send(
            &Cx::for_testing(),
            &JsonRpcMessage::Request(JsonRpcRequest::notification("notifications/third", None)),
        );
        let written = written
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .clone();
        (written, failure.load(Ordering::Acquire), after)
    }

    #[test]
    fn shared_transport_writes_sends_queued_during_recv_in_order_positive() {
        let (written, failed, after) = shared_transport_send_during_blocked_recv_case(false);
        assert_eq!(
            written,
            [
                ("notifications/first".to_owned(), true),
                ("notifications/second".to_owned(), true),
                ("notifications/third".to_owned(), true),
            ]
        );
        assert!(!failed);
        assert!(after.is_ok(), "{after:?}");
    }

    #[test]
    fn shared_transport_latches_failure_of_queued_send_negative() {
        let (written, failed, after) = shared_transport_send_during_blocked_recv_case(true);
        // The first queued write fails, so the rest of the queue is dropped,
        // the pump's failure flag is latched, and later sends are refused
        // rather than written out of order.
        assert_eq!(written, [("notifications/first".to_owned(), true)]);
        assert!(failed);
        assert!(after.is_err(), "{after:?}");
    }

    #[test]
    fn reality_check_regression_returning_transport_preserves_run_and_close_failures() {
        let error = Server::new("returning-combined-failure-test", "1.0.0")
            .build()
            .run_transport_returning_with_cx(
                &Cx::for_testing(),
                ReturningProbeTransport {
                    receive: ReturningProbeReceive::Timeout,
                    fail_send: false,
                    fail_close: true,
                    close_calls: Arc::new(AtomicUsize::new(0)),
                },
            )
            .expect_err("run and close failures must both propagate");

        let data = error.data.expect("combined failure data");
        assert_eq!(data["stage"], "run_and_close");
        assert_eq!(data["kind"], "multiple_failures");
        assert_eq!(data["run"]["data"]["stage"], "receive");
        assert_eq!(data["run"]["data"]["kind"], "timeout");
        assert_eq!(data["close"]["data"]["stage"], "close");
        assert_eq!(data["close"]["data"]["kind"], "io");
    }

    // Exact-2024 era: legacy dispatch and region-close error combination.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn legacy_request_dispatch_and_region_close_retain_simultaneous_failures() {
        let combined = combine_legacy_dispatch_and_close::<()>(
            Err(Legacy2024HandlerError::new("dispatch failed")),
            Err(Legacy2024HandlerError::new("region close failed")),
        )
        .expect_err("both request failures must remain observable");

        assert_eq!(combined.code().as_i32(), Some(-32603));
        assert!(combined.message().contains("dispatch failed"));
        assert!(combined.message().contains("region close failed"));
    }

    // Exact-2024 era: used only by LegacyOnly returning-loop tests.
    #[cfg(feature = "legacy-2024-11-05")]
    struct LegacyReturningOwnershipTool {
        regions: Arc<Mutex<Vec<RegionId>>>,
        cancel_first: bool,
    }

    #[cfg(feature = "legacy-2024-11-05")]
    impl ToolHandler for LegacyReturningOwnershipTool {
        fn definition(&self) -> Tool {
            Tool {
                name: "legacy_returning_ownership_tool".to_owned(),
                description: Some("Records exact legacy request ownership".to_owned()),
                input_schema: serde_json::json!({"type": "object"}),
                output_schema: None,
                icon: None,
                version: None,
                tags: Vec::new(),
                annotations: None,
            }
        }

        fn call(&self, ctx: &McpContext, _arguments: serde_json::Value) -> McpResult<Vec<Content>> {
            self.regions
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(ctx.cx().region_id());
            if self.cancel_first && ctx.request_id() == 201 {
                // Ambient request-region cancellation remains response-bearing;
                // explicit request-token cancellation is reserved for accepted
                // peer cancellation and intentionally suppresses its response.
                ctx.cx().cancel_with(
                    CancelKind::User,
                    Some("legacy request ambient cancellation fixture"),
                );
                return Err(McpError::request_cancelled());
            }
            Ok(vec![Content::text(format!(
                "legacy-request-{}",
                ctx.request_id()
            ))])
        }
    }

    // Exact-2024 era: used only by tests that open with a legacy handshake.
    #[cfg(feature = "legacy-2024-11-05")]
    fn run_returning_transport_with_test_runtime<T>(server: Server, transport: T) -> McpResult<()>
    where
        T: Transport + Send + 'static,
    {
        let runtime = RuntimeBuilder::current_thread()
            .with_reactor(create_reactor().expect("legacy returning test reactor must initialize"))
            .blocking_threads(2, MAX_DISPATCH_QUEUE_DEPTH)
            .build()
            .expect("legacy returning test runtime must initialize");
        let (result_sender, result_receiver) = sync_channel(1);
        runtime.block_on(async move {
            let cx = Cx::current().expect("legacy returning test runtime must install Cx");
            let pump = cx
                .spawn_blocking(move |pump_cx| {
                    let result = server.run_transport_returning_with_cx(&pump_cx, transport);
                    let _ = result_sender.send(result);
                })
                .map_err(|error| McpError::internal_error(error.to_string()))?;
            let deadline = cx.now().saturating_add_nanos(RETURNING_PUMP_WATCHDOG_NANOS);
            loop {
                match result_receiver.try_recv() {
                    Ok(result) => {
                        drop(pump);
                        break result;
                    }
                    Err(std::sync::mpsc::TryRecvError::Disconnected) => {
                        return Err(McpError::internal_error(
                            "legacy returning test pump exited without a result",
                        ));
                    }
                    Err(std::sync::mpsc::TryRecvError::Empty) => {
                        asupersync::time::timeout_at(
                            deadline,
                            asupersync::time::sleep(cx.now(), Duration::from_millis(1)),
                        )
                        .await
                        .map_err(|_| McpError::internal_error("legacy returning test timed out"))?;
                    }
                }
            }
        })
    }

    /// Exact acceptance ID: successful legacy request completion followed by
    /// sibling reuse on the same caller-owned custom connection.
    // Exact-2024 era: selects LegacyOnly, which a no-legacy build refuses.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn fnd_04_b_positive() {
        let regions = Arc::new(Mutex::new(Vec::new()));
        let sent = Arc::new(Mutex::new(Vec::new()));
        run_returning_transport_with_test_runtime(
            Server::new("fnd-04-b-positive", "1.0.0")
                .protocol_policy(ProtocolPolicy::LegacyOnly)
                .expect("LegacyOnly must be available to this test build")
                .tool(LegacyReturningOwnershipTool {
                    regions: Arc::clone(&regions),
                    cancel_first: false,
                })
                .build(),
            ProtocolPolicyScriptTransport {
                inbound: std::collections::VecDeque::from([
                    exact_legacy_initialize_request(100, serde_json::json!("1.0.0")),
                    JsonRpcMessage::Request(JsonRpcRequest::notification(
                        "notifications/initialized",
                        None,
                    )),
                    JsonRpcMessage::Request(JsonRpcRequest::new(
                        "tools/call",
                        Some(serde_json::json!({
                            "name": "legacy_returning_ownership_tool",
                            "arguments": {},
                        })),
                        101_i64,
                    )),
                    JsonRpcMessage::Request(JsonRpcRequest::new(
                        "tools/call",
                        Some(serde_json::json!({
                            "name": "legacy_returning_ownership_tool",
                            "arguments": {},
                        })),
                        102_i64,
                    )),
                ]),
                sent: Arc::clone(&sent),
                receive_calls: Arc::new(AtomicUsize::new(0)),
            },
        )
        .expect("legacy custom returning script must complete");

        let sent = sent
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        for id in [100_i64, 101, 102] {
            assert_eq!(
                sent.iter()
                    .filter(|message| matches!(message, JsonRpcMessage::Response(response) if response.id == Some(id.into())))
                    .count(),
                1,
                "legacy response {id} must be committed exactly once"
            );
        }
        let regions = regions
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert_eq!(regions.len(), 2);
        assert_ne!(
            regions[0], regions[1],
            "sibling requests need distinct child regions"
        );
    }

    /// Exact acceptance ID: near-identical cancellation/EOF case retaining
    /// sibling completion and both dispatch/close diagnostics.
    // Exact-2024 era: selects LegacyOnly, which a no-legacy build refuses.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn fnd_04_b_planted_negative() {
        let regions = Arc::new(Mutex::new(Vec::new()));
        let sent = Arc::new(Mutex::new(Vec::new()));
        run_returning_transport_with_test_runtime(
            Server::new("fnd-04-b-planted-negative", "1.0.0")
                .protocol_policy(ProtocolPolicy::LegacyOnly)
                .expect("LegacyOnly must be available to this test build")
                .tool(LegacyReturningOwnershipTool {
                    regions: Arc::clone(&regions),
                    cancel_first: true,
                })
                .build(),
            ProtocolPolicyScriptTransport {
                inbound: std::collections::VecDeque::from([
                    exact_legacy_initialize_request(200, serde_json::json!("1.0.0")),
                    JsonRpcMessage::Request(JsonRpcRequest::notification(
                        "notifications/initialized",
                        None,
                    )),
                    JsonRpcMessage::Request(JsonRpcRequest::new(
                        "tools/call",
                        Some(serde_json::json!({
                            "name": "legacy_returning_ownership_tool",
                            "arguments": {},
                        })),
                        201_i64,
                    )),
                    JsonRpcMessage::Request(JsonRpcRequest::new(
                        "tools/call",
                        Some(serde_json::json!({
                            "name": "legacy_returning_ownership_tool",
                            "arguments": {},
                        })),
                        202_i64,
                    )),
                ]),
                sent: Arc::clone(&sent),
                receive_calls: Arc::new(AtomicUsize::new(0)),
            },
        )
        .expect("cancellation must not poison the returning custom connection");

        let sent = sent
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let first = sent
            .iter()
            .find_map(|message| match message {
                JsonRpcMessage::Response(response) if response.id == Some(201_i64.into()) => {
                    Some(response)
                }
                _ => None,
            })
            .expect("cancelled request must still commit its exact legacy error response");
        assert_eq!(
            first.error.as_ref().and_then(|error| error.code.as_i32()),
            Some(i32::from(McpErrorCode::RequestCancelled))
        );
        let sibling = sent
            .iter()
            .find_map(|message| match message {
                JsonRpcMessage::Response(response) if response.id == Some(202_i64.into()) => {
                    Some(response)
                }
                _ => None,
            })
            .expect("sibling response must survive target cancellation and clean EOF");
        assert!(sibling.error.is_none());
        let regions = regions
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert_eq!(regions.len(), 2);
        assert_ne!(
            regions[0], regions[1],
            "cancellation must not reuse the target region"
        );
    }

    // Exact-2024 era: selects LegacyOnly, which a no-legacy build refuses.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn legacy_returning_completed_request_allows_sibling_reuse_after_eof() {
        let regions = Arc::new(Mutex::new(Vec::new()));
        let sent = Arc::new(Mutex::new(Vec::new()));
        run_returning_transport_with_test_runtime(
            Server::new("legacy-returning-sibling-reuse", "1.0.0")
                .protocol_policy(ProtocolPolicy::LegacyOnly)
                .expect("LegacyOnly must be available to this test build")
                .tool(LegacyReturningOwnershipTool {
                    regions: Arc::clone(&regions),
                    cancel_first: false,
                })
                .build(),
            ProtocolPolicyScriptTransport {
                inbound: std::collections::VecDeque::from([
                    exact_legacy_initialize_request(300, serde_json::json!("1.0.0")),
                    JsonRpcMessage::Request(JsonRpcRequest::notification(
                        "notifications/initialized",
                        None,
                    )),
                    JsonRpcMessage::Request(JsonRpcRequest::new(
                        "tools/call",
                        Some(serde_json::json!({
                            "name": "legacy_returning_ownership_tool",
                            "arguments": {},
                        })),
                        301_i64,
                    )),
                    JsonRpcMessage::Request(JsonRpcRequest::new(
                        "tools/call",
                        Some(serde_json::json!({
                            "name": "legacy_returning_ownership_tool",
                            "arguments": {},
                        })),
                        301_i64,
                    )),
                ]),
                sent: Arc::clone(&sent),
                receive_calls: Arc::new(AtomicUsize::new(0)),
            },
        )
        .expect("completed request must permit same-id sibling reuse before EOF");

        let sent = sent
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert_eq!(
            sent.iter()
                .filter(|message| matches!(message, JsonRpcMessage::Response(response) if response.id == Some(301_i64.into())))
                .count(),
            2,
            "both completed requests must commit their responses"
        );
        let regions = regions
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert_eq!(regions.len(), 2);
        assert_ne!(
            regions[0], regions[1],
            "reused request IDs must receive distinct child regions"
        );
    }

    #[test]
    fn returning_subscription_nonquiescence_preserves_operation_and_close_errors() {
        returning_subscription_cleanup_case(false, false);
    }

    #[test]
    fn returning_subscription_quiescence_runs_hook_after_owner_retirement() {
        returning_subscription_cleanup_case(true, false);
    }

    #[test]
    fn returning_subscription_protocol_failure_preserves_cleanup_and_close_errors() {
        returning_subscription_cleanup_case(false, true);
    }

    #[test]
    fn returning_subscription_protocol_failure_after_quiescence_runs_hook() {
        returning_subscription_cleanup_case(true, true);
    }

    #[test]
    fn returning_subscription_background_response_write_succeeds() {
        returning_subscription_background_write_case(false);
    }

    #[test]
    fn returning_subscription_background_response_write_failure_survives_eof() {
        returning_subscription_background_write_case(true);
    }

    #[test]
    fn returning_subscription_matching_peer_cancel_retires_only_its_owner() {
        returning_subscription_peer_cancel_case(true);
    }

    #[test]
    fn returning_subscription_unrelated_peer_cancel_preserves_owner_until_eof() {
        returning_subscription_peer_cancel_case(false);
    }

    fn returning_subscription_peer_cancel_case(matching: bool) {
        let runtime = RuntimeBuilder::current_thread()
            .with_reactor(create_reactor().expect("peer cancellation reactor"))
            .blocking_threads(2, MAX_DISPATCH_QUEUE_DEPTH)
            .build()
            .expect("peer cancellation runtime");
        let server = Server::new("returning-peer-cancellation", "1.0.0")
            .protocol_policy(build_default_protocol_policy())
            .expect("the build's default policy must be available")
            .build();
        let active = Arc::clone(&server.active_requests);
        let active_for_recv = Arc::clone(&active);
        let sent = Arc::new(Mutex::new(Vec::new()));
        let sent_for_send = Arc::clone(&sent);
        let (acknowledged, acknowledgement) = sync_channel(1);
        runtime
            .block_on(async move {
                let cx = Cx::current().expect("caller runtime Cx");
                let mut pump = cx
                    .spawn_blocking(move |pump_cx| {
                        let mut phase = 0;
                        server.run_loop_returning(
                            &pump_cx,
                            move |_| {
                                let current = phase;
                                phase += 1;
                                match current {
                                    0 => Ok(modern_discovery_opening_request()),
                                    1 => Ok(modern_subscriptions_listen_request(908)),
                                    2 => {
                                        acknowledgement
                                            .recv_timeout(Duration::from_secs(2))
                                            .expect("real subscription must acknowledge");
                                        assert_eq!(active_for_recv.lock().unwrap().len(), 1);
                                        Ok(JsonRpcMessage::Request(JsonRpcRequest::notification(
                                            "notifications/cancelled",
                                            Some(serde_json::json!({
                                                "requestId": if matching { 908 } else { 909 },
                                                "_meta": {
                                                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                                                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                                                },
                                            })),
                                        )))
                                    }
                                    3 => {
                                        if matching {
                                            let deadline = Instant::now() + Duration::from_secs(2);
                                            while !active_for_recv.lock().unwrap().is_empty() {
                                                assert!(Instant::now() < deadline, "peer cancellation must retire its listener before EOF");
                                                std::thread::sleep(Duration::from_millis(1));
                                            }
                                        } else {
                                            let owners = active_for_recv.lock().unwrap();
                                            assert_eq!(owners.len(), 1);
                                            assert!(!owners.values().next().unwrap().cancellation.is_cancel_requested());
                                        }
                                        Err(TransportError::Closed)
                                    }
                                    _ => panic!("unexpected receive after EOF"),
                                }
                            },
                            move |_, message| {
                                sent_for_send.lock().unwrap().push(message.clone());
                                Ok(())
                            },
                            Arc::new(move |notification| {
                                if notification.method == "notifications/subscriptions/acknowledged" {
                                    acknowledged.send(()).expect("receive pump owns acknowledgement channel");
                                }
                            }),
                            None,
                            "test",
                        )
                    })
                    .expect("caller runtime admits receive pump");
                let result = asupersync::time::timeout(
                    cx.now(),
                    Duration::from_secs(3),
                    pump.join(&cx),
                )
                .await
                .expect("peer cancellation pump must settle")
                .expect("peer cancellation pump must not panic");
                assert!(!cx.is_cancel_requested(), "request cancellation must preserve the caller");
                result
            })
            .expect("peer cancellation followed by EOF is clean");
        assert!(active.lock().unwrap().is_empty());
        let sent = sent.lock().unwrap();
        let completions: Vec<_> = sent
            .iter()
            .filter_map(|message| match message {
                JsonRpcMessage::Response(response)
                    if response.id == Some(RequestId::Number(908)) =>
                {
                    Some(response)
                }
                _ => None,
            })
            .collect();
        if matching {
            assert!(
                completions.is_empty(),
                "peer cancellation suppresses the terminal response"
            );
        } else {
            assert_eq!(completions.len(), 1);
            assert!(final_subscription_completion_response(completions[0]));
        }
    }

    fn returning_subscription_background_write_case(fail_write: bool) {
        struct RejectListen;

        impl Middleware for RejectListen {
            fn on_request(
                &self,
                _ctx: &McpContext,
                request: &JsonRpcRequest,
            ) -> McpResult<MiddlewareDecision> {
                if request.method == SUBSCRIPTIONS_LISTEN {
                    return Err(McpError::invalid_params("listener rejected by application"));
                }
                Ok(MiddlewareDecision::Continue)
            }
        }

        let runtime = RuntimeBuilder::current_thread()
            .with_reactor(create_reactor().expect("background write test reactor"))
            .blocking_threads(2, MAX_DISPATCH_QUEUE_DEPTH)
            .build()
            .expect("background write test runtime");
        let attempts = Arc::new(AtomicUsize::new(0));
        let attempts_for_send = Arc::clone(&attempts);
        let shutdown_calls = Arc::new(AtomicUsize::new(0));
        let shutdown_calls_for_hook = Arc::clone(&shutdown_calls);
        let server = Server::new("background-response-write", "1.0.0")
            .protocol_policy(build_default_protocol_policy())
            .expect("the build's default policy must be available")
            .middleware(RejectListen)
            .on_shutdown(move || {
                shutdown_calls_for_hook.fetch_add(1, Ordering::AcqRel);
            })
            .build();
        let active = Arc::clone(&server.active_requests);
        let (attempted, attempt_received) = sync_channel(1);
        let result = runtime.block_on(async move {
            let cx = Cx::current().expect("caller runtime Cx");
            let mut pump = cx
                .spawn_blocking(move |pump_cx| {
                    let mut incoming = std::collections::VecDeque::from([
                        modern_discovery_opening_request(),
                        modern_subscriptions_listen_request(906),
                    ]);
                    server.run_loop_returning(
                        &pump_cx,
                        move |_| {
                            if let Some(request) = incoming.pop_front() {
                                return Ok(request);
                            }
                            attempt_received
                                .recv_timeout(Duration::from_secs(2))
                                .expect("worker must attempt its correlated response");
                            Err(TransportError::Closed)
                        },
                        move |_, message| {
                            if let JsonRpcMessage::Response(response) = message
                                && response.id == Some(RequestId::Number(906))
                            {
                                assert_eq!(
                                    response.error.as_ref().map(|error| error.message.as_str()),
                                    Some("listener rejected by application")
                                );
                                attempts_for_send.fetch_add(1, Ordering::AcqRel);
                                attempted
                                    .send(())
                                    .expect("receive pump still owns its channel");
                                if fail_write {
                                    return Err(TransportError::Io(std::io::Error::new(
                                        std::io::ErrorKind::BrokenPipe,
                                        "background response writer failed",
                                    )));
                                }
                            }
                            Ok(())
                        },
                        Arc::new(|_| {}),
                        None,
                        "test",
                    )
                })
                .expect("caller runtime admits the receive pump");
            asupersync::time::timeout(cx.now(), Duration::from_secs(3), pump.join(&cx))
                .await
                .expect("background response pump must settle")
                .expect("background response pump must not panic")
        });
        assert_eq!(attempts.load(Ordering::Acquire), 1);
        if fail_write {
            let error = result.expect_err("clean EOF cannot hide the failed response write");
            let data = error.data.expect("typed write failure");
            assert_eq!(data["stage"], "send");
            assert_eq!(data["kind"], "io");
        } else {
            result.expect("delivered response followed by EOF succeeds");
        }
        assert_eq!(shutdown_calls.load(Ordering::Acquire), 1);
        assert!(active.lock().unwrap().is_empty());
    }

    fn returning_subscription_cleanup_case(release_before_shutdown: bool, invalid_response: bool) {
        struct CloseAfterDrainTransport {
            control: Arc<NonQuiescentLegacyControl>,
            phase: usize,
            close_calls: Arc<AtomicUsize>,
            closed_before_drain: Arc<AtomicBool>,
            release_before_shutdown: bool,
            invalid_response: bool,
        }

        struct NonQuiescentSubscriptionMiddleware {
            control: Arc<NonQuiescentLegacyControl>,
        }

        impl Middleware for NonQuiescentSubscriptionMiddleware {
            fn on_request(
                &self,
                _ctx: &McpContext,
                request: &JsonRpcRequest,
            ) -> McpResult<MiddlewareDecision> {
                if request.method == SUBSCRIPTIONS_LISTEN {
                    self.control.wait_until_released();
                }
                Ok(MiddlewareDecision::Continue)
            }
        }

        impl Transport for CloseAfterDrainTransport {
            fn send(&mut self, _cx: &Cx, _message: &JsonRpcMessage) -> Result<(), TransportError> {
                Ok(())
            }

            fn recv(&mut self, _cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
                let phase = self.phase;
                self.phase = self.phase.saturating_add(1);
                match phase {
                    0 => Ok(modern_discovery_opening_request()),
                    1 => Ok(modern_subscriptions_listen_request(903)),
                    2 if self.control.wait_for_started(Duration::from_secs(2)) => {
                        if self.release_before_shutdown {
                            self.control.release();
                            assert!(self.control.wait_for_finished(Duration::from_secs(2)));
                        }
                        if self.invalid_response {
                            let mut response = JsonRpcResponse::success(
                                RequestId::Number(904),
                                serde_json::json!({}),
                            );
                            response.jsonrpc = "1.0".into();
                            return Ok(JsonRpcMessage::Response(response));
                        }
                        Err(TransportError::Io(std::io::Error::new(
                            std::io::ErrorKind::BrokenPipe,
                            "receive while request remains active",
                        )))
                    }
                    _ => Err(TransportError::Timeout),
                }
            }

            fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
                self.close_calls.fetch_add(1, Ordering::AcqRel);
                if !self.control.has_finished() {
                    self.closed_before_drain.store(true, Ordering::Release);
                }
                Err(TransportError::Io(std::io::Error::new(
                    std::io::ErrorKind::BrokenPipe,
                    "close after request drain",
                )))
            }
        }

        let control = Arc::new(NonQuiescentLegacyControl::default());
        let runtime = RuntimeBuilder::current_thread()
            .with_reactor(create_reactor().expect("bounded cleanup test reactor must initialize"))
            .blocking_threads(2, MAX_DISPATCH_QUEUE_DEPTH)
            .build()
            .expect("bounded cleanup test runtime must initialize");
        let closed_before_drain = Arc::new(AtomicBool::new(false));
        let shutdown_before_drain = Arc::new(AtomicBool::new(false));
        let shutdown_calls = Arc::new(AtomicUsize::new(0));
        let close_calls = Arc::new(AtomicUsize::new(0));
        let control_for_shutdown = Arc::clone(&control);
        let shutdown_before_drain_for_hook = Arc::clone(&shutdown_before_drain);
        let shutdown_calls_for_hook = Arc::clone(&shutdown_calls);
        let server = Server::new("legacy-returning-bounded-cleanup", "1.0.0")
            .protocol_policy(build_default_protocol_policy())
            .expect("the build's default policy must be available")
            .middleware(NonQuiescentSubscriptionMiddleware {
                control: Arc::clone(&control),
            })
            .on_shutdown(move || {
                shutdown_calls_for_hook.fetch_add(1, Ordering::AcqRel);
                if !control_for_shutdown.has_finished() {
                    shutdown_before_drain_for_hook.store(true, Ordering::Release);
                }
            })
            .build();
        let active_requests_for_assert = Arc::clone(&server.active_requests);

        struct ReleaseNonCooperativeOnDrop(Arc<NonQuiescentLegacyControl>);

        impl Drop for ReleaseNonCooperativeOnDrop {
            fn drop(&mut self) {
                self.0.release();
                let _ = self.0.wait_for_finished(Duration::from_secs(2));
            }
        }

        let _release_on_failure = ReleaseNonCooperativeOnDrop(Arc::clone(&control));

        runtime
            .block_on(async move {
                let cx = Cx::current().expect("bounded cleanup test runtime must install Cx");
                let (result_sender, result_receiver) = sync_channel(1);
                let control_for_transport = Arc::clone(&control);
                let close_calls_for_transport = Arc::clone(&close_calls);
                let closed_before_drain_for_transport = Arc::clone(&closed_before_drain);
                let mut pump = cx
                    .spawn_blocking(move |pump_cx| {
                        let result = server.run_transport_returning_with_cx(
                            &pump_cx,
                            CloseAfterDrainTransport {
                                control: control_for_transport,
                                phase: 0,
                                close_calls: close_calls_for_transport,
                                closed_before_drain: closed_before_drain_for_transport,
                                release_before_shutdown,
                                invalid_response,
                            },
                        );
                        let _ = result_sender.send(result);
                    })
                    .expect("returning bounded cleanup pump must be admitted");
                let started = Instant::now();
                // Same anti-hang watchdog as the sibling returning-pump helpers, and for
                // the same reason. 8 s stood here, but the branch below deliberately waits
                // `>= SHUTDOWN_CLEANUP_TIMEOUT` (5 s), which left only ~3 s of headroom for
                // pump scheduling on a host running the other 2307 tests concurrently. That
                // is the same upper-bound-on-wall-time mistake the comment further down
                // records for the removed `started.elapsed() < SHUTDOWN_CLEANUP_TIMEOUT`
                // assertion, which flaked 1926/0 then 1925/1 on identical source.
                let deadline = cx.now().saturating_add_nanos(RETURNING_PUMP_WATCHDOG_NANOS);
                let result = loop {
                    match result_receiver.try_recv() {
                        Ok(result) => break result,
                        Err(std::sync::mpsc::TryRecvError::Disconnected) => {
                            panic!(
                                "returning bounded cleanup pump exited without reporting its result"
                            );
                        }
                        Err(std::sync::mpsc::TryRecvError::Empty) => {
                            asupersync::time::timeout_at(
                                deadline,
                                asupersync::time::sleep(cx.now(), Duration::from_millis(1)),
                            )
                            .await
                            .expect("returning bounded cleanup pump must settle within its bound");
                        }
                    }
                };

                pump.join(&cx)
                    .await
                    .expect("returning bounded-failure pump task must finish");
                let error = result.expect_err("transport close failure must remain visible");
                assert_eq!(
                    error.data.as_ref().and_then(|data| data["stage"].as_str()),
                    Some("run_and_close")
                );
                let data = error
                    .data
                    .as_ref()
                    .expect("combined error must include data");
                assert_eq!(data["kind"], "multiple_failures");
                let receive_kind = if invalid_response {
                    "invalid_response"
                } else {
                    "io"
                };
                if release_before_shutdown {
                    // `stage == "receive"` already entails that the non-quiescent
                    // cleanup wait was not entered: entering it produces a
                    // `run_and_cleanup` combined error carrying a `cleanup` key,
                    // which is what the other branch asserts. The two are mutually
                    // exclusive by construction, so this branch needs no separate
                    // check that the cleanup timeout was skipped.
                    //
                    // An `assert!(started.elapsed() < SHUTDOWN_CLEANUP_TIMEOUT)`
                    // stood here and was removed. It added no information about the
                    // property above, and it was an UPPER bound on real wall time
                    // (`Instant::now()`) covering the whole pump lifecycle, so a
                    // loaded host failed it with no code change: this test passed
                    // 1926/0 and failed 1925/1 seventeen minutes apart on identical
                    // source. Note the sibling branch's `>= SHUTDOWN_CLEANUP_TIMEOUT`
                    // is a LOWER bound and is load-monotone, so it is sound and stays.
                    // Do not reinstate an upper bound on wall time here.
                    assert_eq!(data["run"]["data"]["stage"], "receive");
                    assert_eq!(data["run"]["data"]["kind"], receive_kind);
                } else {
                    assert_eq!(data["run"]["data"]["stage"], "run_and_cleanup");
                    assert_eq!(data["run"]["data"]["kind"], "multiple_failures");
                    assert_eq!(data["run"]["data"]["run"]["data"]["stage"], "receive");
                    assert_eq!(data["run"]["data"]["run"]["data"]["kind"], receive_kind);
                    assert_eq!(data["run"]["data"]["cleanup"]["data"]["stage"], "shutdown");
                    assert_eq!(
                        data["run"]["data"]["cleanup"]["data"]["kind"],
                        "non_quiescent"
                    );
                    assert!(
                        data["run"]["data"]["cleanup"]["data"]["remaining"]
                            .as_u64()
                            .unwrap_or(0)
                            >= 1
                    );
                    assert!(started.elapsed() >= SHUTDOWN_CLEANUP_TIMEOUT);
                }
                assert_eq!(data["close"]["data"]["stage"], "close");
                assert_eq!(data["close"]["data"]["kind"], "io");
                assert_eq!(close_calls.load(Ordering::Acquire), 1);
                assert_eq!(
                    closed_before_drain.load(Ordering::Acquire),
                    !release_before_shutdown
                );
                assert!(!shutdown_before_drain.load(Ordering::Acquire));
                assert_eq!(
                    shutdown_calls.load(Ordering::Acquire),
                    usize::from(release_before_shutdown)
                );
                assert_eq!(
                    active_requests_for_assert
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .is_empty(),
                    release_before_shutdown
                );
                control.release();
                assert!(control.wait_for_finished(Duration::from_secs(2)));
                let cleanup_deadline = cx.now().saturating_add_nanos(2_000_000_000);
                while !active_requests_for_assert
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .is_empty()
                {
                    asupersync::time::timeout_at(
                        cleanup_deadline,
                        asupersync::time::sleep(cx.now(), Duration::from_millis(1)),
                    )
                    .await
                    .expect("released request region must retire before fixture teardown");
                }
                assert!(control.has_finished());
                assert!(
                    active_requests_for_assert
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .is_empty()
                );
                Ok::<(), McpError>(())
            })
            .expect("returning bounded cleanup failure must preserve ownership and errors");
    }

    // bd-gl2we: the `returning_subscription_*` family fails intermittently
    // through two races around a stdio listen's acknowledgement (comment 5403).
    // These pairs FORCE each interleaving instead of waiting for load to find
    // it. Each pair differs only in the ordering it forces, and each records
    // that the ordering was actually reached, so a pass on an unforced run
    // cannot pass silently. They are deliberately outside the family's
    // `returning_subscription_*` prefix and its denominator.
    //
    // Both pairs now assert the contract. The pump-first test was bd-gl2we
    // finding F1: stdio shutdown lost a pending graceful election. bd-81cct
    // fixed it by having shutdown wait for the owner of a won election before
    // generic cancellation. The under-recv-lock test was F2: an
    // acknowledgement sent during an unsplit transport's `recv` failed the
    // connection. bd-8bcfq fixed it by queueing such output until `recv`
    // returns.

    #[test]
    fn forced_subscription_ack_order_pump_first_keeps_graceful_completion() {
        forced_subscription_shutdown_order_case(true);
    }

    #[test]
    fn forced_subscription_ack_order_active_first_keeps_graceful_completion() {
        forced_subscription_shutdown_order_case(false);
    }

    #[test]
    fn forced_subscription_ack_order_under_recv_lock_is_written_when_recv_returns() {
        forced_subscription_recv_lock_order_case(true);
    }

    #[test]
    fn forced_subscription_ack_order_outside_recv_lock_reports_receive_stage() {
        forced_subscription_recv_lock_order_case(false);
    }

    /// Election phases of every live final-subscription lease. The entry list
    /// is copied out before any phase lock is taken, so this never holds the
    /// registry mutex and an election mutex at once.
    fn final_subscription_phases(
        registry: &FinalSubscriptionRegistry,
    ) -> Vec<FinalSubscriptionPhase> {
        let elections: Vec<_> = registry
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .entries
            .values()
            .map(|entry| Arc::clone(&entry.election))
            .collect();
        elections
            .iter()
            .map(|election| {
                *election
                    .phase
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
            })
            .collect()
    }

    /// `Active` is published by the opener only after its acknowledgement
    /// callback has returned, so reaching it proves the acknowledgement was
    /// already attempted.
    fn wait_for_single_active_final_subscription(
        registry: &FinalSubscriptionRegistry,
        timeout: Duration,
    ) -> bool {
        let deadline = Instant::now() + timeout;
        loop {
            if final_subscription_phases(registry) == [FinalSubscriptionPhase::Active] {
                return true;
            }
            if Instant::now() >= deadline {
                return false;
            }
            std::thread::sleep(Duration::from_millis(1));
        }
    }

    /// EOF shutdown against a listen whose acknowledgement callback has run.
    /// `pump_first` holds the opener inside that callback, before it can
    /// publish `Active`, until shutdown's `terminate` has recorded
    /// `ServerTerminationPending(0)`. It then keeps holding for a grace window
    /// in which a generic shutdown cancellation, had it been issued, would
    /// defeat the opener's deferred election. Otherwise the pump holds EOF
    /// until the opener has published `Active`, and shutdown elects the
    /// graceful completion directly. Either order must deliver exactly one
    /// graceful completion.
    fn forced_subscription_shutdown_order_case(pump_first: bool) {
        let runtime = RuntimeBuilder::current_thread()
            .with_reactor(create_reactor().expect("forced shutdown-order reactor"))
            .blocking_threads(2, MAX_DISPATCH_QUEUE_DEPTH)
            .build()
            .expect("forced shutdown-order runtime");
        let server = Server::new("forced-subscription-shutdown-order", "1.0.0")
            .protocol_policy(build_default_protocol_policy())
            .expect("the build's default policy must be available")
            .build();
        let active = Arc::clone(&server.active_requests);
        let active_for_callback = Arc::clone(&active);
        let registry = Arc::clone(&server.final_subscriptions);
        let registry_for_callback = Arc::clone(&registry);
        let sent = Arc::new(Mutex::new(Vec::new()));
        let sent_for_send = Arc::clone(&sent);
        let forced = Arc::new(AtomicBool::new(false));
        let forced_by_callback = Arc::clone(&forced);
        let forced_by_recv = Arc::clone(&forced);
        let cancelled_during_callback = Arc::new(AtomicBool::new(false));
        let cancelled_by_callback = Arc::clone(&cancelled_during_callback);
        let (acknowledged, acknowledgement) = sync_channel(1);
        runtime
            .block_on(async move {
                let cx = Cx::current().expect("caller runtime Cx");
                let mut pump = cx
                    .spawn_blocking(move |pump_cx| {
                        let mut phase = 0;
                        server.run_loop_returning(
                            &pump_cx,
                            move |_| {
                                let current = phase;
                                phase += 1;
                                match current {
                                    0 => Ok(modern_discovery_opening_request()),
                                    1 => Ok(modern_subscriptions_listen_request(910)),
                                    2 => {
                                        acknowledgement
                                            .recv_timeout(Duration::from_secs(2))
                                            .expect("real subscription must acknowledge");
                                        if !pump_first
                                            && wait_for_single_active_final_subscription(
                                                &registry,
                                                Duration::from_secs(2),
                                            )
                                        {
                                            forced_by_recv.store(true, Ordering::Release);
                                        }
                                        Err(TransportError::Closed)
                                    }
                                    _ => panic!("unexpected receive after EOF"),
                                }
                            },
                            move |_, message| {
                                sent_for_send.lock().unwrap().push(message.clone());
                                Ok(())
                            },
                            Arc::new(move |notification| {
                                if notification.method != "notifications/subscriptions/acknowledged"
                                {
                                    return;
                                }
                                // The lease is registered before its
                                // acknowledgement is sent; keep its election
                                // so the phase stays observable after
                                // `terminate` removes the registry entry.
                                let elections: Vec<_> = registry_for_callback
                                    .inner
                                    .lock()
                                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                                    .entries
                                    .values()
                                    .map(|entry| Arc::clone(&entry.election))
                                    .collect();
                                acknowledged
                                    .send(())
                                    .expect("receive pump owns acknowledgement channel");
                                if !pump_first {
                                    return;
                                }
                                let deadline = Instant::now() + Duration::from_secs(2);
                                let server_won_during_callback = loop {
                                    if elections.iter().any(|election| {
                                        *election
                                            .phase
                                            .lock()
                                            .unwrap_or_else(std::sync::PoisonError::into_inner)
                                            == FinalSubscriptionPhase::ServerTerminationPending(0)
                                    }) {
                                        break true;
                                    }
                                    if Instant::now() >= deadline {
                                        break false;
                                    }
                                    std::thread::sleep(Duration::from_millis(1));
                                };
                                if !server_won_during_callback {
                                    return;
                                }
                                forced_by_callback.store(true, Ordering::Release);
                                // Shutdown must not cancel the request while
                                // this callback still owns the won election.
                                let grace = Instant::now() + Duration::from_millis(500);
                                while Instant::now() < grace {
                                    if active_for_callback
                                        .lock()
                                        .unwrap()
                                        .values()
                                        .any(|owner| owner.cancellation.is_cancel_requested())
                                    {
                                        cancelled_by_callback.store(true, Ordering::Release);
                                        return;
                                    }
                                    std::thread::sleep(Duration::from_millis(1));
                                }
                            }),
                            None,
                            "test",
                        )
                    })
                    .expect("caller runtime admits receive pump");
                asupersync::time::timeout(cx.now(), Duration::from_secs(3), pump.join(&cx))
                    .await
                    .expect("forced shutdown-order pump must settle")
                    .expect("forced shutdown-order pump must not panic")
            })
            .expect("EOF after an acknowledged listen is a clean close");
        assert!(
            forced.load(Ordering::Acquire),
            "the {} interleaving was not forced",
            if pump_first {
                "pump-first"
            } else {
                "active-first"
            }
        );
        assert!(active.lock().unwrap().is_empty());
        let sent = sent.lock().unwrap();
        let responses: Vec<_> = sent
            .iter()
            .filter_map(|message| match message {
                JsonRpcMessage::Response(response)
                    if response.id == Some(RequestId::Number(910)) =>
                {
                    Some(response)
                }
                _ => None,
            })
            .collect();
        assert!(
            !cancelled_during_callback.load(Ordering::Acquire),
            "shutdown cancelled the request while its won election was still pending"
        );
        assert_eq!(responses.len(), 1, "{responses:?}");
        assert!(final_subscription_completion_response(responses[0]));
    }

    /// An invalid response frame after an acknowledged listen, on an unsplit
    /// transport. Both variants send the same frames and run the same
    /// release-then-wait-for-`Active` step; only its location differs.
    /// `ack_under_recv_lock` runs it inside `recv`, while `SharedTransport`'s
    /// pump owns the I/O handle, so the acknowledgement is queued and written
    /// when that `recv` returns (receive phase 4). Otherwise it runs in
    /// middleware for an inline request, after `recv` has released the handle,
    /// and is written directly (receive phase 3).
    fn forced_subscription_recv_lock_order_case(ack_under_recv_lock: bool) {
        struct ForcedAckOrderTransport {
            control: Arc<NonQuiescentLegacyControl>,
            registry: Arc<FinalSubscriptionRegistry>,
            forced: Arc<AtomicBool>,
            acknowledgement_phases: Arc<Mutex<Vec<usize>>>,
            phase: usize,
            ack_under_recv_lock: bool,
        }

        struct ForcedAckOrderMiddleware {
            control: Arc<NonQuiescentLegacyControl>,
            registry: Arc<std::sync::OnceLock<Arc<FinalSubscriptionRegistry>>>,
            forced: Arc<AtomicBool>,
            ack_under_recv_lock: bool,
        }

        impl Middleware for ForcedAckOrderMiddleware {
            fn on_request(
                &self,
                _ctx: &McpContext,
                request: &JsonRpcRequest,
            ) -> McpResult<MiddlewareDecision> {
                if request.method == SUBSCRIPTIONS_LISTEN {
                    self.control.wait_until_released();
                } else if !self.ack_under_recv_lock && request.id == Some(RequestId::Number(907)) {
                    self.control.release();
                    let registry = self
                        .registry
                        .get()
                        .expect("registry is published before the pump starts");
                    if wait_for_single_active_final_subscription(registry, Duration::from_secs(2)) {
                        self.forced.store(true, Ordering::Release);
                    }
                }
                Ok(MiddlewareDecision::Continue)
            }
        }

        impl Transport for ForcedAckOrderTransport {
            fn send(&mut self, _cx: &Cx, message: &JsonRpcMessage) -> Result<(), TransportError> {
                if let JsonRpcMessage::Request(request) = message
                    && request.method == "notifications/subscriptions/acknowledged"
                {
                    self.acknowledgement_phases
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .push(self.phase);
                }
                Ok(())
            }

            fn recv(&mut self, _cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
                let phase = self.phase;
                self.phase = self.phase.saturating_add(1);
                match phase {
                    0 => Ok(modern_discovery_opening_request()),
                    1 => Ok(modern_subscriptions_listen_request(911)),
                    2 => Ok(modern_discovery_request(907)),
                    3 => {
                        if self.ack_under_recv_lock {
                            self.control.release();
                            if wait_for_single_active_final_subscription(
                                &self.registry,
                                Duration::from_secs(2),
                            ) {
                                self.forced.store(true, Ordering::Release);
                            }
                        }
                        let mut response =
                            JsonRpcResponse::success(RequestId::Number(912), serde_json::json!({}));
                        response.jsonrpc = "1.0".into();
                        Ok(JsonRpcMessage::Response(response))
                    }
                    _ => Err(TransportError::Timeout),
                }
            }

            fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
                Ok(())
            }
        }

        let control = Arc::new(NonQuiescentLegacyControl::default());
        let forced = Arc::new(AtomicBool::new(false));
        let acknowledgement_phases = Arc::new(Mutex::new(Vec::new()));
        let registry_cell = Arc::new(std::sync::OnceLock::new());
        let runtime = RuntimeBuilder::current_thread()
            .with_reactor(create_reactor().expect("forced recv-lock reactor"))
            .blocking_threads(2, MAX_DISPATCH_QUEUE_DEPTH)
            .build()
            .expect("forced recv-lock runtime");
        let server = Server::new("forced-subscription-recv-lock-order", "1.0.0")
            .protocol_policy(build_default_protocol_policy())
            .expect("the build's default policy must be available")
            .middleware(ForcedAckOrderMiddleware {
                control: Arc::clone(&control),
                registry: Arc::clone(&registry_cell),
                forced: Arc::clone(&forced),
                ack_under_recv_lock,
            })
            .build();
        let registry = Arc::clone(&server.final_subscriptions);
        assert!(registry_cell.set(Arc::clone(&registry)).is_ok());
        let active = Arc::clone(&server.active_requests);
        let transport = ForcedAckOrderTransport {
            control: Arc::clone(&control),
            registry,
            forced: Arc::clone(&forced),
            acknowledgement_phases: Arc::clone(&acknowledgement_phases),
            phase: 0,
            ack_under_recv_lock,
        };
        let result = runtime.block_on(async move {
            let cx = Cx::current().expect("caller runtime Cx");
            let mut pump = cx
                .spawn_blocking(move |pump_cx| {
                    server.run_transport_returning_with_cx(&pump_cx, transport)
                })
                .expect("caller runtime admits receive pump");
            asupersync::time::timeout(cx.now(), Duration::from_secs(5), pump.join(&cx))
                .await
                .expect("forced recv-lock pump must settle")
                .expect("forced recv-lock pump must not panic")
        });
        control.release();
        assert!(
            forced.load(Ordering::Acquire),
            "the {} interleaving was not forced",
            if ack_under_recv_lock {
                "under-recv-lock"
            } else {
                "outside-recv-lock"
            }
        );
        let error = result.expect_err("an invalid response frame terminates the connection");
        let data = error.data.as_ref().expect("typed run failure");
        // Exactly one acknowledgement reaches the wire either way. Under the
        // receive lock it is queued and written right after the fourth `recv`
        // returns, before the pump classifies that frame; otherwise it is
        // written directly while the pump dispatches the third frame.
        let expected_phase = if ack_under_recv_lock { 4 } else { 3 };
        assert_eq!(
            *acknowledgement_phases
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner),
            [expected_phase],
            "{error:?}"
        );
        assert_eq!(data["stage"], "receive", "{error:?}");
        assert_eq!(data["kind"], "invalid_response", "{error:?}");
        assert!(active.lock().unwrap().is_empty());
    }

    // Exact-2024 era: negotiates the connection with a legacy initialize.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn returning_loop_replies_to_bounded_codec_error_then_reads_next_frame() {
        use std::collections::VecDeque;
        use std::sync::atomic::AtomicUsize;

        // A malformed OPENING frame is a fatal era-security rejection under
        // Auto, so the recoverable-parse-error contract is probed on an
        // already negotiated connection.
        let steps = Arc::new(Mutex::new(VecDeque::from([
            Ok(exact_legacy_initialize_request(
                32,
                serde_json::json!("1.0.0"),
            )),
            Ok(JsonRpcMessage::Request(JsonRpcRequest::notification(
                "notifications/initialized",
                None,
            ))),
            Err(TransportError::Codec(fastmcp_transport::CodecError::Json(
                serde_json::from_str::<serde_json::Value>("{")
                    .expect_err("fixture must be invalid JSON"),
            ))),
            Err(TransportError::Closed),
        ])));
        let receive_calls = Arc::new(AtomicUsize::new(0));
        let sent = Arc::new(Mutex::new(Vec::<JsonRpcMessage>::new()));
        let receive_steps = Arc::clone(&steps);
        let receive_count = Arc::clone(&receive_calls);
        let sent_messages = Arc::clone(&sent);

        let cx = Cx::for_testing();
        Server::new("recoverable-codec-error-test", "1.0.0")
            .build()
            .run_loop_returning_with_dispatch_cx(
                &cx,
                &cx,
                move |_, _worker_failed| {
                    receive_count.fetch_add(1, Ordering::Relaxed);
                    receive_steps
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .pop_front()
                        .unwrap_or(Err(TransportError::Closed))
                },
                move |_, message| {
                    sent_messages
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .push(message.clone());
                    Ok(())
                },
                Arc::new(|_| {}),
                None,
                "test",
            )
            .expect("clean transport closure after a recoverable codec error must succeed");

        assert_eq!(receive_calls.load(Ordering::Relaxed), 4);
        let sent = sent
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        // The initialize response races worker shutdown and is incidental;
        // the contract is exactly one uncorrelated parse-error reply.
        let parse_errors: Vec<&JsonRpcResponse> = sent
            .iter()
            .filter_map(|message| match message {
                JsonRpcMessage::Response(response) if response.id.is_none() => Some(response),
                _ => None,
            })
            .collect();
        let [response] = parse_errors.as_slice() else {
            panic!("expected exactly one uncorrelated parse-error response");
        };
        assert_eq!(
            response
                .error
                .as_ref()
                .and_then(|error| error.code.as_i32()),
            Some(-32700)
        );
        let wire = serde_json::to_value(response).expect("parse error response must serialize");
        assert!(wire.get("id").is_none());
    }

    struct ModernReturningScriptTransport {
        steps: std::collections::VecDeque<Result<JsonRpcMessage, TransportError>>,
        received: Arc<AtomicUsize>,
        sent: Arc<Mutex<Vec<JsonRpcMessage>>>,
        closed: Arc<AtomicUsize>,
    }

    impl Transport for ModernReturningScriptTransport {
        fn recv(&mut self, _cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
            self.received.fetch_add(1, Ordering::AcqRel);
            self.steps
                .pop_front()
                .unwrap_or(Err(TransportError::Closed))
        }

        fn send(&mut self, _cx: &Cx, message: &JsonRpcMessage) -> Result<(), TransportError> {
            self.sent
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(message.clone());
            Ok(())
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            self.closed.fetch_add(1, Ordering::AcqRel);
            Ok(())
        }
    }

    struct ModernReturningCallbackTransport<R> {
        receive: R,
        sent: Arc<Mutex<Vec<JsonRpcMessage>>>,
    }

    impl<R> Transport for ModernReturningCallbackTransport<R>
    where
        R: FnMut(&Cx) -> Result<JsonRpcMessage, TransportError>,
    {
        fn recv(&mut self, cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
            (self.receive)(cx)
        }

        fn send(&mut self, _cx: &Cx, message: &JsonRpcMessage) -> Result<(), TransportError> {
            self.sent
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(message.clone());
            Ok(())
        }

        fn close(&mut self, _cx: &Cx) -> Result<(), TransportError> {
            Ok(())
        }
    }

    struct ReleaseModernReturningBlocker(Arc<NonQuiescentLegacyControl>);

    impl Drop for ReleaseModernReturningBlocker {
        fn drop(&mut self) {
            self.0.release();
        }
    }

    #[test]
    fn modern_returning_loop_queued_subscription_below_capacity_allows_request() {
        modern_returning_loop_queued_capacity_case(false);
    }

    #[test]
    fn modern_returning_loop_queued_subscription_at_capacity_rejects_request() {
        modern_returning_loop_queued_capacity_case(true);
    }

    fn modern_returning_loop_queued_capacity_case(at_capacity: bool) {
        // The receive loop is synchronous; a second async worker must keep
        // polling the caller-owned spawn wrappers while this one receives.
        let runtime = RuntimeBuilder::multi_thread()
            .worker_threads(2)
            .blocking_threads(1, 1)
            .build()
            .expect("queued admission runtime");
        runtime.block_on(async move {
            let cx = Cx::current().expect("caller runtime context");
            let blocker_control = Arc::new(NonQuiescentLegacyControl::default());
            let _release = ReleaseModernReturningBlocker(Arc::clone(&blocker_control));
            let blocker_wait = Arc::clone(&blocker_control);
            let mut blocker = cx
                .spawn_blocking(move |_| blocker_wait.wait_until_released())
                .expect("the only blocking worker is admitted");
            assert!(blocker_control.wait_for_started(Duration::from_secs(2)));
            let server = Server::new("modern-returning-queued-capacity", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("modern policy")
                .build();
            let active = Arc::clone(&server.active_requests);
            let sent = Arc::new(Mutex::new(Vec::new()));
            let sent_for_receive = Arc::clone(&sent);
            let queued = MAX_DISPATCH_QUEUE_DEPTH - usize::from(!at_capacity);
            let mut phase = 0;
            server
                .run_transport_returning_with_cx(
                    &cx,
                    ModernReturningCallbackTransport {
                        receive: move |_: &Cx| {
                            let current = phase;
                            phase += 1;
                            if current < queued {
                                return Ok(modern_subscriptions_listen_request(
                                    10_000 + current as i64,
                                ));
                            }
                            if current == queued {
                                return Ok(modern_discovery_request(11_000));
                            }
                            let owners = active
                                .lock()
                                .unwrap_or_else(std::sync::PoisonError::into_inner);
                            assert_eq!(owners.len(), queued);
                            let messages = sent_for_receive
                                .lock()
                                .unwrap_or_else(std::sync::PoisonError::into_inner);
                            let [JsonRpcMessage::Response(response)] = messages.as_slice() else {
                                panic!("queued listens must not execute before the worker is free");
                            };
                            assert_eq!(response.id, Some(11_000_i64.into()));
                            if at_capacity {
                                assert_eq!(
                                    response.error.as_ref().unwrap().code.as_i32(),
                                    Some(RESOURCE_EXHAUSTED_ERROR_CODE)
                                );
                            } else {
                                assert!(response.error.is_none());
                            }
                            for owner in owners.values() {
                                owner.cancellation.cancel();
                            }
                            drop(owners);
                            blocker_control.release();
                            Err(TransportError::Closed)
                        },
                        sent,
                    },
                )
                .expect("queued owners retire after their blocker is released");
            blocker.join(&cx).await.expect("blocker retires");
        });
    }

    #[test]
    fn modern_returning_loop_opening_listen_accepts_queued_peer_cancellation() {
        modern_returning_loop_queued_cancellation_case(true);
    }

    #[test]
    fn modern_returning_loop_opening_listen_ignores_unrelated_queued_cancellation() {
        modern_returning_loop_queued_cancellation_case(false);
    }

    fn modern_returning_loop_queued_cancellation_case(matching: bool) {
        struct ObserveSubscriptionStart(Arc<BoundedTestSignal>);

        impl Middleware for ObserveSubscriptionStart {
            fn on_request(
                &self,
                _ctx: &McpContext,
                request: &JsonRpcRequest,
            ) -> McpResult<MiddlewareDecision> {
                if request.method == SUBSCRIPTIONS_LISTEN {
                    self.0.raise();
                }
                Ok(MiddlewareDecision::Continue)
            }
        }

        let runtime = RuntimeBuilder::multi_thread()
            .worker_threads(2)
            .blocking_threads(1, 1)
            .build()
            .expect("queued cancellation runtime");
        runtime.block_on(async move {
            let cx = Cx::current().expect("caller runtime context");
            let blocker_control = Arc::new(NonQuiescentLegacyControl::default());
            let _release = ReleaseModernReturningBlocker(Arc::clone(&blocker_control));
            let blocker_wait = Arc::clone(&blocker_control);
            let mut blocker = cx
                .spawn_blocking(move |_| blocker_wait.wait_until_released())
                .expect("the only blocking worker is admitted");
            assert!(blocker_control.wait_for_started(Duration::from_secs(2)));
            let started = Arc::new(BoundedTestSignal::default());
            let started_for_receive = Arc::clone(&started);
            let server = Server::new("modern-returning-opening-listen-cancellation", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("modern policy")
                .middleware(ObserveSubscriptionStart(Arc::clone(&started)))
                .build();
            let active = Arc::clone(&server.active_requests);
            let active_for_receive = Arc::clone(&active);
            let mut phase = 0;
            server
                .run_transport_returning_with_cx(
                    &cx,
                    ModernReturningCallbackTransport {
                        receive: move |_: &Cx| {
                            let current = phase;
                            phase += 1;
                            match current {
                                0 => Ok(modern_subscriptions_listen_request(12_000)),
                                1 => Ok(modern_cancelled_notification(if matching {
                                    12_000
                                } else {
                                    12_001
                                })),
                                _ => {
                                    let owners = active_for_receive
                                        .lock()
                                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                                    assert_eq!(owners.len(), 1);
                                    let owner = owners.values().next().unwrap();
                                    assert_eq!(
                                        owner.cancellation.is_cancel_requested(),
                                        matching,
                                        "the opening listen must bind its principal before spawn"
                                    );
                                    let completion = Arc::clone(&owner.completion);
                                    drop(owners);
                                    blocker_control.release();
                                    if matching {
                                        assert!(completion.wait_timeout(Duration::from_secs(2)));
                                    } else {
                                        assert!(started_for_receive.wait(Duration::from_secs(2)));
                                    }
                                    Err(TransportError::Closed)
                                }
                            }
                        },
                        sent: Arc::new(Mutex::new(Vec::new())),
                    },
                )
                .expect("queued cancellation must preserve a clean shutdown");
            blocker.join(&cx).await.expect("blocker retires");
            assert_eq!(started.wait(Duration::ZERO), !matching);
            assert!(active.lock().unwrap().is_empty());
        });
    }

    #[test]
    fn modern_returning_loop_valid_peer_response_preserves_next_request() {
        modern_returning_loop_peer_response_case(false);
    }

    #[test]
    fn modern_returning_loop_invalid_peer_response_stops_before_next_request() {
        modern_returning_loop_peer_response_case(true);
    }

    fn modern_returning_loop_peer_response_case(invalid_version: bool) {
        let mut response = JsonRpcResponse::success(9900_i64.into(), serde_json::json!({}));
        if invalid_version {
            response.jsonrpc = "1.0".into();
        }
        let received = Arc::new(AtomicUsize::new(0));
        let sent = Arc::new(Mutex::new(Vec::new()));
        let closed = Arc::new(AtomicUsize::new(0));
        let result = Server::new("modern-returning-response-validation", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("the modern profile must be available")
            .build()
            .run_transport_returning_with_cx(
                &Cx::for_testing(),
                ModernReturningScriptTransport {
                    steps: std::collections::VecDeque::from([
                        Ok(modern_discovery_request(9901)),
                        Ok(JsonRpcMessage::Response(response)),
                        Ok(modern_discovery_request(9902)),
                        Err(TransportError::Closed),
                    ]),
                    received: Arc::clone(&received),
                    sent: Arc::clone(&sent),
                    closed: Arc::clone(&closed),
                },
            );
        let messages = sent
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert_eq!(closed.load(Ordering::Acquire), 1);
        assert!(matches!(
            messages.first(),
            Some(JsonRpcMessage::Response(response))
                if response.id == Some(9901_i64.into()) && response.error.is_none()
        ));
        if invalid_version {
            let error = result.expect_err("an invalid peer response must terminate ingress");
            assert_eq!(error.data.as_ref().unwrap()["stage"], "receive");
            assert_eq!(error.data.as_ref().unwrap()["kind"], "invalid_response");
            assert_eq!(received.load(Ordering::Acquire), 2);
            assert_eq!(messages.len(), 1, "no later request may be dispatched");
        } else {
            result.expect("a valid unmatched response must not poison the connection");
            assert_eq!(received.load(Ordering::Acquire), 4);
            assert_eq!(messages.len(), 2);
            assert!(matches!(
                messages.last(),
                Some(JsonRpcMessage::Response(response))
                    if response.id == Some(9902_i64.into()) && response.error.is_none()
            ));
        }
    }

    #[test]
    fn modern_returning_loop_complete_json_error_replies_and_continues() {
        modern_returning_loop_codec_boundary_case(false);
    }

    #[test]
    fn modern_returning_loop_unbounded_frame_error_stops_without_reply() {
        modern_returning_loop_codec_boundary_case(true);
    }

    fn modern_returning_loop_codec_boundary_case(lost_frame_boundary: bool) {
        let codec_error = if lost_frame_boundary {
            fastmcp_transport::CodecError::MessageTooLarge(1)
        } else {
            fastmcp_transport::CodecError::Json(
                serde_json::from_str::<serde_json::Value>("{")
                    .expect_err("the complete frame contains malformed JSON"),
            )
        };
        let received = Arc::new(AtomicUsize::new(0));
        let sent = Arc::new(Mutex::new(Vec::new()));
        let closed = Arc::new(AtomicUsize::new(0));
        let result = Server::new("modern-returning-codec-boundary", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("the modern profile must be available")
            .build()
            .run_transport_returning_with_cx(
                &Cx::for_testing(),
                ModernReturningScriptTransport {
                    steps: std::collections::VecDeque::from([
                        Err(TransportError::Codec(codec_error)),
                        Ok(modern_discovery_request(9911)),
                        Err(TransportError::Closed),
                    ]),
                    received: Arc::clone(&received),
                    sent: Arc::clone(&sent),
                    closed: Arc::clone(&closed),
                },
            );
        let messages = sent
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert_eq!(closed.load(Ordering::Acquire), 1);
        if lost_frame_boundary {
            let error = result.expect_err("a lost framing boundary must terminate ingress");
            assert_eq!(error.data.as_ref().unwrap()["stage"], "receive");
            assert_eq!(error.data.as_ref().unwrap()["kind"], "codec");
            assert_eq!(received.load(Ordering::Acquire), 1);
            assert!(
                messages.is_empty(),
                "an unbounded frame must receive no reply"
            );
        } else {
            result.expect("a complete malformed JSON frame must permit the next request");
            assert_eq!(received.load(Ordering::Acquire), 3);
            let [
                JsonRpcMessage::Response(parse_error),
                JsonRpcMessage::Response(discovery),
            ] = messages.as_slice()
            else {
                panic!("expected one parse error followed by one discovery response");
            };
            assert!(parse_error.id.is_none());
            assert_eq!(
                parse_error.error.as_ref().unwrap().code.as_i32(),
                Some(-32700)
            );
            assert!(parse_error.error.as_ref().unwrap().data.is_none());
            assert_eq!(discovery.id, Some(9911_i64.into()));
            assert!(discovery.error.is_none());
        }
    }

    // Exact-2024 era: negotiates the connection with a legacy initialize.
    #[cfg(feature = "legacy-2024-11-05")]
    #[test]
    fn returning_loop_correlates_invalid_request_only_when_codec_proves_unique_id() {
        use std::collections::VecDeque;

        let invalid = fastmcp_transport::Codec::new()
            .decode_complete_message(br#"{"jsonrpc":"2.1","method":"tools/list","id":"safe-id"}"#)
            .expect_err("wrong JSON-RPC version must be invalid");
        // A malformed OPENING frame is a fatal era-security rejection under
        // Auto, so the correlation contract is probed on an already
        // negotiated connection.
        let steps = Arc::new(Mutex::new(VecDeque::from([
            Ok(exact_legacy_initialize_request(
                31,
                serde_json::json!("1.0.0"),
            )),
            Ok(JsonRpcMessage::Request(JsonRpcRequest::notification(
                "notifications/initialized",
                None,
            ))),
            Err(TransportError::Codec(invalid)),
            Err(TransportError::Closed),
        ])));
        let sent = Arc::new(Mutex::new(Vec::<JsonRpcMessage>::new()));
        let receive_steps = Arc::clone(&steps);
        let sent_messages = Arc::clone(&sent);

        let cx = Cx::for_testing();
        Server::new("correlated-invalid-request-test", "1.0.0")
            .build()
            .run_loop_returning_with_dispatch_cx(
                &cx,
                &cx,
                move |_, _worker_failed| {
                    receive_steps
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .pop_front()
                        .unwrap_or(Err(TransportError::Closed))
                },
                move |_, message| {
                    sent_messages
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .push(message.clone());
                    Ok(())
                },
                Arc::new(|_| {}),
                None,
                "test",
            )
            .expect("clean transport closure after an invalid-request reply must succeed");

        let sent = sent
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        // The initialize response races worker shutdown and is incidental;
        // the contract is exactly one reply correlated to the proven id.
        let correlated: Vec<&JsonRpcResponse> = sent
            .iter()
            .filter_map(|message| match message {
                JsonRpcMessage::Response(response)
                    if response.id == Some(RequestId::String("safe-id".to_string())) =>
                {
                    Some(response)
                }
                _ => None,
            })
            .collect();
        let [response] = correlated.as_slice() else {
            panic!("expected exactly one response correlated to the proven unique id");
        };
        assert_eq!(
            response
                .error
                .as_ref()
                .and_then(|error| error.code.as_i32()),
            Some(i32::from(McpErrorCode::InvalidRequest))
        );
    }

    #[test]
    fn returning_loop_terminates_after_fatal_framing_error_without_logging_payload() {
        use std::sync::atomic::AtomicUsize;

        let receive_calls = Arc::new(AtomicUsize::new(0));
        let receive_count = Arc::clone(&receive_calls);
        let sent = Arc::new(AtomicUsize::new(0));
        let sent_count = Arc::clone(&sent);

        let cx = Cx::for_testing();
        let error = Server::new("fatal-framing-error-test", "1.0.0")
            .build()
            .run_loop_returning_with_dispatch_cx(
                &cx,
                &cx,
                move |_, _worker_failed| {
                    receive_count.fetch_add(1, Ordering::Relaxed);
                    Err(TransportError::Io(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "SECRET_FRAMING_CANARY\r\nforged-log-line",
                    )))
                },
                move |_, _| {
                    sent_count.fetch_add(1, Ordering::Relaxed);
                    Ok(())
                },
                Arc::new(|_| {}),
                None,
                "test",
            )
            .expect_err("fatal framing failure must propagate from the returning loop");

        assert_eq!(receive_calls.load(Ordering::Relaxed), 1);
        assert_eq!(sent.load(Ordering::Relaxed), 0);
        assert_eq!(error.code, McpErrorCode::InternalError);
        assert_eq!(
            error.data.as_ref().and_then(|data| data["kind"].as_str()),
            Some("pump_failure")
        );
        assert_eq!(
            classify_receive_error(&TransportError::Timeout),
            ReceiveErrorDisposition::Terminate
        );
        assert_eq!(
            classify_receive_error(&TransportError::ReceiveDeadlineExceeded),
            ReceiveErrorDisposition::Terminate
        );
        assert_eq!(
            classify_receive_error(&TransportError::ControlFrameTooLarge {
                size: 513,
                max: 512,
            }),
            ReceiveErrorDisposition::Terminate
        );
        assert_eq!(
            classify_receive_error(&TransportError::Codec(
                fastmcp_transport::CodecError::MessageTooLarge(42)
            )),
            ReceiveErrorDisposition::Terminate
        );
    }

    #[test]
    fn receive_pump_terminates_each_fatal_transport_failure_without_retrying() {
        use std::sync::atomic::AtomicUsize;

        for error in [
            TransportError::Timeout,
            TransportError::ReceiveDeadlineExceeded,
            TransportError::ControlFrameTooLarge {
                size: 513,
                max: 512,
            },
            TransportError::Codec(fastmcp_transport::CodecError::MessageTooLarge(42)),
        ] {
            let error_label = format!("{error:?}");
            let receive_calls = Arc::new(AtomicUsize::new(0));
            let receive_count = Arc::clone(&receive_calls);
            let sent = Arc::new(AtomicUsize::new(0));
            let sent_count = Arc::clone(&sent);
            let mut next_error = Some(error);

            let cx = Cx::for_testing();
            let exit_code = Arc::new(Server::new("fatal-receive-error-test", "1.0.0").build())
                .run_loop_pump_with_policy(
                    &cx,
                    &cx,
                    move |_, _worker_failed| {
                        receive_count.fetch_add(1, Ordering::Relaxed);
                        Err(next_error.take().unwrap_or(TransportError::Closed))
                    },
                    move |_, _| {
                        sent_count.fetch_add(1, Ordering::Relaxed);
                        Ok(())
                    },
                    Arc::new(|_| {}),
                    "test",
                    true,
                    None,
                    true,
                    true,
                    None,
                    None,
                    None,
                    PumpIoMode::Split,
                );

            assert_eq!(exit_code, 1, "fatal error must fail: {error_label}");
            assert_eq!(
                receive_calls.load(Ordering::Relaxed),
                1,
                "fatal error must not be retried: {error_label}"
            );
            assert_eq!(
                sent.load(Ordering::Relaxed),
                0,
                "fatal error must not emit a response: {error_label}"
            );
        }
    }

    #[test]
    fn lifespan_hooks_default_matches_new() {
        let default_hooks = LifespanHooks::default();
        let new_hooks = LifespanHooks::new();
        assert!(default_hooks.on_startup.is_none());
        assert!(default_hooks.on_shutdown.is_none());
        assert!(new_hooks.on_startup.is_none());
        assert!(new_hooks.on_shutdown.is_none());
    }

    #[test]
    fn request_completion_wait_resolves_on_concurrent_done() {
        use std::sync::Arc;
        use std::thread;

        let rc = Arc::new(RequestCompletion::new());
        let rc_clone = rc.clone();

        let handle = thread::spawn(move || {
            thread::sleep(Duration::from_millis(20));
            rc_clone.mark_done();
        });

        // Should resolve within the timeout because the other thread marks done
        assert!(rc.wait_timeout(Duration::from_secs(2)));
        handle.join().unwrap();
    }

    #[test]
    fn active_request_stores_region_id() {
        let cx = Cx::for_testing();
        let expected_region = cx.region_id();
        let completion = Arc::new(RequestCompletion::new());
        let ar = ActiveRequest::new(cx, completion);
        assert_eq!(ar.region_id, expected_region);
    }

    #[test]
    fn transport_auth_binds_session_and_rejects_cross_principal_reuse() {
        #[derive(Debug)]
        struct EchoAuthProvider;

        impl AuthProvider for EchoAuthProvider {
            fn authenticate(
                &self,
                _ctx: &McpContext,
                request: AuthRequest<'_>,
            ) -> McpResult<AuthContext> {
                let access = request
                    .access_token()
                    .ok_or_else(|| McpError::invalid_request("missing auth token"))?;
                let subject = fixed_test_subject_for_credential(&access.token)?;
                Ok(AuthContext::with_subject(subject))
            }
        }

        let server = Server::new("http-auth-test-server", "1.0.0")
            .auth_provider(EchoAuthProvider)
            .tool(HttpAuthEchoToolRuntime)
            .build();
        let mut session = Session::new(server.info.clone(), server.capabilities.clone());
        session.initialize(
            fastmcp_protocol::ClientInfo {
                name: "http-auth-test-client".to_string(),
                version: "1.0.0".to_string(),
            },
            fastmcp_protocol::ClientCapabilities::default(),
            "2024-11-05".to_string(),
        );

        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();

        let mut run_request = |id: i64, token: &str| {
            let authorization = format!("Bearer {token}");
            block_on(server.handle_request_internal(
                &Cx::for_testing(),
                &mut session,
                JsonRpcRequest::new(
                    "tools/call",
                    Some(serde_json::json!({
                        "name": "http_auth_echo_tool_runtime",
                        "arguments": {}
                    })),
                    id,
                ),
                &notification_sender,
                &request_sender,
                None,
                Some(&authorization),
            ))
            .map(|handled| handled.finalize_for_return(&mut session))
            .expect("tools/call must receive a JSON-RPC response")
        };

        for id in [1, 2] {
            let response = run_request(id, "alpha");
            let result = response.result.expect("bound principal should succeed");
            let tool_result: CallToolResult =
                serde_json::from_value(result).expect("parse tool result payload");
            assert!(matches!(
                tool_result.content.as_slice(),
                [LegacyContent::Text { text, .. }] if text == "principal-alpha"
            ));
        }

        let rejected = run_request(3, "beta");
        let error = rejected
            .error
            .expect("a different principal must not reuse session state");
        assert_eq!(
            error.code,
            i32::from(McpErrorCode::ResourceForbidden).into()
        );
        assert!(rejected.result.is_none());
    }

    #[test]
    fn dispatch_stateful_tool_calls_preserve_session_state_updates() {
        let server = Server::new("http-state-test-server", "1.0.0")
            .tool(HttpStatefulIncrementTool)
            .build();
        let mut session = Session::new(server.info.clone(), server.capabilities.clone());
        session.initialize(
            fastmcp_protocol::ClientInfo {
                name: "http-state-test-client".to_string(),
                version: "1.0.0".to_string(),
            },
            fastmcp_protocol::ClientCapabilities::default(),
            "2024-11-05".to_string(),
        );

        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();

        let mut run_request = |id: i64| {
            let json = block_on(server.dispatch_request(
                &Cx::for_testing(),
                &mut session,
                JsonRpcRequest::new(
                    "tools/call",
                    Some(serde_json::json!({
                        "name": "http_stateful_increment_tool",
                        "arguments": {}
                    })),
                    id,
                ),
                &notification_sender,
                &request_sender,
            ))
            .expect("tools/call must receive a JSON-RPC response");
            let result = json.result.expect("stateful request should succeed");
            let tool_result: CallToolResult =
                serde_json::from_value(result).expect("parse tool result payload");
            assert!(!tool_result.is_error, "stateful tool unexpectedly errored");
            match tool_result.content.as_slice() {
                [LegacyContent::Text { text, .. }] => text.clone(),
                other => panic!("expected single text tool result, got {other:?}"),
            }
        };

        assert_eq!(run_request(1), "Counter: 1");
        assert_eq!(run_request(2), "Counter: 2");
    }

    #[test]
    fn dispatch_exclusive_requests_expose_request_auth_to_middleware() {
        #[derive(Debug)]
        struct EchoAuthProvider;

        impl AuthProvider for EchoAuthProvider {
            fn authenticate(
                &self,
                _ctx: &McpContext,
                request: AuthRequest<'_>,
            ) -> McpResult<AuthContext> {
                let access = request
                    .access_token()
                    .ok_or_else(|| McpError::invalid_request("missing auth token"))?;
                let subject = fixed_test_subject_for_credential(&access.token)?;
                Ok(AuthContext::with_subject(subject))
            }
        }

        let seen = Arc::new(Mutex::new(Vec::new()));
        let middleware = CapturingAuthMiddleware {
            seen: Arc::clone(&seen),
        };
        let server = Server::new("http-middleware-auth-test-server", "1.0.0")
            .auth_provider(EchoAuthProvider)
            .middleware(middleware)
            .build();
        let mut session = Session::new(server.info.clone(), server.capabilities.clone());
        session.initialize(
            fastmcp_protocol::ClientInfo {
                name: "http-middleware-client".to_string(),
                version: "1.0.0".to_string(),
            },
            fastmcp_protocol::ClientCapabilities::default(),
            "2024-11-05".to_string(),
        );

        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();
        block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            JsonRpcRequest::new(
                "tools/list",
                Some(serde_json::json!({
                    "auth": "Bearer alpha"
                })),
                1_i64,
            ),
            &notification_sender,
            &request_sender,
        ))
        .expect("tools/list must receive a JSON-RPC response");

        let observed = seen
            .lock()
            .expect("captured auth middleware mutex should not be poisoned")
            .clone();
        assert_eq!(
            observed,
            vec![(
                "tools/list".to_string(),
                Some("principal-alpha".to_string())
            )]
        );
    }

    #[test]
    fn dispatch_read_only_requests_expose_request_auth_to_middleware() {
        #[derive(Debug)]
        struct EchoAuthProvider;

        impl AuthProvider for EchoAuthProvider {
            fn authenticate(
                &self,
                _ctx: &McpContext,
                request: AuthRequest<'_>,
            ) -> McpResult<AuthContext> {
                let access = request
                    .access_token()
                    .ok_or_else(|| McpError::invalid_request("missing auth token"))?;
                let subject = fixed_test_subject_for_credential(&access.token)?;
                Ok(AuthContext::with_subject(subject))
            }
        }

        let seen = Arc::new(Mutex::new(Vec::new()));
        let middleware = CapturingAuthMiddleware {
            seen: Arc::clone(&seen),
        };
        let server = Server::new("http-read-only-middleware-auth-test-server", "1.0.0")
            .auth_provider(EchoAuthProvider)
            .middleware(middleware)
            .tool(HttpCurrentAuthSubjectTool)
            .build();
        let mut session = Session::new(server.info.clone(), server.capabilities.clone());
        session.initialize(
            fastmcp_protocol::ClientInfo {
                name: "http-read-only-middleware-client".to_string(),
                version: "1.0.0".to_string(),
            },
            fastmcp_protocol::ClientCapabilities::default(),
            "2024-11-05".to_string(),
        );

        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();
        let json = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            JsonRpcRequest::new(
                "tools/call",
                Some(serde_json::json!({
                    "name": "http_current_auth_subject_tool",
                    "arguments": {},
                    "auth": "Bearer beta"
                })),
                1_i64,
            ),
            &notification_sender,
            &request_sender,
        ))
        .expect("tools/call must receive a JSON-RPC response");
        let result = json.result.expect("read-only auth request should succeed");
        let tool_result: CallToolResult =
            serde_json::from_value(result).expect("parse tool result payload");
        match tool_result.content.as_slice() {
            [LegacyContent::Text { text, .. }] => assert_eq!(text, "principal-beta"),
            other => panic!("expected single text tool result, got {other:?}"),
        }

        let observed = seen
            .lock()
            .expect("captured auth middleware mutex should not be poisoned")
            .clone();
        assert_eq!(
            observed,
            vec![("tools/call".to_string(), Some("principal-beta".to_string()))]
        );
    }

    #[test]
    fn dispatch_exclusive_middleware_cannot_replace_committed_request_auth() {
        let server = Server::new("http-exclusive-auth-override-test-server", "1.0.0")
            .middleware(OverridingAuthMiddleware {
                subject: "exclusive-override",
            })
            .tool(HttpCurrentAuthSubjectExclusiveTool)
            .build();
        let mut session = Session::new(server.info.clone(), server.capabilities.clone());
        session.initialize(
            fastmcp_protocol::ClientInfo {
                name: "http-exclusive-auth-override-client".to_string(),
                version: "1.0.0".to_string(),
            },
            fastmcp_protocol::ClientCapabilities::default(),
            "2024-11-05".to_string(),
        );

        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();
        let json = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            JsonRpcRequest::new(
                "tools/call",
                Some(serde_json::json!({
                    "name": "http_current_auth_subject_exclusive_tool",
                    "arguments": {}
                })),
                1_i64,
            ),
            &notification_sender,
            &request_sender,
        ))
        .expect("tools/call must receive a JSON-RPC response");
        let result = json
            .result
            .expect("exclusive request should succeed with committed anonymous auth");
        let tool_result: CallToolResult =
            serde_json::from_value(result).expect("parse tool result payload");
        match tool_result.content.as_slice() {
            [LegacyContent::Text { text, .. }] => assert_eq!(text, "anonymous"),
            other => panic!("expected single text tool result, got {other:?}"),
        }
    }

    #[test]
    fn dispatch_read_only_middleware_cannot_replace_committed_request_auth() {
        let server = Server::new("http-read-only-auth-override-test-server", "1.0.0")
            .middleware(OverridingAuthMiddleware {
                subject: "read-only-override",
            })
            .tool(HttpCurrentAuthSubjectTool)
            .build();
        let mut session = Session::new(server.info.clone(), server.capabilities.clone());
        session.initialize(
            fastmcp_protocol::ClientInfo {
                name: "http-read-only-auth-override-client".to_string(),
                version: "1.0.0".to_string(),
            },
            fastmcp_protocol::ClientCapabilities::default(),
            "2024-11-05".to_string(),
        );

        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();
        let json = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            JsonRpcRequest::new(
                "tools/call",
                Some(serde_json::json!({
                    "name": "http_current_auth_subject_tool",
                    "arguments": {}
                })),
                1_i64,
            ),
            &notification_sender,
            &request_sender,
        ))
        .expect("tools/call must receive a JSON-RPC response");
        let result = json
            .result
            .expect("read-only request should succeed with committed anonymous auth");
        let tool_result: CallToolResult =
            serde_json::from_value(result).expect("parse tool result payload");
        match tool_result.content.as_slice() {
            [LegacyContent::Text { text, .. }] => assert_eq!(text, "anonymous"),
            other => panic!("expected single text tool result, got {other:?}"),
        }
    }

    #[test]
    fn dispatch_exclusive_auth_failures_flow_through_middleware_error_rewriting() {
        let server = Server::new("http-exclusive-auth-error-test-server", "1.0.0")
            .auth_provider(AlwaysFailAuthProvider)
            .middleware(RewritingErrorMiddleware)
            .build();
        let mut session = Session::new(server.info.clone(), server.capabilities.clone());
        session.initialize(
            fastmcp_protocol::ClientInfo {
                name: "http-exclusive-auth-error-client".to_string(),
                version: "1.0.0".to_string(),
            },
            fastmcp_protocol::ClientCapabilities::default(),
            "2024-11-05".to_string(),
        );

        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();
        let json = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            JsonRpcRequest::new(
                "tools/list",
                Some(serde_json::json!({
                    "auth": "Bearer nope"
                })),
                1_i64,
            ),
            &notification_sender,
            &request_sender,
        ))
        .expect("tools/list must receive a JSON-RPC response");
        let error = json
            .error
            .expect("auth failure should return JSON-RPC error");
        assert_eq!(error.message, "rewritten: Authentication failed");
    }

    #[test]
    fn dispatch_read_only_auth_failures_flow_through_middleware_error_rewriting() {
        let server = Server::new("http-read-only-auth-error-test-server", "1.0.0")
            .auth_provider(AlwaysFailAuthProvider)
            .middleware(RewritingErrorMiddleware)
            .tool(HttpCurrentAuthSubjectTool)
            .build();
        let mut session = Session::new(server.info.clone(), server.capabilities.clone());
        session.initialize(
            fastmcp_protocol::ClientInfo {
                name: "http-read-only-auth-error-client".to_string(),
                version: "1.0.0".to_string(),
            },
            fastmcp_protocol::ClientCapabilities::default(),
            "2024-11-05".to_string(),
        );

        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();
        let json = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            JsonRpcRequest::new(
                "tools/call",
                Some(serde_json::json!({
                    "name": "http_current_auth_subject_tool",
                    "arguments": {},
                    "auth": "Bearer nope"
                })),
                1_i64,
            ),
            &notification_sender,
            &request_sender,
        ))
        .expect("tools/call must receive a JSON-RPC response");
        let error = json
            .error
            .expect("auth failure should return JSON-RPC error");
        assert_eq!(error.message, "rewritten: Authentication failed");
    }

    #[test]
    fn auth_provider_error_payload_is_sanitized_before_middleware_and_wire() {
        const CANARY: &str = "AUTH-PROVIDER-RAW-CREDENTIAL-CANARY";

        #[derive(Debug)]
        struct LeakingAuthProvider;

        impl AuthProvider for LeakingAuthProvider {
            fn authenticate(
                &self,
                _ctx: &McpContext,
                _request: AuthRequest<'_>,
            ) -> McpResult<AuthContext> {
                Err(McpError::with_data(
                    McpErrorCode::ResourceForbidden,
                    format!("denied bearer {CANARY}"),
                    serde_json::json!({"raw_token": CANARY}),
                ))
            }
        }

        #[derive(Debug, Clone)]
        struct CapturingErrorMiddleware {
            seen: Arc<Mutex<Vec<McpError>>>,
        }

        impl Middleware for CapturingErrorMiddleware {
            fn on_error(
                &self,
                _ctx: &McpContext,
                _request: &JsonRpcRequest,
                error: McpError,
            ) -> McpError {
                self.seen
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .push(error.clone());
                error
            }
        }

        let seen = Arc::new(Mutex::new(Vec::new()));
        let server = Server::new("auth-error-sanitization-test", "1.0.0")
            .auth_provider(LeakingAuthProvider)
            .middleware(CapturingErrorMiddleware {
                seen: Arc::clone(&seen),
            })
            .build();
        let mut session = Session::new(server.info.clone(), server.capabilities.clone());
        session.initialize(
            fastmcp_protocol::ClientInfo {
                name: "auth-error-sanitization-client".to_string(),
                version: "1.0.0".to_string(),
            },
            fastmcp_protocol::ClientCapabilities::default(),
            "2024-11-05".to_string(),
        );

        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();
        let response = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            JsonRpcRequest::new(
                "tools/list",
                Some(serde_json::json!({"authorization": "Bearer peer-token"})),
                1_i64,
            ),
            &notification_sender,
            &request_sender,
        ))
        .expect("tools/list must receive a JSON-RPC response");
        let wire = serde_json::to_string(&response).expect("JSON-RPC response serializes");
        assert!(!wire.contains(CANARY));
        let response: JsonRpcResponse = serde_json::from_str(&wire).expect("JSON-RPC response");
        let error = response.error.expect("authentication must fail");
        assert_eq!(error.message, "Authentication failed");
        assert!(error.data.is_none());

        let seen = seen
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert_eq!(seen.len(), 1);
        assert_eq!(seen[0].message, "Authentication failed");
        assert!(seen[0].data.is_none());
        assert!(!format!("{:?}", seen[0]).contains(CANARY));
    }

    #[test]
    fn router_tools_call_injects_explicit_request_auth() {
        let server = Server::new("router-auth-test-server", "1.0.0")
            .tool(HttpCurrentAuthSubjectTool)
            .build();
        let state = SessionState::new();
        let request_ctx = McpContext::with_state(Cx::for_testing(), 41, state.clone())
            .with_auth(AuthContext::with_subject("alpha"));
        let result = block_on(server.router.handle_tools_call(
            &request_ctx,
            CallToolParams {
                name: "http_current_auth_subject_tool".to_string(),
                arguments: Some(serde_json::json!({})),
                meta: None,
            },
            state,
            None,
            None,
        ))
        .expect("tool call should succeed");

        match result.content.as_slice() {
            [LegacyContent::Text { text, .. }] => assert_eq!(text, "alpha"),
            other => panic!("expected single text tool result, got {other:?}"),
        }
    }

    #[test]
    fn request_cost_accounting_flows_through_auth_middleware_and_handler() {
        type Observation = (&'static str, Option<u64>);

        #[derive(Debug, Clone)]
        struct ChargingAuth {
            seen: Arc<Mutex<Vec<Observation>>>,
        }

        impl AuthProvider for ChargingAuth {
            fn authenticate(
                &self,
                ctx: &McpContext,
                _request: AuthRequest<'_>,
            ) -> McpResult<AuthContext> {
                ctx.consume_cost(1)?;
                self.seen
                    .lock()
                    .expect("cost observation mutex poisoned")
                    .push(("auth", ctx.budget().cost_quota));
                Ok(AuthContext::anonymous())
            }
        }

        #[derive(Debug, Clone)]
        struct ChargingMiddleware {
            seen: Arc<Mutex<Vec<Observation>>>,
        }

        impl Middleware for ChargingMiddleware {
            fn on_request(
                &self,
                ctx: &McpContext,
                _request: &JsonRpcRequest,
            ) -> McpResult<MiddlewareDecision> {
                ctx.consume_cost(1)?;
                self.seen
                    .lock()
                    .expect("cost observation mutex poisoned")
                    .push(("middleware", ctx.budget().cost_quota));
                Ok(MiddlewareDecision::Continue)
            }
        }

        #[derive(Debug, Clone)]
        struct ChargingTool {
            seen: Arc<Mutex<Vec<Observation>>>,
        }

        impl ToolHandler for ChargingTool {
            fn definition(&self) -> Tool {
                Tool {
                    name: "charging_tool".to_string(),
                    description: Some("Charges the shared request cost budget".to_string()),
                    input_schema: serde_json::json!({"type": "object"}),
                    output_schema: None,
                    icon: None,
                    version: None,
                    tags: Vec::new(),
                    annotations: None,
                }
            }

            fn call(&self, ctx: &McpContext, _args: serde_json::Value) -> McpResult<Vec<Content>> {
                ctx.consume_cost(1)?;
                self.seen
                    .lock()
                    .expect("cost observation mutex poisoned")
                    .push(("handler", ctx.budget().cost_quota));
                Ok(vec![Content::text("charged")])
            }
        }

        let seen = Arc::new(Mutex::new(Vec::new()));
        let server = Server::new("request-cost-accounting-test", "1.0.0")
            .auth_provider(ChargingAuth {
                seen: Arc::clone(&seen),
            })
            .middleware(ChargingMiddleware {
                seen: Arc::clone(&seen),
            })
            .tool(ChargingTool {
                seen: Arc::clone(&seen),
            })
            .build();
        let mut session = initialized_test_session(&server);
        let cx = Cx::for_testing_with_budget(Budget::new().with_cost_quota(3));
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();
        let request = JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({
                "name": "charging_tool",
                "arguments": {}
            })),
            1,
        );

        let response = block_on(server.dispatch_request(
            &cx,
            &mut session,
            request,
            &notification_sender,
            &request_sender,
        ))
        .expect("request should produce a response");
        assert!(
            response.error.is_none(),
            "unexpected response: {response:?}"
        );
        assert_eq!(
            *seen.lock().expect("cost observation mutex poisoned"),
            vec![
                ("auth", Some(2)),
                ("middleware", Some(1)),
                ("handler", Some(0)),
            ]
        );
        assert_eq!(
            cx.budget().cost_quota,
            Some(3),
            "request accounting must not mutate the caller-owned ambient Cx"
        );

        let rejected_seen = Arc::new(Mutex::new(Vec::new()));
        let rejected_server = Server::new("request-cost-overrun-test", "1.0.0")
            .auth_provider(ChargingAuth {
                seen: Arc::clone(&rejected_seen),
            })
            .middleware(ChargingMiddleware {
                seen: Arc::clone(&rejected_seen),
            })
            .tool(ChargingTool {
                seen: Arc::clone(&rejected_seen),
            })
            .build();
        let mut rejected_session = initialized_test_session(&rejected_server);
        let rejected_cx = Cx::for_testing_with_budget(Budget::new().with_cost_quota(2));
        let rejected_response = block_on(rejected_server.dispatch_request(
            &rejected_cx,
            &mut rejected_session,
            JsonRpcRequest::new(
                "tools/call",
                Some(serde_json::json!({
                    "name": "charging_tool",
                    "arguments": {}
                })),
                2,
            ),
            &notification_sender,
            &request_sender,
        ))
        .expect("over-budget tool request should produce a response");
        assert!(rejected_response.result.is_none());
        assert_eq!(
            rejected_response
                .error
                .as_ref()
                .expect("budget refusal must be a JSON-RPC cancellation error")
                .code,
            i32::from(McpErrorCode::RequestCancelled).into()
        );
        assert_eq!(
            *rejected_seen
                .lock()
                .expect("cost observation mutex poisoned"),
            vec![("auth", Some(1)), ("middleware", Some(0))],
            "the N+1 handler debit must fail before handler effects"
        );
    }

    #[test]
    fn failed_authentication_cannot_publish_a_tentative_identity() {
        #[derive(Debug, Clone, Copy)]
        struct MutatingFailAuth;

        impl AuthProvider for MutatingFailAuth {
            fn authenticate(
                &self,
                ctx: &McpContext,
                _request: AuthRequest<'_>,
            ) -> McpResult<AuthContext> {
                ctx.set_auth(AuthContext::with_subject("tentative-secret-identity"));
                Err(McpError::invalid_request("authentication rejected"))
            }
        }

        #[derive(Debug, Clone)]
        struct CaptureAuthOnError {
            seen: Arc<Mutex<Vec<Option<String>>>>,
        }

        impl Middleware for CaptureAuthOnError {
            fn on_error(
                &self,
                ctx: &McpContext,
                _request: &JsonRpcRequest,
                error: McpError,
            ) -> McpError {
                self.seen
                    .lock()
                    .expect("auth error observation mutex poisoned")
                    .push(ctx.auth().and_then(|auth| auth.subject));
                error
            }
        }

        let seen = Arc::new(Mutex::new(Vec::new()));
        let server = Server::new("transactional-auth-test", "1.0.0")
            .auth_provider(MutatingFailAuth)
            .middleware(CaptureAuthOnError {
                seen: Arc::clone(&seen),
            })
            .build();
        let mut session = initialized_test_session(&server);
        let response = dispatch_test_request(&server, &mut session, "tools/list");

        assert!(response.error.is_some());
        assert_eq!(
            *seen.lock().expect("auth error observation mutex poisoned"),
            vec![None],
            "failed provider identity must remain isolated from error middleware"
        );
    }

    #[test]
    fn zero_cost_quota_allows_a_zero_cost_request() {
        let server = Server::new("zero-cost-request-test", "1.0.0")
            .tool(HttpCurrentAuthSubjectTool)
            .build();
        let mut session = initialized_test_session(&server);
        let cx = Cx::for_testing_with_budget(Budget::new().with_cost_quota(0));
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();
        let response = block_on(server.dispatch_request(
            &cx,
            &mut session,
            JsonRpcRequest::new(
                "tools/call",
                Some(serde_json::json!({
                    "name": "http_current_auth_subject_tool",
                    "arguments": {}
                })),
                1,
            ),
            &notification_sender,
            &request_sender,
        ))
        .expect("zero-cost request should produce a response");

        assert!(
            response.error.is_none(),
            "unexpected response: {response:?}"
        );
        assert!(response.result.is_some());
    }

    #[test]
    fn production_dispatch_wires_router_backed_nested_tool_calls() {
        #[derive(Debug, Clone, Copy)]
        struct InnerTool;

        impl ToolHandler for InnerTool {
            fn definition(&self) -> Tool {
                Tool {
                    name: "inner_tool".to_string(),
                    description: Some("Nested dispatch target".to_string()),
                    input_schema: serde_json::json!({"type": "object"}),
                    output_schema: None,
                    icon: None,
                    version: None,
                    tags: Vec::new(),
                    annotations: None,
                }
            }

            fn call(&self, _ctx: &McpContext, _args: serde_json::Value) -> McpResult<Vec<Content>> {
                Ok(vec![Content::text("inner-result")])
            }
        }

        #[derive(Debug, Clone, Copy)]
        struct OuterTool;

        impl ToolHandler for OuterTool {
            fn definition(&self) -> Tool {
                Tool {
                    name: "outer_tool".to_string(),
                    description: Some("Calls another registered tool".to_string()),
                    input_schema: serde_json::json!({"type": "object"}),
                    output_schema: None,
                    icon: None,
                    version: None,
                    tags: Vec::new(),
                    annotations: None,
                }
            }

            fn call(&self, _ctx: &McpContext, _args: serde_json::Value) -> McpResult<Vec<Content>> {
                Err(McpError::internal_error(
                    "outer_tool requires async dispatch",
                ))
            }

            fn call_async<'a>(
                &'a self,
                ctx: &'a McpContext,
                _args: serde_json::Value,
            ) -> BoxFuture<'a, fastmcp_core::McpOutcome<Vec<Content>>> {
                Box::pin(async move {
                    match ctx.call_tool("inner_tool", serde_json::json!({})).await {
                        Ok(result) => {
                            let text = result.first_text().unwrap_or("missing nested text");
                            asupersync::Outcome::Ok(vec![Content::text(text)])
                        }
                        Err(error) => asupersync::Outcome::Err(error),
                    }
                })
            }
        }

        let server = Server::new("nested-production-dispatch-test", "1.0.0")
            .tool(InnerTool)
            .tool(OuterTool)
            .build();
        let mut session = initialized_test_session(&server);
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();
        let response = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            JsonRpcRequest::new(
                "tools/call",
                Some(serde_json::json!({
                    "name": "outer_tool",
                    "arguments": {}
                })),
                1_i64,
            ),
            &notification_sender,
            &request_sender,
        ))
        .expect("nested tool request should produce a response");
        let result: CallToolResult = serde_json::from_value(
            response
                .result
                .expect("top-level tool should complete through nested router dispatch"),
        )
        .expect("decode nested tool result");

        match result.content.as_slice() {
            [LegacyContent::Text { text, .. }] => assert_eq!(text, "inner-result"),
            other => panic!("expected nested tool text result, got {other:?}"),
        }
    }

    #[test]
    fn escaped_request_context_is_revoked_and_does_not_retain_server_router() {
        #[derive(Clone)]
        struct CaptureContextTool {
            captured: Arc<Mutex<Option<McpContext>>>,
        }

        impl ToolHandler for CaptureContextTool {
            fn definition(&self) -> Tool {
                Tool {
                    name: "capture_context".to_string(),
                    description: Some(
                        "Captures a request context for revocation testing".to_string(),
                    ),
                    input_schema: serde_json::json!({"type": "object"}),
                    output_schema: None,
                    icon: None,
                    version: None,
                    tags: Vec::new(),
                    annotations: None,
                }
            }

            fn call(&self, ctx: &McpContext, _args: serde_json::Value) -> McpResult<Vec<Content>> {
                *self
                    .captured
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(ctx.clone());
                Ok(vec![Content::text("captured")])
            }
        }

        let captured = Arc::new(Mutex::new(None));
        let server = Server::new("request-lease-test", "1.0.0")
            .tool(CaptureContextTool {
                captured: Arc::clone(&captured),
            })
            .build();
        let mut session = initialized_test_session(&server);
        let notification_sender: NotificationSender = Arc::new(|_| {});
        let request_sender = test_request_sender();
        let response = block_on(server.dispatch_request(
            &Cx::for_testing(),
            &mut session,
            JsonRpcRequest::new(
                "tools/call",
                Some(serde_json::json!({
                    "name": "capture_context",
                    "arguments": {}
                })),
                1_i64,
            ),
            &notification_sender,
            &request_sender,
        ))
        .expect("capture request should produce a response");
        assert!(
            response.error.is_none(),
            "unexpected response: {response:?}"
        );

        let escaped = captured
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .take()
            .expect("handler should capture its context");
        let error = block_on(escaped.call_tool("capture_context", serde_json::json!({})))
            .expect_err("nested authority must close when dispatch returns");
        assert_eq!(error.code, McpErrorCode::RequestCancelled);

        let router = server.into_router();
        assert!(
            router
                .tools()
                .iter()
                .any(|tool| tool.name == "capture_context")
        );
    }

    #[test]
    fn http_bind_rejects_an_invalid_address_without_running_lifecycle_hooks() {
        let startup_called = Arc::new(AtomicBool::new(false));
        let shutdown_called = Arc::new(AtomicBool::new(false));
        let startup_observer = Arc::clone(&startup_called);
        let shutdown_observer = Arc::clone(&shutdown_called);

        let cx = Cx::for_testing();
        let result = block_on(
            Server::new("http-bind-test", "1.0.0")
                .on_startup(move || {
                    startup_observer.store(true, Ordering::SeqCst);
                    Ok::<(), std::io::Error>(())
                })
                .on_shutdown(move || shutdown_observer.store(true, Ordering::SeqCst))
                .build()
                .bind_http(&cx, "not-a-bindable-socket-address"),
        );
        let Err(error) = result else {
            panic!("an invalid bind address must be rejected by the live listener");
        };

        assert!(!startup_called.load(Ordering::SeqCst));
        assert!(!shutdown_called.load(Ordering::SeqCst));
        assert!(
            error.message.contains("HTTP listener bind failed"),
            "the bind failure must report the live listener boundary: {error:?}"
        );
    }

    #[test]
    fn final_subscription_acknowledges_filters_tags_and_releases_request_owned_state() {
        let server = Server::new("final-subscription-stream-test", "1.0.0").build();
        let registry = Arc::clone(&server.final_subscriptions);
        let sent = Arc::new(Mutex::new(Vec::<JsonRpcRequest>::new()));
        let sent_for_sender = Arc::clone(&sent);
        let sender: NotificationSender = Arc::new(move |notification| {
            sent_for_sender
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(notification);
        });
        let subscription_id = RequestId::String("subscription-71".to_owned());
        let lease = registry
            .open(
                subscription_id.clone(),
                SubscriptionFilter {
                    tools_list_changed: Some(true),
                    resources_list_changed: Some(false),
                    ..SubscriptionFilter::default()
                },
                false,
                None,
                McpRequestCancellation::new(),
                None,
                sender,
            )
            .expect("final subscription should admit a bounded stream");

        let acknowledgement = sent
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .first()
            .cloned()
            .expect("acknowledgement must be the first stream frame");
        let ServerNotification::SubscriptionsAcknowledged(acknowledgement) =
            ServerNotification::decode(&acknowledgement)
                .expect("acknowledgement must use the exact final server union")
        else {
            panic!("first subscription frame must be an acknowledgement");
        };
        assert_eq!(acknowledgement.notifications.tools_list_changed, Some(true));
        assert_eq!(acknowledgement.notifications.resources_list_changed, None);
        let acknowledged_id: RequestId = serde_json::from_value(
            acknowledgement
                .meta
                .as_ref()
                .and_then(|metadata| metadata.get(FINAL_SUBSCRIPTION_ID_META_KEY))
                .cloned()
                .expect("acknowledgement must carry its subscription id"),
        )
        .expect("subscription id metadata must retain the JSON-RPC id");
        assert_eq!(acknowledged_id, subscription_id);

        assert_eq!(
            server
                .publish_subscription_notification(ServerNotification::ToolsListChanged(None))
                .expect("selected catalog event should publish"),
            1
        );
        assert_eq!(
            server
                .publish_subscription_notification(ServerNotification::ResourcesListChanged(None))
                .expect("unselected catalog event should be safely filtered"),
            0
        );
        let delivered = sent
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .get(1)
            .cloned()
            .expect("selected event must follow acknowledgement");
        let ServerNotification::ToolsListChanged(Some(delivered)) =
            ServerNotification::decode(&delivered)
                .expect("delivered event must use the exact final server union")
        else {
            panic!("selected event must remain a tools/list_changed notification");
        };
        let delivered_id: RequestId = serde_json::from_value(
            delivered
                .meta
                .as_ref()
                .and_then(|metadata| metadata.get(FINAL_SUBSCRIPTION_ID_META_KEY))
                .cloned()
                .expect("selected event must carry its subscription id"),
        )
        .expect("delivery metadata must retain the JSON-RPC id");
        assert_eq!(delivered_id, subscription_id);

        drop(lease);
        assert!(
            registry
                .inner
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .entries
                .is_empty(),
            "request completion or cancellation must release the subscription entry"
        );
    }

    #[cfg(all(feature = "proxy", feature = "tasks"))]
    #[test]
    fn subscription_filter_admission_matches_reordered_active_sets() {
        let task_a =
            fastmcp_protocol::FinalTaskId::parse("task-a").expect("bounded final task identifier");
        let task_b =
            fastmcp_protocol::FinalTaskId::parse("task-b").expect("bounded final task identifier");
        let mut expected = SubscriptionFilter {
            prompts_list_changed: Some(false),
            resource_subscriptions: Some(vec![
                "file:///subscriptions/a".to_owned(),
                "file:///subscriptions/b".to_owned(),
            ]),
            resources_list_changed: Some(false),
            tools_list_changed: Some(true),
            additional: BTreeMap::from([(
                "io.example/future-filter".to_owned(),
                serde_json::json!({"enabled": true}),
            )]),
        };
        set_task_subscription_ids(
            &mut expected,
            vec![task_a.clone(), task_b.clone(), task_a.clone()],
        )
        .expect("compose the requested Tasks selection");

        let mut acknowledged = SubscriptionFilter {
            resource_subscriptions: Some(vec![
                "file:///subscriptions/b".to_owned(),
                "file:///subscriptions/a".to_owned(),
            ]),
            tools_list_changed: Some(true),
            ..SubscriptionFilter::default()
        };
        set_task_subscription_ids(&mut acknowledged, vec![task_b, task_a])
            .expect("compose the reordered Tasks acknowledgement");

        assert!(
            subscription_filter_admission_matches(&expected, &acknowledged)
                .expect("equivalent active selections must be valid"),
            "resource and Tasks order, inactive booleans, and unknown filters must not narrow admission"
        );
    }

    #[cfg(all(feature = "proxy", feature = "tasks"))]
    #[test]
    fn subscription_filter_admission_rejects_one_missing_task_id() {
        let task_a =
            fastmcp_protocol::FinalTaskId::parse("task-a").expect("bounded final task identifier");
        let task_b =
            fastmcp_protocol::FinalTaskId::parse("task-b").expect("bounded final task identifier");
        let mut expected = SubscriptionFilter {
            resource_subscriptions: Some(vec![
                "file:///subscriptions/a".to_owned(),
                "file:///subscriptions/b".to_owned(),
            ]),
            tools_list_changed: Some(true),
            ..SubscriptionFilter::default()
        };
        set_task_subscription_ids(&mut expected, vec![task_a.clone(), task_b])
            .expect("compose the requested Tasks selection");

        let mut acknowledged = expected.clone();
        acknowledged
            .additional
            .remove(fastmcp_protocol::TASK_SUBSCRIPTION_IDS_KEY)
            .expect("the acknowledgement starts from the requested Tasks selection");
        set_task_subscription_ids(&mut acknowledged, vec![task_a])
            .expect("remove exactly one task from the acknowledgement");

        assert!(
            !subscription_filter_admission_matches(&expected, &acknowledged)
                .expect("well-formed narrowed Tasks selection must compare"),
            "changing only one requested task ID must remain a rejected narrowing"
        );
    }

    #[test]
    fn final_subscription_registry_isolates_duplicate_ids_by_http_body_owner() {
        let server = Server::new("modern-http-listen-key-test", "1.0.0").build();
        let registry = Arc::clone(&server.final_subscriptions);
        let sender: NotificationSender = Arc::new(|_| {});
        let first_cancellation = McpRequestCancellation::new();
        let second_cancellation = McpRequestCancellation::new();
        let first = registry
            .open(
                RequestId::Integer("873".to_owned()),
                SubscriptionFilter::default(),
                false,
                Some(873),
                first_cancellation.clone(),
                None,
                Arc::clone(&sender),
            )
            .expect("the first modern HTTP response body must admit");
        let second = registry
            .open(
                RequestId::Number(873),
                SubscriptionFilter::default(),
                false,
                Some(874),
                second_cancellation.clone(),
                None,
                sender,
            )
            .expect("a distinct response body may reuse the same JSON-RPC id");
        assert_eq!(
            registry
                .inner
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .entries
                .len(),
            2,
            "request-body ownership keeps equal JSON-RPC ids independent",
        );
        assert!(
            !registry.cancel_modern_http_owner(875),
            "a one-variable wrong response-body owner must not cancel either listen",
        );
        assert!(registry.cancel_modern_http_owner(873));
        assert!(
            first_cancellation.is_cancel_requested(),
            "the selected response body retains its own cancellation authority",
        );
        assert!(!second_cancellation.is_cancel_requested());
        drop(first);
        drop(second);
        assert!(
            registry
                .inner
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .modern_http_owners
                .is_empty(),
            "request completion must remove every response-body owner",
        );
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn final_tasks_runtime_publishes_only_to_acknowledged_exact_task_ids() {
        let application_notifications = Arc::new(Mutex::new(Vec::new()));
        let (server, _service) = final_tasks_test_server(Arc::clone(&application_notifications));
        let runtime = server
            .final_task_runtime()
            .expect("final Tasks runtime must remain public")
            .clone();
        let created = runtime
            .create_task_with_work(
                final_tasks_test_work_descriptor(),
                Some("queued".to_owned()),
            )
            .expect("task must be durable before subscription");
        let task_id = created.task.base().task_id.clone();
        let foreign_id =
            fastmcp_protocol::FinalTaskId::parse("foreign-task").expect("bounded foreign task id");

        let mut requested = SubscriptionFilter {
            tools_list_changed: Some(true),
            ..SubscriptionFilter::default()
        };
        set_task_subscription_ids(
            &mut requested,
            vec![task_id.clone(), foreign_id.clone(), task_id.clone()],
        )
        .expect("compose task IDs beside the core filter");
        let sent = Arc::new(Mutex::new(Vec::<JsonRpcRequest>::new()));
        let sent_for_sender = Arc::clone(&sent);
        let sender: NotificationSender = Arc::new(move |notification| {
            sent_for_sender
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(notification);
        });
        let subscription_id = RequestId::String("task-subscription-73".to_owned());
        let subscription_cancellation = McpRequestCancellation::new();
        let _lease = server
            .final_subscriptions
            .open(
                subscription_id.clone(),
                requested,
                true,
                None,
                subscription_cancellation.clone(),
                None,
                sender,
            )
            .expect("negotiated Tasks filter must open");

        let acknowledgement = sent
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .first()
            .cloned()
            .expect("acknowledgement must precede task events");
        let ServerNotification::SubscriptionsAcknowledged(acknowledgement) =
            ServerNotification::decode(&acknowledgement).expect("typed acknowledgement")
        else {
            panic!("first Tasks stream frame must be the core acknowledgement");
        };
        let accepted = task_subscription_ids(&acknowledgement.notifications)
            .expect("acknowledged Tasks fragment must validate")
            .expect("acknowledgement must retain taskIds");
        assert_eq!(accepted, [task_id.clone(), foreign_id]);
        assert_eq!(acknowledgement.notifications.tools_list_changed, Some(true));

        runtime
            .cancel_task(&task_id)
            .expect("unelected task cancellation commits terminal state");
        assert!(matches!(
            runtime
                .get_task(&task_id)
                .expect("terminally cancelled task remains readable")
                .task,
            fastmcp_protocol::Task::Cancelled(_)
        ));

        let delivered = sent
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .get(1)
            .cloned()
            .expect("matching task transition must follow acknowledgement");
        let delivered: FinalTaskStatusNotification = serde_json::from_value(
            serde_json::to_value(delivered).expect("notification request must serialize"),
        )
        .expect("notification must retain the exact Tasks wire type");
        assert_eq!(delivered.params.task.base().task_id, task_id);
        assert_eq!(
            delivered
                .params
                .meta
                .as_ref()
                .and_then(|metadata| metadata.get(FINAL_SUBSCRIPTION_ID_META_KEY)),
            Some(&serde_json::to_value(subscription_id).expect("subscription id"))
        );
        assert_eq!(
            sent.lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .len(),
            2,
            "one acknowledged stream receives exactly one matching task event"
        );
        subscription_cancellation.cancel();
        assert_eq!(
            server
                .final_subscriptions
                .publish_task(delivered)
                .expect("peer-cancelled task publication remains well-formed"),
            0,
            "a peer-cancelled token must prevent a Tasks callback before lease cleanup",
        );
        assert_eq!(
            sent.lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .len(),
            2,
            "peer-cancelled Tasks publication must leave delivery state unchanged",
        );
    }

    #[test]
    fn final_subscription_rejects_request_scoped_message_without_delivery() {
        use fastmcp_protocol::{FinalLogMessageParams, common_types::LoggingLevel};

        let server = Server::new("final-subscription-rejection-test", "1.0.0").build();
        let registry = Arc::clone(&server.final_subscriptions);
        let sent = Arc::new(Mutex::new(Vec::<JsonRpcRequest>::new()));
        let sent_for_sender = Arc::clone(&sent);
        let sender: NotificationSender = Arc::new(move |notification| {
            sent_for_sender
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(notification);
        });
        let _lease = registry
            .open(
                RequestId::Number(72),
                SubscriptionFilter {
                    tools_list_changed: Some(true),
                    ..SubscriptionFilter::default()
                },
                false,
                None,
                McpRequestCancellation::new(),
                None,
                sender,
            )
            .expect("selected catalog subscription should admit");
        assert_eq!(
            server
                .publish_subscription_notification(ServerNotification::ToolsListChanged(None))
                .expect("the selected event establishes the positive neighbor"),
            1
        );
        let sent_before_rejection = sent
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .len();

        let error = server
            .publish_subscription_notification(ServerNotification::Message(FinalLogMessageParams {
                level: LoggingLevel::Info,
                logger: None,
                data: serde_json::json!({"message": "request scoped"}),
                meta: None,
                additional: BTreeMap::new(),
            }))
            .expect_err("changing only the notification category must reject request-scoped logs");

        assert_eq!(error.code, McpErrorCode::InvalidParams);
        assert_eq!(
            sent.lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .len(),
            sent_before_rejection,
            "rejected request-scoped notifications must not mutate the stream"
        );
    }

    #[test]
    fn final_subscription_reentrant_ack_publication_flushes_after_acknowledgement() {
        let registry = Arc::new(FinalSubscriptionRegistry::default());
        let sent = Arc::new(Mutex::new(Vec::<JsonRpcRequest>::new()));
        let published = Arc::new(AtomicUsize::new(usize::MAX));
        let callback_count = Arc::new(AtomicUsize::new(0));
        let sender_registry = Arc::clone(&registry);
        let sender_sent = Arc::clone(&sent);
        let sender_published = Arc::clone(&published);
        let sender_callback_count = Arc::clone(&callback_count);
        let sender: NotificationSender = Arc::new(move |notification| {
            sender_sent
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(notification);
            if sender_callback_count.fetch_add(1, Ordering::AcqRel) == 0 {
                sender_published.store(
                    sender_registry
                        .publish(ServerNotification::ToolsListChanged(None))
                        .expect("reentrant catalogue publication must remain well-formed"),
                    Ordering::Release,
                );
            }
        });
        let lease = registry
            .open(
                RequestId::Number(721),
                SubscriptionFilter {
                    tools_list_changed: Some(true),
                    ..SubscriptionFilter::default()
                },
                false,
                None,
                McpRequestCancellation::new(),
                None,
                sender,
            )
            .expect("a reentrant acknowledgement publication must open");

        assert_eq!(published.load(Ordering::Acquire), 1);
        let sent = sent
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert_eq!(sent.len(), 2);
        assert!(matches!(
            ServerNotification::decode(&sent[0]),
            Ok(ServerNotification::SubscriptionsAcknowledged(_))
        ));
        assert!(matches!(
            ServerNotification::decode(&sent[1]),
            Ok(ServerNotification::ToolsListChanged(_))
        ));
        drop(sent);
        drop(lease);

        let negative_registry = Arc::new(FinalSubscriptionRegistry::default());
        let negative_sent = Arc::new(Mutex::new(Vec::<JsonRpcRequest>::new()));
        let negative_published = Arc::new(AtomicUsize::new(usize::MAX));
        let negative_callback_count = Arc::new(AtomicUsize::new(0));
        let negative_sender_registry = Arc::clone(&negative_registry);
        let negative_sender_sent = Arc::clone(&negative_sent);
        let negative_sender_published = Arc::clone(&negative_published);
        let negative_sender_callback_count = Arc::clone(&negative_callback_count);
        let negative_sender: NotificationSender = Arc::new(move |notification| {
            negative_sender_sent
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(notification);
            if negative_sender_callback_count.fetch_add(1, Ordering::AcqRel) == 0 {
                negative_sender_published.store(
                    negative_sender_registry
                        .publish(ServerNotification::ToolsListChanged(None))
                        .expect("wrong-filter publication must remain well-formed"),
                    Ordering::Release,
                );
            }
        });
        let _negative_lease = negative_registry
            .open(
                RequestId::Number(722),
                SubscriptionFilter {
                    prompts_list_changed: Some(true),
                    ..SubscriptionFilter::default()
                },
                false,
                None,
                McpRequestCancellation::new(),
                None,
                negative_sender,
            )
            .expect("the one-filter negative must still acknowledge");
        assert_eq!(negative_published.load(Ordering::Acquire), 0);
        assert_eq!(
            negative_sent
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .len(),
            1,
            "changing only the accepted filter must leave the stream at its acknowledgement",
        );
    }

    #[test]
    fn final_subscription_publishers_do_not_wait_for_held_ack_and_flush_fifo() {
        let registry = Arc::new(FinalSubscriptionRegistry::default());
        let gate = Arc::new((Mutex::new((false, false)), Condvar::new()));
        let sent = Arc::new(Mutex::new(Vec::<JsonRpcRequest>::new()));
        let sender_gate = Arc::clone(&gate);
        let sender_sent = Arc::clone(&sent);
        let callback_count = Arc::new(AtomicUsize::new(0));
        let sender_callback_count = Arc::clone(&callback_count);
        let sender: NotificationSender = Arc::new(move |notification| {
            sender_sent
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(notification);
            if sender_callback_count.fetch_add(1, Ordering::AcqRel) == 0 {
                let (lock, ready) = &*sender_gate;
                let mut state = lock
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
                state.0 = true;
                ready.notify_all();
                while !state.1 {
                    state = ready
                        .wait(state)
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                }
            }
        });
        let opener_registry = Arc::clone(&registry);
        let opener = thread::spawn(move || {
            opener_registry.open(
                RequestId::Number(723),
                SubscriptionFilter {
                    resources_list_changed: Some(true),
                    tools_list_changed: Some(true),
                    ..SubscriptionFilter::default()
                },
                false,
                None,
                McpRequestCancellation::new(),
                None,
                sender,
            )
        });

        let (lock, ready) = &*gate;
        let mut state = lock
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        while !state.0 {
            state = ready
                .wait(state)
                .unwrap_or_else(std::sync::PoisonError::into_inner);
        }
        drop(state);

        let publisher_registry = Arc::clone(&registry);
        let (published_sender, published_receiver) = std::sync::mpsc::channel();
        let publisher = thread::spawn(move || {
            let tools = publisher_registry
                .publish(ServerNotification::ToolsListChanged(None))
                .expect("held-ack tools publication must remain well-formed");
            let resources = publisher_registry
                .publish(ServerNotification::ResourcesListChanged(None))
                .expect("held-ack resources publication must remain well-formed");
            published_sender
                .send((tools, resources))
                .expect("publication result receiver must remain live");
        });
        assert_eq!(
            published_receiver
                .recv_timeout(Duration::from_secs(1))
                .expect("publishers must not wait for the acknowledgement callback"),
            (1, 1),
        );

        let mut state = lock
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        state.1 = true;
        ready.notify_all();
        drop(state);
        publisher.join().expect("publisher must not panic");
        let lease = opener
            .join()
            .expect("opener must not panic")
            .expect("queued publications must preserve stream admission");

        let sent = sent
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert_eq!(sent.len(), 3);
        assert!(matches!(
            ServerNotification::decode(&sent[0]),
            Ok(ServerNotification::SubscriptionsAcknowledged(_))
        ));
        assert!(matches!(
            ServerNotification::decode(&sent[1]),
            Ok(ServerNotification::ToolsListChanged(_))
        ));
        assert!(matches!(
            ServerNotification::decode(&sent[2]),
            Ok(ServerNotification::ResourcesListChanged(_))
        ));
        drop(sent);
        drop(lease);
    }

    #[test]
    fn final_subscription_opening_queue_capacity_fails_closed_without_delivery() {
        let registry = Arc::new(FinalSubscriptionRegistry::default());
        let gate = Arc::new((Mutex::new((false, false)), Condvar::new()));
        let sent = Arc::new(Mutex::new(Vec::<JsonRpcRequest>::new()));
        let sender_gate = Arc::clone(&gate);
        let sender_sent = Arc::clone(&sent);
        let sender: NotificationSender = Arc::new(move |notification| {
            sender_sent
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(notification);
            let (lock, ready) = &*sender_gate;
            let mut state = lock
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if !state.0 {
                state.0 = true;
                ready.notify_all();
                while !state.1 {
                    state = ready
                        .wait(state)
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                }
            }
        });
        let cancellation = McpRequestCancellation::new();
        let opener_registry = Arc::clone(&registry);
        let opener_cancellation = cancellation.clone();
        let opener = thread::spawn(move || {
            opener_registry.open(
                RequestId::Number(725),
                SubscriptionFilter {
                    tools_list_changed: Some(true),
                    ..SubscriptionFilter::default()
                },
                false,
                None,
                opener_cancellation,
                None,
                sender,
            )
        });

        let (lock, ready) = &*gate;
        let mut state = lock
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        while !state.0 {
            state = ready
                .wait(state)
                .unwrap_or_else(std::sync::PoisonError::into_inner);
        }
        drop(state);

        for admitted in 0..MAX_FINAL_SUBSCRIPTION_QUEUED_EVENTS {
            assert_eq!(
                registry
                    .publish(ServerNotification::ToolsListChanged(None))
                    .expect("bounded opening publication must remain well-formed"),
                1,
                "opening event {admitted} must fit within the frozen bound",
            );
        }
        assert_eq!(
            registry
                .publish(ServerNotification::ToolsListChanged(None))
                .expect("the first over-capacity publication must fail closed"),
            0,
        );
        assert!(
            cancellation.is_cancel_requested(),
            "capacity exhaustion must cancel the opening stream"
        );

        let mut state = lock
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        state.1 = true;
        ready.notify_all();
        drop(state);
        assert!(
            opener.join().expect("opener must not panic").is_err(),
            "a capacity-failed opening must not return a live lease"
        );
        assert_eq!(
            sent.lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .len(),
            1,
            "capacity failure must discard every queued event",
        );
        assert!(
            registry
                .inner
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .entries
                .is_empty(),
            "capacity failure must release its registry entry when acknowledgement unwinds",
        );
    }

    #[test]
    fn final_subscription_acknowledgement_panic_discards_reentrant_publication() {
        let registry = Arc::new(FinalSubscriptionRegistry::default());
        let sent = Arc::new(Mutex::new(Vec::<JsonRpcRequest>::new()));
        let published = Arc::new(AtomicUsize::new(usize::MAX));
        let sender_registry = Arc::clone(&registry);
        let sender_sent = Arc::clone(&sent);
        let sender_published = Arc::clone(&published);
        let sender: NotificationSender = Arc::new(move |notification| {
            sender_sent
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(notification);
            sender_published.store(
                sender_registry
                    .publish(ServerNotification::ToolsListChanged(None))
                    .expect("reentrant publication before acknowledgement panic must be valid"),
                Ordering::Release,
            );
            panic!("planted acknowledgement sender panic");
        });
        let cancellation = McpRequestCancellation::new();
        assert!(
            registry
                .open(
                    RequestId::Number(726),
                    SubscriptionFilter {
                        tools_list_changed: Some(true),
                        ..SubscriptionFilter::default()
                    },
                    false,
                    None,
                    cancellation.clone(),
                    None,
                    sender,
                )
                .is_err(),
            "an acknowledgement panic must fail stream admission"
        );
        assert_eq!(published.load(Ordering::Acquire), 1);
        assert!(cancellation.is_cancel_requested());
        assert_eq!(
            sent.lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .len(),
            1,
            "the queued event must never be delivered after acknowledgement panic",
        );
        assert!(
            registry
                .inner
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .entries
                .is_empty(),
            "acknowledgement panic must remove the failed opening entry",
        );
    }

    #[test]
    fn final_subscription_peer_cancellation_discards_held_ack_publication() {
        let registry = Arc::new(FinalSubscriptionRegistry::default());
        let gate = Arc::new((Mutex::new((false, false)), Condvar::new()));
        let sent = Arc::new(Mutex::new(Vec::<JsonRpcRequest>::new()));
        let sender_gate = Arc::clone(&gate);
        let sender_sent = Arc::clone(&sent);
        let sender: NotificationSender = Arc::new(move |notification| {
            sender_sent
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(notification);
            let (lock, ready) = &*sender_gate;
            let mut state = lock
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if !state.0 {
                state.0 = true;
                ready.notify_all();
                while !state.1 {
                    state = ready
                        .wait(state)
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                }
            }
        });
        let cancellation = McpRequestCancellation::new();
        let opener_registry = Arc::clone(&registry);
        let opener_cancellation = cancellation.clone();
        let opener = thread::spawn(move || {
            opener_registry.open(
                RequestId::Number(727),
                SubscriptionFilter {
                    tools_list_changed: Some(true),
                    ..SubscriptionFilter::default()
                },
                false,
                Some(727),
                opener_cancellation,
                None,
                sender,
            )
        });

        let (lock, ready) = &*gate;
        let mut state = lock
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        while !state.0 {
            state = ready
                .wait(state)
                .unwrap_or_else(std::sync::PoisonError::into_inner);
        }
        drop(state);
        assert_eq!(
            registry
                .publish(ServerNotification::ToolsListChanged(None))
                .expect("publication during a held acknowledgement must be admitted"),
            1,
        );
        assert!(registry.cancel_modern_http_owner(727));
        assert!(cancellation.is_cancel_requested());

        let mut state = lock
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        state.1 = true;
        ready.notify_all();
        drop(state);
        assert!(
            opener.join().expect("opener must not panic").is_err(),
            "peer cancellation must prevent a live lease"
        );
        assert_eq!(
            sent.lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .len(),
            1,
            "peer cancellation must discard the queued event",
        );
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn final_task_subscription_reentrant_ack_publication_flushes_after_acknowledgement() {
        let application_notifications = Arc::new(Mutex::new(Vec::new()));
        let (server, _service) = final_tasks_test_server(application_notifications);
        let runtime = server
            .final_task_runtime()
            .expect("final Tasks runtime must remain public");
        let created = runtime
            .create_task_with_work(
                final_tasks_test_work_descriptor(),
                Some("queued".to_owned()),
            )
            .expect("task must be durable before subscription");
        let task_id = created.task.base().task_id.clone();
        let task_notification = crate::tasks::final_task_notification(&created.task);
        let registry = Arc::clone(&server.final_subscriptions);
        let sent = Arc::new(Mutex::new(Vec::<JsonRpcRequest>::new()));
        let published = Arc::new(AtomicUsize::new(usize::MAX));
        let callback_count = Arc::new(AtomicUsize::new(0));
        let sender_registry = Arc::clone(&registry);
        let sender_sent = Arc::clone(&sent);
        let sender_published = Arc::clone(&published);
        let sender_callback_count = Arc::clone(&callback_count);
        let sender: NotificationSender = Arc::new(move |notification| {
            sender_sent
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(notification);
            if sender_callback_count.fetch_add(1, Ordering::AcqRel) == 0 {
                sender_published.store(
                    sender_registry
                        .publish_task(task_notification.clone())
                        .expect("reentrant Tasks publication must remain well-formed"),
                    Ordering::Release,
                );
            }
        });
        let mut requested = SubscriptionFilter::default();
        set_task_subscription_ids(&mut requested, vec![task_id.clone()])
            .expect("compose the exact Tasks selection");
        let _lease = registry
            .open(
                RequestId::Number(724),
                requested,
                true,
                None,
                McpRequestCancellation::new(),
                None,
                sender,
            )
            .expect("a reentrant Tasks publication must open");

        assert_eq!(published.load(Ordering::Acquire), 1);
        let sent = sent
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert_eq!(sent.len(), 2);
        assert!(matches!(
            ServerNotification::decode(&sent[0]),
            Ok(ServerNotification::SubscriptionsAcknowledged(_))
        ));
        let delivered: FinalTaskStatusNotification = serde_json::from_value(
            serde_json::to_value(&sent[1]).expect("queued Tasks event must serialize"),
        )
        .expect("queued Tasks event must retain its wire type");
        assert_eq!(delivered.params.task.base().task_id, task_id);
    }

    #[test]
    fn final_subscription_acknowledgement_sender_can_reenter_termination() {
        let (done_sender, done_receiver) = std::sync::mpsc::channel();
        let worker = std::thread::spawn(move || {
            let registry = Arc::new(FinalSubscriptionRegistry::default());
            let registry_for_sender = Arc::clone(&registry);
            let sent = Arc::new(Mutex::new(Vec::<JsonRpcRequest>::new()));
            let sent_for_sender = Arc::clone(&sent);
            let callback_count = Arc::new(AtomicUsize::new(0));
            let callback_count_for_sender = Arc::clone(&callback_count);
            let terminated = Arc::new(AtomicUsize::new(0));
            let terminated_for_sender = Arc::clone(&terminated);
            let cancellation = McpRequestCancellation::new();
            let sender: NotificationSender = Arc::new(move |notification| {
                sent_for_sender
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .push(notification);
                if callback_count_for_sender.fetch_add(1, Ordering::AcqRel) == 0 {
                    terminated_for_sender.store(registry_for_sender.terminate(), Ordering::Release);
                }
            });

            let lease = registry
                .open(
                    RequestId::Number(73),
                    SubscriptionFilter::default(),
                    false,
                    None,
                    cancellation.clone(),
                    None,
                    sender,
                )
                .expect("reentrant server termination should complete stream admission");
            let sent = sent
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .clone();
            done_sender
                .send((
                    lease.has_graceful_completion(),
                    cancellation.is_cancel_requested(),
                    callback_count.load(Ordering::Acquire),
                    terminated.load(Ordering::Acquire),
                    sent,
                ))
                .expect("reentrant acknowledgement result receiver should remain live");
        });

        let (graceful, cancelled, callback_count, terminated, sent) = done_receiver
            .recv_timeout(Duration::from_secs(2))
            .expect("acknowledgement callback reentry must not deadlock");
        worker
            .join()
            .expect("reentrant acknowledgement worker should not panic");
        assert!(graceful);
        assert!(cancelled);
        assert_eq!(callback_count, 2);
        assert_eq!(terminated, 1);
        assert!(matches!(
            ServerNotification::decode(&sent[0]),
            Ok(ServerNotification::SubscriptionsAcknowledged(_))
        ));
        assert!(matches!(
            ServerNotification::decode(&sent[1]),
            Ok(ServerNotification::Cancelled(params))
                if params.request_id == RequestId::Number(73)
        ));
    }

    #[test]
    fn final_subscription_event_sender_can_reenter_termination() {
        let (done_sender, done_receiver) = std::sync::mpsc::channel();
        let worker = std::thread::spawn(move || {
            let registry = Arc::new(FinalSubscriptionRegistry::default());
            let registry_for_sender = Arc::clone(&registry);
            let sent = Arc::new(Mutex::new(Vec::<JsonRpcRequest>::new()));
            let sent_for_sender = Arc::clone(&sent);
            let callback_count = Arc::new(AtomicUsize::new(0));
            let callback_count_for_sender = Arc::clone(&callback_count);
            let terminated = Arc::new(AtomicUsize::new(0));
            let terminated_for_sender = Arc::clone(&terminated);
            let cancellation = McpRequestCancellation::new();
            let sender: NotificationSender = Arc::new(move |notification| {
                sent_for_sender
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .push(notification);
                if callback_count_for_sender.fetch_add(1, Ordering::AcqRel) == 1 {
                    terminated_for_sender.store(registry_for_sender.terminate(), Ordering::Release);
                }
            });

            let lease = registry
                .open(
                    RequestId::Number(74),
                    SubscriptionFilter {
                        tools_list_changed: Some(true),
                        ..SubscriptionFilter::default()
                    },
                    false,
                    None,
                    cancellation.clone(),
                    None,
                    sender,
                )
                .expect("event reentry stream should admit");
            let published = registry
                .publish(ServerNotification::ToolsListChanged(None))
                .expect("event delivery with reentrant termination should remain valid");
            let sent = sent
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .clone();
            done_sender
                .send((
                    lease.has_graceful_completion(),
                    cancellation.is_cancel_requested(),
                    callback_count.load(Ordering::Acquire),
                    terminated.load(Ordering::Acquire),
                    published,
                    sent,
                ))
                .expect("reentrant event result receiver should remain live");
        });

        let (graceful, cancelled, callback_count, terminated, published, sent) = done_receiver
            .recv_timeout(Duration::from_secs(2))
            .expect("event callback reentry must not deadlock");
        worker
            .join()
            .expect("reentrant event worker should not panic");
        assert!(graceful);
        assert!(cancelled);
        assert_eq!(callback_count, 3);
        assert_eq!(terminated, 1);
        assert_eq!(published, 1);
        assert!(matches!(
            ServerNotification::decode(&sent[0]),
            Ok(ServerNotification::SubscriptionsAcknowledged(_))
        ));
        assert!(matches!(
            ServerNotification::decode(&sent[1]),
            Ok(ServerNotification::ToolsListChanged(_))
        ));
        assert!(matches!(
            ServerNotification::decode(&sent[2]),
            Ok(ServerNotification::Cancelled(params))
                if params.request_id == RequestId::Number(74)
        ));
    }

    struct HeldFinalSubscription {
        handle: SubscriptionListenHandle,
        frames: Arc<Mutex<Vec<JsonRpcRequest>>>,
        release: Arc<(Mutex<bool>, Condvar)>,
        entered: std::sync::mpsc::Receiver<()>,
        max_active: Arc<AtomicUsize>,
    }

    impl HeldFinalSubscription {
        fn open(server: &Arc<Server>, id: i64) -> Self {
            let frames = Arc::new(Mutex::new(Vec::new()));
            let release = Arc::new((Mutex::new(false), Condvar::new()));
            let active = Arc::new(AtomicUsize::new(0));
            let max_active = Arc::new(AtomicUsize::new(0));
            let (entered_sender, entered) = std::sync::mpsc::channel();
            let sender_frames = Arc::clone(&frames);
            let sender_release = Arc::clone(&release);
            let sender_active = Arc::clone(&active);
            let sender_max_active = Arc::clone(&max_active);
            let held = AtomicBool::new(false);
            let sender: NotificationSender = Arc::new(move |notification| {
                let acknowledgement =
                    final_subscription_acknowledgement_notification(&notification);
                sender_frames.lock().unwrap().push(notification);
                if acknowledgement {
                    return;
                }
                let active = sender_active.fetch_add(1, Ordering::AcqRel) + 1;
                sender_max_active.fetch_max(active, Ordering::AcqRel);
                if !held.swap(true, Ordering::AcqRel) {
                    entered_sender
                        .send(())
                        .expect("first callback observer remains live");
                    let (lock, ready) = &*sender_release;
                    let mut released = lock.lock().unwrap();
                    while !*released {
                        released = ready.wait(released).unwrap();
                    }
                }
                sender_active.fetch_sub(1, Ordering::AcqRel);
            });
            let handle = server
                .open_subscription_listen(
                    RequestId::Number(id),
                    SubscriptionFilter {
                        tools_list_changed: Some(true),
                        resources_list_changed: Some(true),
                        ..SubscriptionFilter::default()
                    },
                    sender,
                )
                .expect("public listener must acknowledge before publication");
            Self {
                handle,
                frames,
                release,
                entered,
                max_active,
            }
        }

        fn release(&self) {
            let (lock, ready) = &*self.release;
            *lock.lock().unwrap() = true;
            ready.notify_all();
        }
    }

    impl Drop for HeldFinalSubscription {
        fn drop(&mut self) {
            self.release();
        }
    }

    #[test]
    fn final_subscription_active_publications_are_serial_and_fifo() {
        let server = Arc::new(Server::new("active-subscription-fifo", "1.0.0").build());
        let held = HeldFinalSubscription::open(&server, 730);
        let first_server = Arc::clone(&server);
        let first = thread::spawn(move || {
            first_server
                .publish_subscription_notification(ServerNotification::ToolsListChanged(None))
        });
        held.entered
            .recv_timeout(Duration::from_secs(2))
            .expect("first event must enter");
        let second_server = Arc::clone(&server);
        let (done_sender, done) = std::sync::mpsc::channel();
        let second = thread::spawn(move || {
            let result = second_server
                .publish_subscription_notification(ServerNotification::ResourcesListChanged(None));
            done_sender
                .send(result)
                .expect("second publisher observer remains live");
        });
        let admitted = done.recv_timeout(Duration::from_secs(2));
        let frames_before_release = held.frames.lock().unwrap().len();
        held.release();
        assert_eq!(
            first
                .join()
                .expect("first publisher must not panic")
                .expect("first event publishes"),
            1
        );
        second.join().expect("second publisher must not panic");
        assert_eq!(
            admitted
                .expect("concurrent publisher must not wait for callback")
                .unwrap(),
            1
        );
        assert_eq!(
            frames_before_release, 2,
            "only acknowledgement and first callback may enter"
        );
        assert_eq!(held.max_active.load(Ordering::Acquire), 1);
        let frames = held.frames.lock().unwrap();
        assert_eq!(
            frames
                .iter()
                .map(|frame| frame.method.as_str())
                .collect::<Vec<_>>(),
            vec![
                "notifications/subscriptions/acknowledged",
                "notifications/tools/list_changed",
                "notifications/resources/list_changed",
            ]
        );
        for frame in frames.iter() {
            assert_eq!(
                frame.params.as_ref().unwrap()["_meta"][FINAL_SUBSCRIPTION_ID_META_KEY],
                serde_json::json!(730)
            );
        }
        let queue = held.handle.lease().election.opening_events.lock().unwrap();
        assert_eq!((queue.retained_events, queue.retained_bytes), (0, 0));
    }

    #[test]
    fn final_subscription_active_overflow_retires_only_slow_listener() {
        let server = Arc::new(Server::new("active-subscription-overflow", "1.0.0").build());
        let held = HeldFinalSubscription::open(&server, 731);
        let fast_frames = Arc::new(AtomicUsize::new(0));
        let sender_frames = Arc::clone(&fast_frames);
        let _fast = server
            .open_subscription_listen(
                RequestId::Number(732),
                SubscriptionFilter {
                    tools_list_changed: Some(true),
                    ..SubscriptionFilter::default()
                },
                Arc::new(move |_| {
                    sender_frames.fetch_add(1, Ordering::AcqRel);
                }),
            )
            .expect("unrelated listener must acknowledge");
        let first_server = Arc::clone(&server);
        let first = thread::spawn(move || {
            first_server
                .publish_subscription_notification(ServerNotification::ToolsListChanged(None))
        });
        held.entered
            .recv_timeout(Duration::from_secs(2))
            .expect("slow event must enter");
        for _ in 1..MAX_FINAL_SUBSCRIPTION_QUEUED_EVENTS {
            assert_eq!(
                server
                    .publish_subscription_notification(ServerNotification::ToolsListChanged(None))
                    .unwrap(),
                2
            );
        }
        {
            let queue = held.handle.lease().election.opening_events.lock().unwrap();
            assert_eq!(queue.retained_events, MAX_FINAL_SUBSCRIPTION_QUEUED_EVENTS);
            assert!(queue.retained_bytes > 0);
        }
        assert_eq!(
            server
                .publish_subscription_notification(ServerNotification::ToolsListChanged(None))
                .unwrap(),
            1,
            "one extra event must retire only the listener at its bound"
        );
        {
            let queue = held.handle.lease().election.opening_events.lock().unwrap();
            assert_eq!(
                (
                    queue.retained_events,
                    queue.retained_bytes,
                    queue.events.len()
                ),
                (0, 0, 0)
            );
        }
        assert!(
            !server
                .final_subscriptions
                .inner
                .lock()
                .unwrap()
                .entries
                .contains_key(&held.handle.lease().key),
            "capacity must be released while the failed callback and public handle remain live"
        );
        assert_eq!(
            server
                .publish_subscription_notification(ServerNotification::ToolsListChanged(None))
                .unwrap(),
            1
        );
        held.release();
        assert_eq!(
            first
                .join()
                .expect("first publisher must not panic")
                .unwrap(),
            1
        );
        assert_eq!(
            held.frames.lock().unwrap().len(),
            2,
            "queued events must never run after overflow"
        );
        assert_eq!(
            fast_frames.load(Ordering::Acquire),
            MAX_FINAL_SUBSCRIPTION_QUEUED_EVENTS + 3,
            "the sibling receives acknowledgement and every publication exactly once"
        );
        assert_eq!(held.max_active.load(Ordering::Acquire), 1);
    }

    #[test]
    fn final_subscription_active_byte_limit_rejects_before_retaining() {
        for excess in [0, 1] {
            let server = Arc::new(Server::new("active-subscription-bytes", "1.0.0").build());
            let held = HeldFinalSubscription::open(&server, 733);
            let first_server = Arc::clone(&server);
            let first = thread::spawn(move || {
                first_server
                    .publish_subscription_notification(ServerNotification::ToolsListChanged(None))
            });
            held.entered
                .recv_timeout(Duration::from_secs(2))
                .expect("first event must enter");
            let first_bytes = held
                .handle
                .lease()
                .election
                .opening_events
                .lock()
                .unwrap()
                .retained_bytes;
            let event = |size| {
                ServerNotification::ToolsListChanged(Some(
                    fastmcp_protocol::FinalEmptyNotificationParams {
                        meta: None,
                        additional: BTreeMap::from([(
                            "payload".to_owned(),
                            serde_json::json!("x".repeat(size)),
                        )]),
                    },
                ))
            };
            let empty = tag_subscription_notification(&event(0), &RequestId::Number(733))
                .unwrap()
                .encode()
                .unwrap();
            let overhead = final_subscription_event_bytes(&empty).unwrap();
            let payload = MAX_FINAL_SUBSCRIPTION_QUEUED_BYTES - first_bytes - overhead + excess;
            let admitted = server
                .publish_subscription_notification(event(payload))
                .unwrap();
            {
                let queue = held.handle.lease().election.opening_events.lock().unwrap();
                if excess == 0 {
                    assert_eq!(
                        (admitted, queue.retained_events, queue.retained_bytes),
                        (1, 2, MAX_FINAL_SUBSCRIPTION_QUEUED_BYTES)
                    );
                } else {
                    assert_eq!(
                        (admitted, queue.retained_events, queue.retained_bytes),
                        (0, 0, 0)
                    );
                    assert!(
                        !server
                            .final_subscriptions
                            .inner
                            .lock()
                            .unwrap()
                            .entries
                            .contains_key(&held.handle.lease().key)
                    );
                }
            }
            held.release();
            assert_eq!(
                first
                    .join()
                    .expect("first publisher must not panic")
                    .unwrap(),
                usize::from(excess == 0)
            );
            assert_eq!(
                held.frames.lock().unwrap().len(),
                if excess == 0 { 3 } else { 2 }
            );
            let queue = held.handle.lease().election.opening_events.lock().unwrap();
            assert_eq!((queue.retained_events, queue.retained_bytes), (0, 0));
        }

        // An individually oversized payload is rejected before recipient
        // copies or queue mutation, leaving even a matching listener usable.
        let server = Server::new("subscription-prefanout-bound", "1.0.0").build();
        let frames = Arc::new(AtomicUsize::new(0));
        let sender_frames = Arc::clone(&frames);
        let handle = server
            .open_subscription_listen(
                RequestId::Number(735),
                SubscriptionFilter {
                    tools_list_changed: Some(true),
                    ..SubscriptionFilter::default()
                },
                Arc::new(move |_| {
                    sender_frames.fetch_add(1, Ordering::AcqRel);
                }),
            )
            .unwrap();
        let oversized = ServerNotification::ToolsListChanged(Some(
            fastmcp_protocol::FinalEmptyNotificationParams {
                meta: None,
                additional: BTreeMap::from([(
                    "payload".to_owned(),
                    serde_json::json!("x".repeat(MAX_FINAL_SUBSCRIPTION_QUEUED_BYTES + 1)),
                )]),
            },
        ));
        let error = server
            .publish_subscription_notification(oversized)
            .expect_err("oversized source data must be rejected before fanout");
        assert_eq!(
            error.code,
            McpErrorCode::Custom(RESOURCE_EXHAUSTED_ERROR_CODE)
        );
        assert_eq!(frames.load(Ordering::Acquire), 1);
        assert!(
            server
                .final_subscriptions
                .inner
                .lock()
                .unwrap()
                .entries
                .contains_key(&handle.lease().key)
        );
        let queue = handle.lease().election.opening_events.lock().unwrap();
        assert_eq!((queue.retained_events, queue.retained_bytes), (0, 0));
        drop(queue);
        assert_eq!(
            server
                .publish_subscription_notification(ServerNotification::ToolsListChanged(None))
                .unwrap(),
            1
        );
        assert_eq!(frames.load(Ordering::Acquire), 2);
    }

    #[test]
    fn final_subscription_active_reentrant_publish_and_teardown_preserve_order() {
        for (terminate, panic_after_enqueue) in [(false, false), (true, false), (false, true)] {
            let server = Arc::new(Server::new("active-subscription-reentrant", "1.0.0").build());
            let sender_server = Arc::downgrade(&server);
            let frames = Arc::new(Mutex::new(Vec::new()));
            let sender_frames = Arc::clone(&frames);
            let active = AtomicUsize::new(0);
            let max_active = Arc::new(AtomicUsize::new(0));
            let sender_max = Arc::clone(&max_active);
            let queued = Arc::new(AtomicUsize::new(usize::MAX));
            let sender_queued = Arc::clone(&queued);
            let sender: NotificationSender = Arc::new(move |notification| {
                let active_count = active.fetch_add(1, Ordering::AcqRel) + 1;
                sender_max.fetch_max(active_count, Ordering::AcqRel);
                let publish = notification.method == "notifications/tools/list_changed";
                sender_frames.lock().unwrap().push(notification);
                if publish {
                    let server = sender_server
                        .upgrade()
                        .expect("public publisher remains live");
                    sender_queued.store(
                        server
                            .publish_subscription_notification(
                                ServerNotification::ResourcesListChanged(None),
                            )
                            .unwrap(),
                        Ordering::Release,
                    );
                    if panic_after_enqueue {
                        panic!("planted sender panic after reentrant queue admission");
                    }
                    if terminate {
                        assert_eq!(server.terminate_subscription_streams(), 1);
                    }
                }
                active.fetch_sub(1, Ordering::AcqRel);
            });
            let handle = server
                .open_subscription_listen(
                    RequestId::Number(734),
                    SubscriptionFilter {
                        tools_list_changed: Some(true),
                        resources_list_changed: Some(true),
                        ..SubscriptionFilter::default()
                    },
                    sender,
                )
                .unwrap();
            assert_eq!(
                server
                    .publish_subscription_notification(ServerNotification::ToolsListChanged(None))
                    .unwrap(),
                usize::from(!panic_after_enqueue)
            );
            assert_eq!(queued.load(Ordering::Acquire), 1);
            assert_eq!(
                max_active.load(Ordering::Acquire),
                1,
                "reentrant publication must not reenter the callback"
            );
            let frames = frames.lock().unwrap();
            let mut expected = vec![
                "notifications/subscriptions/acknowledged",
                "notifications/tools/list_changed",
            ];
            if !panic_after_enqueue {
                expected.push(if terminate {
                    "notifications/cancelled"
                } else {
                    "notifications/resources/list_changed"
                });
            }
            assert_eq!(
                frames
                    .iter()
                    .map(|frame| frame.method.as_str())
                    .collect::<Vec<_>>(),
                expected
            );
            assert_eq!(handle.lease().has_graceful_completion(), terminate);
            if panic_after_enqueue {
                assert!(
                    server
                        .final_subscriptions
                        .inner
                        .lock()
                        .unwrap()
                        .entries
                        .is_empty()
                );
            }
            let queue = handle.lease().election.opening_events.lock().unwrap();
            assert_eq!((queue.retained_events, queue.retained_bytes), (0, 0));
        }
    }

    #[test]
    fn final_subscription_concurrent_publications_are_not_silently_dropped() {
        let registry = Arc::new(FinalSubscriptionRegistry::default());
        let sent = Arc::new(AtomicUsize::new(0));
        let sent_for_sender = Arc::clone(&sent);
        let (entered_sender, entered_receiver) = std::sync::mpsc::channel();
        let release = Arc::new((Mutex::new(false), Condvar::new()));
        let release_for_sender = Arc::clone(&release);
        let sender: NotificationSender = Arc::new(move |notification| {
            sent_for_sender.fetch_add(1, Ordering::AcqRel);
            if matches!(
                ServerNotification::decode(&notification),
                Ok(ServerNotification::SubscriptionsAcknowledged(_))
            ) {
                return;
            }
            entered_sender
                .send(())
                .expect("concurrent publication observer should remain live");
            let (lock, ready) = &*release_for_sender;
            let mut released = lock
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            while !*released {
                released = ready
                    .wait(released)
                    .unwrap_or_else(std::sync::PoisonError::into_inner);
            }
        });
        let _lease = registry
            .open(
                RequestId::Number(75),
                SubscriptionFilter {
                    tools_list_changed: Some(true),
                    ..SubscriptionFilter::default()
                },
                false,
                None,
                McpRequestCancellation::new(),
                None,
                sender,
            )
            .expect("concurrent publication stream should admit");

        let first_registry = Arc::clone(&registry);
        let first = thread::spawn(move || {
            first_registry.publish(ServerNotification::ToolsListChanged(None))
        });
        entered_receiver
            .recv_timeout(Duration::from_secs(2))
            .expect("first publication callback should start");
        let second_registry = Arc::clone(&registry);
        let (admitted_sender, admitted_receiver) = std::sync::mpsc::channel();
        let second = thread::spawn(move || {
            let result = second_registry.publish(ServerNotification::ToolsListChanged(None));
            admitted_sender
                .send(())
                .expect("second admission observer remains live");
            result
        });
        let second_admitted = admitted_receiver
            .recv_timeout(Duration::from_secs(2))
            .is_ok();
        let second_entered = entered_receiver.try_recv().is_ok();

        let (lock, ready) = &*release;
        *lock
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner) = true;
        ready.notify_all();

        let first_result = first
            .join()
            .expect("first concurrent publisher should not panic")
            .expect("first concurrent publication should remain valid");
        let second_result = second
            .join()
            .expect("second concurrent publisher should not panic")
            .expect("second concurrent publication should remain valid");
        assert!(
            second_admitted && !second_entered,
            "the second event must be admitted without a concurrent callback or a dropped event"
        );
        assert_eq!(first_result, 1);
        assert_eq!(second_result, 1);
        assert_eq!(
            sent.load(Ordering::Acquire),
            3,
            "one acknowledgement and both accepted events must reach the sender"
        );
    }

    #[test]
    fn final_subscription_terminal_result_is_complete_and_correlated() {
        use fastmcp_protocol::CoreRequest;

        let server = Server::new("final-subscriptions-test", "1.0.0").build();
        let subscription_id = RequestId::String("subscription-terminal".to_owned());
        let terminal = server
            .final_subscription_complete_result(&subscription_id)
            .expect("terminal result should encode through the final result algebra");
        assert_eq!(
            terminal.get("resultType"),
            Some(&serde_json::json!("complete"))
        );
        assert_eq!(
            terminal
                .get("_meta")
                .and_then(|metadata| metadata.get(FINAL_SUBSCRIPTION_ID_META_KEY)),
            Some(&serde_json::to_value(&subscription_id).expect("id must serialize"))
        );

        let request_metadata = OpenMetadata::try_from_entries([
            (
                "io.modelcontextprotocol/protocolVersion".to_owned(),
                serde_json::json!(MODERN_PROTOCOL_VERSION),
            ),
            (
                FINAL_CLIENT_CAPABILITIES_META_KEY.to_owned(),
                serde_json::json!({}),
            ),
        ])
        .expect("final request metadata must be valid");
        let params = serde_json::to_value(FinalSubscriptionsListenParams {
            meta: request_metadata,
            notifications: SubscriptionFilter::default(),
        })
        .expect("final listen parameters must serialize");
        let request =
            CoreRequest::decode(ProtocolEra::Modern2026, SUBSCRIPTIONS_LISTEN, Some(&params))
                .expect("final listen request must select the final result decoder");
        let response = JsonRpcResponse::success(subscription_id.clone(), terminal);
        let CoreResult::Final(FinalCoreResult::SubscriptionsListen {
            subscription_id: decoded_id,
            ..
        }) = request
            .decode_response(&response)
            .expect("terminal complete result must round-trip with its response id")
        else {
            panic!("subscriptions/listen must decode only its terminal final result");
        };
        assert_eq!(decoded_id, subscription_id);
    }

    #[test]
    fn public_stdio_listen_teardown_emits_cancelled_before_correlated_completion() {
        let server = Arc::new(Server::new("final-listen-dispatch-test", "1.0.0").build());
        let wire = Arc::new(Mutex::new(Vec::<JsonRpcMessage>::new()));
        let wire_for_sender = Arc::clone(&wire);
        let notification_sender: NotificationSender = Arc::new(move |notification| {
            wire_for_sender
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(JsonRpcMessage::Request(notification));
        });
        let subscription_id = RequestId::Number(73);
        let metadata = OpenMetadata::try_from_entries([
            (
                "io.modelcontextprotocol/protocolVersion".to_owned(),
                serde_json::json!(MODERN_PROTOCOL_VERSION),
            ),
            (
                FINAL_CLIENT_CAPABILITIES_META_KEY.to_owned(),
                serde_json::json!({}),
            ),
        ])
        .expect("final request metadata must be valid");
        let params = serde_json::to_value(FinalSubscriptionsListenParams {
            meta: metadata,
            notifications: SubscriptionFilter {
                tools_list_changed: Some(true),
                ..SubscriptionFilter::default()
            },
        })
        .expect("final listen parameters must serialize");
        let request =
            JsonRpcRequest::new(SUBSCRIPTIONS_LISTEN, Some(params), subscription_id.clone());
        let inbound = InboundRequestContext::new(
            Cx::for_testing(),
            request_id_to_u64(Some(&subscription_id)),
            InboundRequestTransport::Stdio,
        );
        let terminator = {
            let server = Arc::clone(&server);
            let wire = Arc::clone(&wire);
            std::thread::spawn(move || {
                for _ in 0..100 {
                    if !wire
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .is_empty()
                    {
                        return server.terminate_subscription_streams() == 1;
                    }
                    std::thread::sleep(Duration::from_millis(1));
                }
                false
            })
        };
        let response = block_on(Arc::clone(&server).dispatch_with_protocol_policy_owned(
            ProtocolPolicy::ModernOnly,
            &inbound,
            request,
            None,
            None,
            None,
            None,
            McpRequestCancellation::new(),
            None,
            notification_sender,
        ));

        assert!(
            terminator
                .join()
                .expect("subscription terminator must not panic"),
            "the listener must acknowledge before graceful termination"
        );
        let acknowledgement = wire
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .first()
            .cloned()
            .expect("listener must emit its acknowledgement before terminating");
        let JsonRpcMessage::Request(acknowledgement) = acknowledgement else {
            panic!("listener acknowledgement must be a JSON-RPC notification");
        };
        assert!(matches!(
            ServerNotification::decode(&acknowledgement),
            Ok(ServerNotification::SubscriptionsAcknowledged(_))
        ));
        let response = response.expect("server-owned stdio teardown must complete the listen");
        assert_eq!(response.id, Some(subscription_id.clone()));
        assert!(
            final_subscription_completion_response(&response),
            "server-owned teardown must complete the exact listen request; response={response:?}"
        );
        wire.lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .push(JsonRpcMessage::Response(response.clone()));
        let wire = wire
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let terminal_position = wire
            .iter()
            .position(|message| {
                let JsonRpcMessage::Request(notification) = message else {
                    return false;
                };
                matches!(
                    ServerNotification::decode(notification),
                    Ok(ServerNotification::Cancelled(_))
                )
            })
            .expect("server teardown must emit one cancellation control after acknowledgement");
        let JsonRpcMessage::Request(terminal) = &wire[terminal_position] else {
            unreachable!("the terminal position above only selects requests");
        };
        let ServerNotification::Cancelled(terminal) = ServerNotification::decode(terminal)
            .expect("terminal control must use the final server notification union")
        else {
            panic!("server teardown must emit notifications/cancelled");
        };
        assert_eq!(terminal.request_id, subscription_id);
        assert_eq!(
            terminal
                .meta
                .as_ref()
                .and_then(|meta| meta.get(FINAL_SUBSCRIPTION_ID_META_KEY)),
            Some(&serde_json::json!(73)),
            "terminal metadata must correlate to exactly this listen request",
        );
        let completion_position = wire
            .iter()
            .position(|message| {
                matches!(
                    message,
                    JsonRpcMessage::Response(response)
                        if response.id == Some(subscription_id.clone())
                            && final_subscription_completion_response(response)
                )
            })
            .expect("server teardown must emit the correlated completion result");
        assert_eq!(
            wire.len(),
            3,
            "the acknowledgement, correlated cancellation control, and completion are exact",
        );
        assert!(
            terminal_position < completion_position,
            "stdio must emit notifications/cancelled before the correlated complete result"
        );
    }

    #[test]
    fn http_sse_accept_qvalue_admits_rfc_forms_and_rejects_four_fraction_digits() {
        let accepts = |value| {
            http_request_accepts_sse(
                &HttpRequest::new(HttpMethod::Post, "/mcp").with_header("accept", value),
            )
        };
        assert!(accepts("  */* ; Q=1. "));
        assert!(!accepts("  */* ; Q=0. "));
        assert!(!accepts("*/*; Q = 1."));
        assert!(!accepts("*/*; unrelated=value; Q=1."));
        assert!(!accepts("text/event-stream; q=1.0000"));
        assert!(!accepts("text/event-stream; q=0.0000"));
    }

    #[test]
    fn http_sse_accept_exclusions_override_wildcards_before_stream_allocation() {
        for value in [
            "text/event-stream;q=0, */*;q=1",
            "*/*;q=1, text/event-stream;q=0",
            "text/*;q=0, */*;q=1",
            "text/event-stream, text/event-stream;q=0, application/json",
            "application/json;profile=\"x, text/event-stream\"",
        ] {
            assert!(
                !http_request_accepts_sse(
                    &HttpRequest::new(HttpMethod::Post, "/mcp").with_header("accept", value),
                ),
                "a required SSE body must honor the full admitted preference: {value}",
            );
        }
        assert!(http_request_accepts_sse(
            &HttpRequest::new(HttpMethod::Post, "/mcp")
                .with_header("accept", "text/event-stream;q=0.1, */*;q=1"),
        ));
        assert!(!http_request_accepts_sse(&HttpRequest::new(
            HttpMethod::Post,
            "/mcp",
        )));
    }

    #[test]
    fn public_http_modern_disabled_components_are_isolated_between_sessions() {
        let cx = Cx::for_testing();
        let calls = Arc::new(AtomicUsize::new(0));
        let endpoint = Server::new("modern-http-session-isolation", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .tool(HttpSessionDisablingTool {
                calls: Arc::clone(&calls),
            })
            .test_http_endpoint("http://final.test")
            .expect("modern endpoint must build");
        let mut first_client = endpoint
            .open_session(&cx)
            .expect("first modern HTTP session must open");
        let mut second_client = endpoint
            .open_session(&cx)
            .expect("second modern HTTP session must open");

        let request = modern_http_json_tool_request("http_session_disabling_tool", 901);
        for session in [&mut first_client, &mut second_client] {
            let response = block_on(session.handle_async(&cx, request.clone()))
                .expect("each independently admitted modern session must dispatch its first call");
            let ServerHttpEndpointResponse::Immediate(response) = response else {
                panic!("ordinary modern tool calls must return JSON responses");
            };
            let response: JsonRpcResponse = serde_json::from_slice(&response.body)
                .expect("modern tool response must remain JSON-RPC");
            assert_eq!(response.id, Some(901_i64.into()));
            assert!(response.error.is_none());
        }

        assert_eq!(
            calls.load(Ordering::Acquire),
            2,
            "disabling the tool for the first client must not prevent the second client entering it",
        );
    }

    #[test]
    fn public_http_modern_disabled_components_reject_only_the_same_session() {
        let cx = Cx::for_testing();
        let calls = Arc::new(AtomicUsize::new(0));
        let endpoint = Server::new("modern-http-session-disablement", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .tool(HttpSessionDisablingTool {
                calls: Arc::clone(&calls),
            })
            .test_http_endpoint("http://final.test")
            .expect("modern endpoint must build");
        let mut first_client = endpoint
            .open_session(&cx)
            .expect("first modern HTTP session must open");
        let mut second_client = endpoint
            .open_session(&cx)
            .expect("second modern HTTP session must open");

        let first = block_on(first_client.handle_async(
            &cx,
            modern_http_json_tool_request("http_session_disabling_tool", 903),
        ))
        .expect("first session must dispatch the disabling call");
        assert!(matches!(
            first,
            ServerHttpEndpointResponse::Immediate(response)
                if serde_json::from_slice::<JsonRpcResponse>(&response.body)
                    .is_ok_and(|response| response.error.is_none())
        ));

        let comparison = modern_http_json_tool_request("http_session_disabling_tool", 904);
        let rejected = block_on(first_client.handle_async(&cx, comparison.clone()))
            .expect("same-session disablement must be represented as JSON-RPC");
        assert!(matches!(
            rejected,
            ServerHttpEndpointResponse::Immediate(response)
                if serde_json::from_slice::<JsonRpcResponse>(&response.body).is_ok_and(|response| {
                    response.id == Some(904_i64.into())
                        && response.error.is_some_and(|error| error.code.as_i32() == Some(-32601))
                })
        ));

        let independent = block_on(second_client.handle_async(&cx, comparison))
            .expect("changing only the client session must restore its independent state");
        assert!(matches!(
            independent,
            ServerHttpEndpointResponse::Immediate(response)
                if serde_json::from_slice::<JsonRpcResponse>(&response.body)
                    .is_ok_and(|response| response.id == Some(904_i64.into()) && response.error.is_none())
        ));
        assert_eq!(calls.load(Ordering::Acquire), 2);
    }

    #[test]
    fn rh5_native_http_rejects_server_notification_before_auth_and_session_admission() {
        let cx = Cx::for_testing();
        let provider_calls = Arc::new(AtomicUsize::new(0));
        let handler_calls = Arc::new(AtomicUsize::new(0));
        let middleware_calls = Arc::new(AtomicUsize::new(0));
        let saw_credential = Arc::new(AtomicBool::new(false));
        let endpoint = Server::new("native-http-wrong-direction-notification", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .auth_provider(OneShotNativeAuthProvider {
                calls: Arc::clone(&provider_calls),
            })
            .middleware(ModernHttpAuthMiddleware {
                calls: Arc::clone(&middleware_calls),
                saw_credential: Arc::clone(&saw_credential),
            })
            .tool(ModernHttpAuthCounterTool {
                calls: Arc::clone(&handler_calls),
            })
            .test_http_endpoint("http://final.test")
            .expect("modern endpoint must build");
        let mut session = endpoint
            .open_session(&cx)
            .expect("modern endpoint session must open");
        let server_notification = JsonRpcRequest::notification(
            "notifications/progress",
            Some(serde_json::json!({"progressToken": "server-only", "progress": 1})),
        );
        let rejected = block_on(
            session.handle_async(
                &cx,
                HttpRequest::new(HttpMethod::Post, "/mcp")
                    .with_header("content-type", "application/json")
                    .with_header("accept", "application/json")
                    .with_header("mcp-protocol-version", MODERN_PROTOCOL_VERSION)
                    .with_header("mcp-method", "notifications/progress")
                    .with_body(
                        serde_json::to_vec(&server_notification)
                            .expect("wrong-direction notification must encode"),
                    ),
            ),
        )
        .expect("native HTTP must reject the wrong-direction notification");
        assert!(matches!(
            rejected,
            ServerHttpEndpointResponse::Immediate(HttpResponse {
                status: HttpStatus::BAD_REQUEST,
                ..
            })
        ));
        assert_eq!(provider_calls.load(Ordering::Acquire), 0);
        assert_eq!(middleware_calls.load(Ordering::Acquire), 0);
        assert_eq!(handler_calls.load(Ordering::Acquire), 0);
        assert!(!saw_credential.load(Ordering::Acquire));
        assert_eq!(session.selected_era, None);
        assert!(
            endpoint
                .server
                .active_requests
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .is_empty(),
            "rejected native HTTP notification must not allocate a request session"
        );

        let accepted = block_on(
            session.handle_async(
                &cx,
                modern_http_json_tool_request("modern_http_auth_counter", 947)
                    .with_header("authorization", "Bearer alpha"),
            ),
        )
        .expect("the same HTTP session must remain usable after rejection");
        assert!(matches!(
            accepted,
            ServerHttpEndpointResponse::Immediate(response)
                if serde_json::from_slice::<JsonRpcResponse>(&response.body).is_ok_and(|response| {
                    response.id == Some(947_i64.into()) && response.error.is_none()
                })
        ));
        assert_eq!(provider_calls.load(Ordering::Acquire), 1);
        assert_eq!(middleware_calls.load(Ordering::Acquire), 1);
        assert_eq!(handler_calls.load(Ordering::Acquire), 1);
    }

    #[test]
    fn public_http_modern_authorization_authenticates_before_middleware_and_fences_principals() {
        let cx = Cx::for_testing();
        let handler_calls = Arc::new(AtomicUsize::new(0));
        let middleware_calls = Arc::new(AtomicUsize::new(0));
        let saw_credential = Arc::new(AtomicBool::new(false));
        let endpoint = Server::new("modern-http-authorization", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .auth_provider(ModernHttpAuthProvider)
            .middleware(ModernHttpAuthMiddleware {
                calls: Arc::clone(&middleware_calls),
                saw_credential: Arc::clone(&saw_credential),
            })
            .tool(ModernHttpAuthCounterTool {
                calls: Arc::clone(&handler_calls),
            })
            .test_http_endpoint("http://final.test")
            .expect("modern endpoint must build");
        let mut session = endpoint
            .open_session(&cx)
            .expect("modern endpoint session must open");

        let allowed = block_on(
            session.handle_async(
                &cx,
                modern_http_json_tool_request("modern_http_auth_counter", 931)
                    .with_header("authorization", "Bearer alpha"),
            ),
        )
        .expect("allowed bearer must dispatch");
        let ServerHttpEndpointResponse::Immediate(allowed) = allowed else {
            panic!("ordinary authenticated modern HTTP must return JSON");
        };
        let allowed: JsonRpcResponse =
            serde_json::from_slice(&allowed.body).expect("allowed response must be JSON-RPC");
        assert_eq!(allowed.id, Some(931_i64.into()));
        assert!(allowed.error.is_none());
        assert_eq!(handler_calls.load(Ordering::Acquire), 1);
        assert_eq!(middleware_calls.load(Ordering::Acquire), 1);
        assert!(!saw_credential.load(Ordering::Acquire));

        let rejected = block_on(
            session.handle_async(
                &cx,
                modern_http_json_tool_request("modern_http_auth_counter", 932)
                    .with_header("authorization", "Bearer beta"),
            ),
        )
        .expect("a principal mismatch must be represented as JSON-RPC");
        let ServerHttpEndpointResponse::Immediate(rejected) = rejected else {
            panic!("principal mismatch must not admit an SSE body");
        };
        let rejected_wire = String::from_utf8_lossy(&rejected.body);
        let rejected: JsonRpcResponse =
            serde_json::from_slice(&rejected.body).expect("rejection must remain JSON-RPC");
        assert_eq!(rejected.id, Some(932_i64.into()));
        assert_eq!(
            rejected.error.map(|error| error.code),
            Some(i32::from(McpErrorCode::ResourceForbidden).into())
        );
        assert!(rejected.result.is_none());
        assert_eq!(
            handler_calls.load(Ordering::Acquire),
            1,
            "changing only alpha to beta must not invoke the handler",
        );
        assert_eq!(
            middleware_calls.load(Ordering::Acquire),
            1,
            "changing only alpha to beta must reject before middleware",
        );
        assert!(!saw_credential.load(Ordering::Acquire));
        assert!(!rejected_wire.contains("alpha") && !rejected_wire.contains("beta"));
    }

    #[test]
    fn public_http_modern_sse_authorization_fences_owned_dispatch_before_mutation() {
        let cx = Cx::for_testing();
        let handler_calls = Arc::new(AtomicUsize::new(0));
        let middleware_calls = Arc::new(AtomicUsize::new(0));
        let saw_credential = Arc::new(AtomicBool::new(false));
        let endpoint = Server::new("modern-http-sse-authorization", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .auth_provider(ModernHttpAuthProvider)
            .middleware(ModernHttpAuthMiddleware {
                calls: Arc::clone(&middleware_calls),
                saw_credential: Arc::clone(&saw_credential),
            })
            .tool(ModernHttpAuthCounterTool {
                calls: Arc::clone(&handler_calls),
            })
            .test_http_endpoint("http://final.test")
            .expect("modern endpoint must build");
        let mut session = endpoint
            .open_session(&cx)
            .expect("modern endpoint session must open");
        let request = |id, bearer| {
            modern_http_json_tool_request("modern_http_auth_counter", id)
                .with_header("accept", "text/event-stream")
                .with_header("authorization", format!("Bearer {bearer}"))
        };

        let ServerHttpEndpointResponse::ModernSse(allowed) =
            block_on(session.handle_async(&cx, request(933, "alpha")))
                .expect("allowed bearer must admit an owned SSE dispatch")
        else {
            panic!("SSE request must retain its owned response body");
        };
        assert!(matches!(
            Codec::new()
                .decode_complete_message(
                    allowed
                        .recv_event(&cx)
                        .expect("allowed SSE body must emit its terminal response")
                        .data
                        .as_bytes(),
                )
                .expect("allowed SSE response must remain JSON-RPC"),
            JsonRpcMessage::Response(response)
                if response.id == Some(933_i64.into()) && response.error.is_none()
        ));
        assert_eq!(handler_calls.load(Ordering::Acquire), 1);
        assert_eq!(middleware_calls.load(Ordering::Acquire), 1);

        let ServerHttpEndpointResponse::ModernSse(rejected) =
            block_on(session.handle_async(&cx, request(934, "beta")))
                .expect("principal mismatch must retain the protocol-selected SSE body")
        else {
            panic!("SSE admission must preserve its owned response path");
        };
        let rejected = rejected
            .recv_event(&cx)
            .expect("rejected owned dispatch must emit one terminal response");
        assert!(!rejected.data.contains("alpha") && !rejected.data.contains("beta"));
        assert!(matches!(
            Codec::new()
                .decode_complete_message(rejected.data.as_bytes())
                .expect("rejected SSE response must remain JSON-RPC"),
            JsonRpcMessage::Response(response)
                if response.id == Some(934_i64.into())
                    && response.error.as_ref().is_some_and(|error| {
                        error.code == i32::from(McpErrorCode::ResourceForbidden).into()
                    })
        ));
        assert_eq!(handler_calls.load(Ordering::Acquire), 1);
        assert_eq!(middleware_calls.load(Ordering::Acquire), 1);
        assert!(!saw_credential.load(Ordering::Acquire));
    }

    #[test]
    fn public_final_elicitation_projects_admitted_modes_without_mutating_on_rejection() {
        let calls = Arc::new(AtomicUsize::new(0));
        let server = Server::new("public-final-elicitation", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("modern-only policy is available")
            .tool(PublicFinalElicitationTool {
                name: "public-final-form-elicitation",
                mode: PublicFinalElicitationMode::Form,
                calls: Arc::clone(&calls),
            })
            .tool(PublicFinalElicitationTool {
                name: "public-final-url-elicitation",
                mode: PublicFinalElicitationMode::Url,
                calls: Arc::clone(&calls),
            })
            .build();
        let cx = Cx::for_testing();
        let connection = ModernConnection::new();
        let admitted_params = serde_json::json!({
            "name": "public-final-form-elicitation",
            "arguments": {},
            "_meta": {
                MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                FINAL_CLIENT_CAPABILITIES_META_KEY: {"elicitation": {"form": {}}},
            },
        });
        let admitted = block_on(server.dispatch_stateless(
            &InboundRequestContext::with_modern_connection(
                cx.clone(),
                950,
                InboundRequestTransport::Memory,
                &connection,
            ),
            &JsonRpcRequest::new("tools/call", Some(admitted_params.clone()), 950_i64),
        ))
        .expect("public final form elicitation must respond");
        assert!(admitted.error.is_none());
        assert_eq!(
            admitted
                .result
                .as_ref()
                .and_then(|result| result.get("resultType")),
            Some(&serde_json::json!("input_required"))
        );
        assert_eq!(
            admitted
                .result
                .as_ref()
                .and_then(|result| result.pointer("/inputRequests/approval/params/mode")),
            Some(&serde_json::json!("form"))
        );
        assert_eq!(calls.load(Ordering::Acquire), 1);
        let active_before_rejection = server.router.test_active_mrtr_exchange_count();
        assert_eq!(active_before_rejection, 1);

        let mut capability_removed = admitted_params.clone();
        let capabilities = capability_removed
            .pointer_mut("/_meta/io.modelcontextprotocol~1clientCapabilities")
            .and_then(serde_json::Value::as_object_mut)
            .expect("admitted fixture has a client capability object");
        let admitted_capability_count = capabilities.len();
        assert!(
            capabilities.remove("elicitation").is_some(),
            "the planted negative removes only the elicitation capability"
        );
        assert_eq!(capabilities.len() + 1, admitted_capability_count);
        let capability_rejected = block_on(server.dispatch_stateless(
            &InboundRequestContext::with_modern_connection(
                cx.clone(),
                951,
                InboundRequestTransport::Memory,
                &connection,
            ),
            &JsonRpcRequest::new("tools/call", Some(capability_removed), 951_i64),
        ))
        .expect("the capability-negative final request must respond");
        assert!(capability_rejected.error.is_none());
        let capability_rejected = capability_rejected
            .result
            .expect("a final tool refusal is a complete error result");
        assert_eq!(capability_rejected["resultType"], "complete");
        assert_eq!(capability_rejected["isError"], true);
        assert_eq!(
            server.router.test_active_mrtr_exchange_count(),
            active_before_rejection,
            "removing only client elicitation capability cannot mint or consume MRTR state"
        );
        assert_eq!(
            calls.load(Ordering::Acquire),
            2,
            "capability rejection occurs inside the handler's elicitation constructor without minting MRTR state"
        );

        let mut url_mismatch = admitted_params;
        url_mismatch["name"] = serde_json::json!("public-final-url-elicitation");
        let url_rejected = block_on(server.dispatch_stateless(
            &InboundRequestContext::with_modern_connection(
                cx,
                952,
                InboundRequestTransport::Memory,
                &connection,
            ),
            &JsonRpcRequest::new("tools/call", Some(url_mismatch), 952_i64),
        ))
        .expect("the form-only URL negative must respond");
        assert!(url_rejected.error.is_none());
        let url_rejected = url_rejected
            .result
            .expect("a final tool refusal is a complete error result");
        assert_eq!(url_rejected["resultType"], "complete");
        assert_eq!(url_rejected["isError"], true);
        assert_eq!(
            server.router.test_active_mrtr_exchange_count(),
            active_before_rejection,
            "a form-only client cannot mint URL elicitation state"
        );
        assert_eq!(
            calls.load(Ordering::Acquire),
            3,
            "mode rejection occurs inside the handler's elicitation constructor without minting MRTR state"
        );
    }

    #[test]
    fn public_final_sampling_projects_capability_and_preserves_tool_use_retry() {
        let handler_calls = Arc::new(AtomicUsize::new(0));
        let server = Server::new("public-final-sampling", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("modern-only policy is available")
            .tool(PublicFinalSamplingTool {
                calls: Arc::clone(&handler_calls),
            })
            .build();
        let cx = Cx::for_testing();
        let connection = ModernConnection::new();
        let admitted_params = serde_json::json!({
            "name": "public-final-sampling",
            "arguments": {},
            "_meta": {
                MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                FINAL_CLIENT_CAPABILITIES_META_KEY: {"sampling": {}},
            },
        });
        let initial = block_on(server.dispatch_stateless(
            &InboundRequestContext::with_modern_connection(
                cx.clone(),
                960,
                InboundRequestTransport::Memory,
                &connection,
            ),
            &JsonRpcRequest::new("tools/call", Some(admitted_params.clone()), 960_i64),
        ))
        .expect("public final sampling request must respond");
        assert!(initial.error.is_none());
        assert_eq!(
            initial
                .result
                .as_ref()
                .and_then(|result| result.get("resultType")),
            Some(&serde_json::json!("input_required"))
        );
        assert_eq!(
            initial
                .result
                .as_ref()
                .and_then(|result| result.pointer("/inputRequests/sample/method")),
            Some(&serde_json::json!("sampling/createMessage"))
        );
        assert_eq!(
            initial
                .result
                .as_ref()
                .and_then(|result| result.pointer("/inputRequests/sample/params/toolChoice/mode")),
            Some(&serde_json::json!("required"))
        );
        assert_eq!(
            initial
                .result
                .as_ref()
                .and_then(|result| result.pointer("/inputRequests/sample/params/tools/0/name")),
            Some(&serde_json::json!("weather"))
        );
        assert_eq!(
            initial.result.as_ref().and_then(|result| {
                result.pointer("/inputRequests/sample/params/messages/0/content/type")
            }),
            Some(&serde_json::json!("tool_use"))
        );
        let request_state = initial
            .result
            .as_ref()
            .and_then(|result| result.get("requestState"))
            .and_then(serde_json::Value::as_str)
            .expect("framework-issued final sampling state must be returned")
            .to_owned();
        let active_before_rejection = server.router.test_active_mrtr_exchange_count();
        assert_eq!(active_before_rejection, 1);
        assert_eq!(handler_calls.load(Ordering::Acquire), 1);

        let mut capability_removed = admitted_params.clone();
        let capabilities = capability_removed
            .pointer_mut("/_meta/io.modelcontextprotocol~1clientCapabilities")
            .and_then(serde_json::Value::as_object_mut)
            .expect("admitted fixture has a client capability object");
        let admitted_capability_count = capabilities.len();
        assert!(
            capabilities.remove("sampling").is_some(),
            "the planted RH-5 negative removes only sampling capability"
        );
        assert_eq!(capabilities.len() + 1, admitted_capability_count);
        let rejected = block_on(server.dispatch_stateless(
            &InboundRequestContext::with_modern_connection(
                cx.clone(),
                961,
                InboundRequestTransport::Memory,
                &connection,
            ),
            &JsonRpcRequest::new("tools/call", Some(capability_removed), 961_i64),
        ))
        .expect("the capability-negative final sampling request must respond");
        assert!(rejected.error.is_none());
        let rejected = rejected
            .result
            .expect("a final tool refusal is a complete error result");
        assert_eq!(rejected["resultType"], "complete");
        assert_eq!(rejected["isError"], true);
        assert_eq!(
            server.router.test_active_mrtr_exchange_count(),
            active_before_rejection,
            "removing only sampling capability cannot mint or consume MRTR state"
        );
        assert_eq!(
            handler_calls.load(Ordering::Acquire),
            1,
            "the removed capability must reject before this handler's post-admission mutation"
        );

        let mut retry_params = admitted_params;
        retry_params["inputResponses"] = serde_json::json!({
            "sample": {
                "content": {
                    "type": "tool_use",
                    "id": "weather-response",
                    "name": "weather",
                    "input": {"city": "Cambridge"},
                },
                "role": "assistant",
                "model": "test-model",
            },
        });
        retry_params["requestState"] = serde_json::json!(request_state);
        let resumed = block_on(server.dispatch_stateless(
            &InboundRequestContext::with_modern_connection(
                cx,
                962,
                InboundRequestTransport::Memory,
                &connection,
            ),
            &JsonRpcRequest::new("tools/call", Some(retry_params), 962_i64),
        ))
        .expect("an admitted final sampling retry must respond");
        assert!(resumed.error.is_none());
        assert_eq!(
            resumed
                .result
                .as_ref()
                .and_then(|result| result.get("resultType")),
            Some(&serde_json::json!("complete"))
        );
        assert_eq!(
            handler_calls.load(Ordering::Acquire),
            2,
            "the valid final tool-use response reaches exactly one resumed handler invocation"
        );
        assert_eq!(
            server.router.test_active_mrtr_exchange_count(),
            0,
            "only the admitted retry consumes the framework-owned request state"
        );
    }

    #[test]
    fn public_http_mrtr_cross_session_resume_is_bound_and_single_use() {
        let cx = Cx::for_testing();
        let calls = Arc::new(AtomicUsize::new(0));
        let endpoint = Server::new("modern-http-mrtr-stateless-resume", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .auth_provider(auth_00_mrtr_provider(true))
            .tool(LiveHttpMrtrTool {
                name: "live_http_mrtr",
                calls: Arc::clone(&calls),
            })
            .tool(LiveHttpMrtrTool {
                name: "other_live_http_mrtr",
                calls: Arc::clone(&calls),
            })
            .test_http_endpoint("http://final.test")
            .expect("modern endpoint must build");
        let mut issuing_client = endpoint
            .open_session(&cx)
            .expect("issuing modern HTTP session must open");
        let mut other_client = endpoint
            .open_session(&cx)
            .expect("independent modern HTTP session must open");
        let mut argument_client = endpoint
            .open_session(&cx)
            .expect("argument-negative modern HTTP session must open");
        let mut principal_client = endpoint
            .open_session(&cx)
            .expect("principal-negative modern HTTP session must open");
        let mut valid_client = endpoint
            .open_session(&cx)
            .expect("valid retry modern HTTP session must open");

        let initial = block_on(
            issuing_client.handle_async(
                &cx,
                modern_http_json_tool_request("live_http_mrtr", 906)
                    .with_header("authorization", "Bearer alpha"),
            ),
        )
        .expect("the issuing session must receive an input-required response");
        let ServerHttpEndpointResponse::Immediate(initial) = initial else {
            panic!("ordinary MRTR requests must return JSON responses");
        };
        let initial: JsonRpcResponse =
            serde_json::from_slice(&initial.body).expect("initial MRTR response must be JSON-RPC");
        let request_state = initial
            .result
            .as_ref()
            .and_then(|result| result.get("requestState"))
            .and_then(serde_json::Value::as_str)
            .expect("initial MRTR response must contain framework-issued state")
            .to_owned();
        assert_eq!(calls.load(Ordering::Acquire), 1);

        let roots = serde_json::to_value(
            bidirectional::MrtrInputResponse::roots(fastmcp_protocol::ListRootsResult::empty())
                .expect("MRTR roots response must construct"),
        )
        .expect("MRTR roots response must serialize");
        let retry =
            |state: &str, name: &str, arguments: serde_json::Value, id: i64, bearer: &str| {
                let request = JsonRpcRequest::new(
                    "tools/call",
                    Some(serde_json::json!({
                        "name": name,
                        "arguments": arguments,
                        "inputResponses": {"roots": roots.clone()},
                        "requestState": state,
                        "_meta": {
                            MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                            FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                        },
                    })),
                    id,
                );
                HttpRequest::new(HttpMethod::Post, "/mcp")
                    .with_header("content-type", "application/json")
                    .with_header("accept", "application/json")
                    .with_header("mcp-protocol-version", MODERN_PROTOCOL_VERSION)
                    .with_header("mcp-method", "tools/call")
                    .with_header("mcp-name", name)
                    .with_header("authorization", format!("Bearer {bearer}"))
                    .with_body(serde_json::to_vec(&request).expect("MRTR retry must encode"))
            };

        let forged_state = format!("{request_state}-foreign");
        let forged = block_on(issuing_client.handle_async(
            &cx,
            retry(
                &forged_state,
                "live_http_mrtr",
                serde_json::json!({}),
                907,
                "alpha",
            ),
        ))
        .expect("forged MRTR state must receive a JSON-RPC rejection");
        assert!(matches!(
            forged,
            ServerHttpEndpointResponse::Immediate(response)
                if serde_json::from_slice::<JsonRpcResponse>(&response.body).is_ok_and(|response| {
                    response.id == Some(907_i64.into()) && response.error.is_some()
                })
        ));
        assert_eq!(
            calls.load(Ordering::Acquire),
            1,
            "changing only requestState must not consume or resume the issued continuation",
        );
        assert_eq!(endpoint.server.router.test_active_mrtr_exchange_count(), 1);

        let target_mismatch = block_on(other_client.handle_async(
            &cx,
            retry(
                &request_state,
                "other_live_http_mrtr",
                serde_json::json!({}),
                908,
                "alpha",
            ),
        ))
        .expect("a target-mismatched MRTR retry must receive a JSON-RPC rejection");
        assert!(matches!(
            target_mismatch,
            ServerHttpEndpointResponse::Immediate(response)
                if serde_json::from_slice::<JsonRpcResponse>(&response.body).is_ok_and(|response| {
                    response.id == Some(908_i64.into()) && response.error.is_some()
                })
        ));
        assert_eq!(
            calls.load(Ordering::Acquire),
            1,
            "changing only the registered tool target must not reenter either handler",
        );
        assert_eq!(
            endpoint.server.router.test_active_mrtr_exchange_count(),
            1,
            "a target-binding rejection must leave the issued state available",
        );

        let argument_mismatch = block_on(argument_client.handle_async(
            &cx,
            retry(
                &request_state,
                "live_http_mrtr",
                serde_json::json!({"city": "Cambridge"}),
                909,
                "alpha",
            ),
        ))
        .expect("an argument-mismatched MRTR retry must receive a JSON-RPC rejection");
        assert!(matches!(
            argument_mismatch,
            ServerHttpEndpointResponse::Immediate(response)
                if serde_json::from_slice::<JsonRpcResponse>(&response.body).is_ok_and(|response| {
                    response.id == Some(909_i64.into()) && response.error.is_some()
                })
        ));
        assert_eq!(
            calls.load(Ordering::Acquire),
            1,
            "changing only valid arguments must not reenter the handler",
        );
        assert_eq!(
            endpoint.server.router.test_active_mrtr_exchange_count(),
            1,
            "an argument-binding rejection must leave the issued state available",
        );

        let principal_mismatch = block_on(principal_client.handle_async(
            &cx,
            retry(
                &request_state,
                "live_http_mrtr",
                serde_json::json!({}),
                910,
                "beta",
            ),
        ))
        .expect("a principal-mismatched MRTR retry must receive a JSON-RPC rejection");
        assert!(matches!(
            principal_mismatch,
            ServerHttpEndpointResponse::Immediate(response)
                if serde_json::from_slice::<JsonRpcResponse>(&response.body).is_ok_and(|response| {
                    response.id == Some(910_i64.into()) && response.error.is_some()
                })
        ));
        assert_eq!(
            calls.load(Ordering::Acquire),
            1,
            "changing only the authenticated principal must not reenter the handler",
        );
        assert_eq!(
            endpoint.server.router.test_active_mrtr_exchange_count(),
            1,
            "a principal-binding rejection must leave the issued state available",
        );

        let valid_retry = retry(
            &request_state,
            "live_http_mrtr",
            serde_json::json!({}),
            911,
            "alpha",
        );
        let resumed = block_on(valid_client.handle_async(&cx, valid_retry.clone()))
            .expect("a later stateless session with the bound request must resume");
        assert!(matches!(
            resumed,
            ServerHttpEndpointResponse::Immediate(response)
                if serde_json::from_slice::<JsonRpcResponse>(&response.body).is_ok_and(|response| {
                    response.id == Some(911_i64.into())
                        && response.error.is_none()
                        && response.result.as_ref().and_then(|result| result.get("resultType"))
                            == Some(&serde_json::json!("complete"))
                })
        ));
        assert_eq!(calls.load(Ordering::Acquire), 2);

        let replay = block_on(issuing_client.handle_async(&cx, valid_retry))
            .expect("a consumed MRTR state must receive a JSON-RPC rejection");
        assert!(matches!(
            replay,
            ServerHttpEndpointResponse::Immediate(response)
                if serde_json::from_slice::<JsonRpcResponse>(&response.body).is_ok_and(|response| {
                    response.id == Some(911_i64.into()) && response.error.is_some()
                })
        ));
        assert_eq!(
            calls.load(Ordering::Acquire),
            2,
            "replaying consumed requestState must not reenter the handler",
        );
        assert_eq!(endpoint.server.router.test_active_mrtr_exchange_count(), 0);
    }

    #[test]
    fn public_http_stateless_elicitation_retry_resumes_once_across_sessions() {
        let cx = Cx::for_testing();
        let calls = Arc::new(AtomicUsize::new(0));
        let endpoint = Server::new("modern-http-stateless-elicitation", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .auth_provider(auth_00_mrtr_provider(true))
            .tool(PublicFinalElicitationTool {
                name: "stateless-form-elicitation",
                mode: PublicFinalElicitationMode::Form,
                calls: Arc::clone(&calls),
            })
            .test_http_endpoint("http://final.test")
            .expect("modern endpoint must build");
        let mut issuing_client = endpoint
            .open_session(&cx)
            .expect("issuing modern HTTP session must open");
        let mut retrying_client = endpoint
            .open_session(&cx)
            .expect("independent modern HTTP session must open");
        let request = |request_state: Option<&str>, id: i64| {
            let mut params = serde_json::json!({
                "name": "stateless-form-elicitation",
                "arguments": {},
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {"elicitation": {"form": {}}},
                },
            });
            if let Some(request_state) = request_state {
                params["inputResponses"] = serde_json::json!({
                    "approval": {"action": "accept", "content": {"approved": true}},
                });
                params["requestState"] = serde_json::json!(request_state);
            }
            let request = JsonRpcRequest::new("tools/call", Some(params), id);
            HttpRequest::new(HttpMethod::Post, "/mcp")
                .with_header("content-type", "application/json")
                .with_header("accept", "application/json")
                .with_header("mcp-protocol-version", MODERN_PROTOCOL_VERSION)
                .with_header("mcp-method", "tools/call")
                .with_header("mcp-name", "stateless-form-elicitation")
                .with_header("authorization", "Bearer alpha")
                .with_body(serde_json::to_vec(&request).expect("elicitation request must encode"))
        };

        let initial = block_on(issuing_client.handle_async(&cx, request(None, 912)))
            .expect("stateless elicitation must return input_required");
        let ServerHttpEndpointResponse::Immediate(initial) = initial else {
            panic!("ordinary stateless elicitation must use the JSON response lane");
        };
        let initial: JsonRpcResponse =
            serde_json::from_slice(&initial.body).expect("initial response must be JSON-RPC");
        assert_eq!(initial.id, Some(912_i64.into()));
        assert!(initial.error.is_none());
        assert_eq!(
            initial
                .result
                .as_ref()
                .and_then(|result| result.get("resultType")),
            Some(&serde_json::json!("input_required"))
        );
        let request_state = initial
            .result
            .as_ref()
            .and_then(|result| result.get("requestState"))
            .and_then(serde_json::Value::as_str)
            .expect("initial elicitation result must carry requestState");
        assert_eq!(calls.load(Ordering::Acquire), 1);
        assert_eq!(endpoint.server.router.test_active_mrtr_exchange_count(), 1);

        // MCP 2026-07-28 MRTR: an elicitation answer is ordinary input data, so
        // a stateless retry from an independent HTTP session resumes the
        // operation exactly like sampling or roots input does.
        let resumed =
            block_on(retrying_client.handle_async(&cx, request(Some(request_state), 913)))
                .expect("stateless elicitation retry must receive a JSON-RPC response");
        let ServerHttpEndpointResponse::Immediate(resumed) = resumed else {
            panic!("stateless elicitation retry must use the JSON response lane");
        };
        let resumed: JsonRpcResponse =
            serde_json::from_slice(&resumed.body).expect("retry response must be JSON-RPC");
        assert_eq!(resumed.id, Some(913_i64.into()));
        assert!(
            resumed.error.is_none(),
            "stateless elicitation retry must resume, got {:?}",
            resumed.error
        );
        assert_eq!(
            calls.load(Ordering::Acquire),
            2,
            "an admitted retry re-enters the handler exactly once"
        );
        // This fixture asks again on every call, so the resumed round mints a
        // fresh state; the consumed one must not be reusable.
        let reissued_state = resumed
            .result
            .as_ref()
            .and_then(|result| result.get("requestState"))
            .and_then(serde_json::Value::as_str)
            .expect("the resumed round's input_required result carries a fresh requestState");
        assert_ne!(reissued_state, request_state);

        // Planted negative: replaying the consumed state is rejected before the
        // handler runs.
        let replayed =
            block_on(retrying_client.handle_async(&cx, request(Some(request_state), 914)))
                .expect("replayed elicitation retry must receive a JSON-RPC response");
        let ServerHttpEndpointResponse::Immediate(replayed) = replayed else {
            panic!("replayed elicitation retry must use the JSON response lane");
        };
        let replayed: JsonRpcResponse =
            serde_json::from_slice(&replayed.body).expect("replay response must be JSON-RPC");
        assert_eq!(replayed.id, Some(914_i64.into()));
        let error = replayed
            .error
            .expect("a consumed elicitation requestState must not resume twice");
        assert_eq!(error.code, McpErrorCode::InvalidParams.into());
        assert_eq!(error.message, "Invalid or expired MRTR request state");
        assert_eq!(
            calls.load(Ordering::Acquire),
            2,
            "a replay rejection must happen before handler reentry"
        );
    }

    #[test]
    fn public_http_request_scoped_progress_and_logging_use_owned_sse() {
        let cx = Cx::for_testing();
        let calls = Arc::new(AtomicUsize::new(0));
        let endpoint = Server::new("final-http-request-scoped", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .log_level(Level::Debug)
            .tool(HttpRequestScopedProgressTool {
                calls: Arc::clone(&calls),
            })
            .test_http_endpoint("http://final.test")
            .expect("modern endpoint must build");
        let mut session = endpoint
            .open_session(&cx)
            .expect("modern endpoint session must open");
        let request = JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({
                "name": "http_request_scoped_progress",
                "arguments": {},
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                    "progressToken": "final-http-progress",
                    "io.modelcontextprotocol/logLevel": "info",
                },
            })),
            811_i64,
        );
        let ServerHttpEndpointResponse::ModernSse(sse) = block_on(
            session.handle_async(
                &cx,
                HttpRequest::new(HttpMethod::Post, "/mcp")
                    .with_header("content-type", "application/json")
                    .with_header("accept", "application/json, text/event-stream; Q=1.")
                    .with_header("mcp-protocol-version", MODERN_PROTOCOL_VERSION)
                    .with_header("mcp-method", "tools/call")
                    .with_header("mcp-name", "http_request_scoped_progress")
                    .with_body(serde_json::to_vec(&request).expect("final request must encode")),
            ),
        )
        .expect("notification-capable modern request must dispatch over SSE") else {
            panic!("notification-capable modern request must select SSE");
        };

        let progress = sse
            .recv_event(&cx)
            .expect("progress must precede the terminal response");
        let JsonRpcMessage::Request(progress) = Codec::new()
            .decode_complete_message(progress.data.as_bytes())
            .expect("progress event must remain JSON-RPC")
        else {
            panic!("first request-scoped frame must be a progress notification");
        };
        let ServerNotification::Progress(progress) = ServerNotification::decode(&progress)
            .expect("progress must use the final server notification union")
        else {
            panic!("first request-scoped frame must be notifications/progress");
        };
        assert_eq!(
            progress.progress_token,
            ProgressMarker::String("final-http-progress".to_owned())
        );
        let progress_wire =
            serde_json::to_string(&progress).expect("coalesced final HTTP progress must serialize");
        assert!(progress_wire.contains("\"progress\":12000"));
        assert!(progress_wire.contains("\"total\":11999"));
        assert!(progress_wire.contains("\"message\":\"latest\""));

        let log = sse
            .recv_event(&cx)
            .expect("typed log must follow handler progress");
        let JsonRpcMessage::Request(log) = Codec::new()
            .decode_complete_message(log.data.as_bytes())
            .expect("log event must remain JSON-RPC")
        else {
            panic!("second request-scoped frame must be a log notification");
        };
        assert!(matches!(
            ServerNotification::decode(&log)
                .expect("log must use the final server notification union"),
            ServerNotification::Message(_)
        ));
        assert!(matches!(
            Codec::new()
                .decode_complete_message(
                    sse.recv_event(&cx)
                        .expect("terminal response must follow notifications")
                        .data
                        .as_bytes(),
                )
                .expect("terminal response must remain JSON-RPC"),
            JsonRpcMessage::Response(response)
                if response.id == Some(811_i64.into()) && response.error.is_none()
        ));
        assert_eq!(calls.load(Ordering::Acquire), 1);
    }

    #[test]
    fn http_sse_would_block_retries_preserve_progress_log_and_terminal_order() {
        let cx = Cx::for_testing();
        let request_cancellation = McpRequestCancellation::new();
        let commit_gate = Mutex::new(());
        let frames = Mutex::new(Vec::new());
        let attempts = AtomicUsize::new(0);

        for frame in ["progress", "log", "response"] {
            let _commit = commit_gate
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            retry_http_sse_commit(
                &cx,
                &request_cancellation,
                || {
                    if attempts.fetch_add(1, Ordering::AcqRel).is_multiple_of(2) {
                        return Err(TransportError::Io(std::io::Error::new(
                            std::io::ErrorKind::WouldBlock,
                            "forced final HTTP commit contention",
                        )));
                    }
                    frames
                        .lock()
                        .unwrap_or_else(std::sync::PoisonError::into_inner)
                        .push(frame);
                    Ok(())
                },
                retryable_http_sse_transport_error,
            )
            .expect("bounded transient contention must retry to its ordered commit");
        }

        assert_eq!(attempts.load(Ordering::Acquire), 6);
        assert_eq!(
            *frames
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner),
            vec!["progress", "log", "response"],
            "a forced WouldBlock must not reorder the serialized final frames",
        );
    }

    #[test]
    fn http_sse_would_block_retry_stops_at_the_bound() {
        let cx = Cx::for_testing();
        let request_cancellation = McpRequestCancellation::new();
        let attempts = AtomicUsize::new(0);
        let error = retry_http_sse_commit(
            &cx,
            &request_cancellation,
            || {
                attempts.fetch_add(1, Ordering::AcqRel);
                Err::<(), _>(TransportError::Io(std::io::Error::new(
                    std::io::ErrorKind::WouldBlock,
                    "permanently contended final HTTP commit",
                )))
            },
            retryable_http_sse_transport_error,
        )
        .expect_err("permanent contention must return instead of spinning forever");

        assert!(retryable_http_sse_transport_error(&error));
        assert_eq!(
            attempts.load(Ordering::Acquire),
            MAX_HTTP_SSE_COMMIT_RETRIES + 1,
            "the initial attempt plus the configured retry bound are exact",
        );
    }

    #[test]
    fn public_http_exhausted_progress_commit_retires_before_log_or_terminal_response() {
        let cx = Cx::for_testing();
        let endpoint = Server::new("final-http-progress-exhaustion", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .log_level(Level::Debug)
            .tool(HttpRequestScopedProgressTool {
                calls: Arc::new(AtomicUsize::new(0)),
            })
            .test_http_endpoint("http://final.test")
            .expect("modern endpoint must build");
        let mut session = endpoint
            .open_session(&cx)
            .expect("modern endpoint session must open");
        let request = JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({
                "name": "http_request_scoped_progress",
                "arguments": {},
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                    "progressToken": "final-http-exhaustion-progress",
                    "io.modelcontextprotocol/logLevel": "info",
                },
            })),
            813_i64,
        );

        set_forced_http_sse_would_block_commits(MAX_HTTP_SSE_COMMIT_RETRIES + 1);
        let result = block_on(
            session.handle_async(
                &cx,
                HttpRequest::new(HttpMethod::Post, "/mcp")
                    .with_header("content-type", "application/json")
                    .with_header("accept", "text/event-stream")
                    .with_header("mcp-protocol-version", MODERN_PROTOCOL_VERSION)
                    .with_header("mcp-method", "tools/call")
                    .with_header("mcp-name", "http_request_scoped_progress")
                    .with_body(serde_json::to_vec(&request).expect("final request must encode")),
            ),
        );
        let remaining = forced_http_sse_would_block_commits_remaining();
        set_forced_http_sse_would_block_commits(0);

        assert!(
            result.is_err(),
            "an exhausted public HTTP progress commit must retire instead of dropping progress and returning a log/response out of order"
        );
        assert_eq!(
            remaining, 0,
            "the public request must consume the initial attempt plus every bounded retry"
        );
    }

    #[test]
    fn public_http_final_progress_cancellation_discards_pending_update_and_log() {
        let cx = Cx::for_testing();
        let endpoint = Server::new("final-http-progress-cancellation", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .log_level(Level::Debug)
            .tool(HttpFinalProgressCancellationTool)
            .test_http_endpoint("http://final.test")
            .expect("modern endpoint must build");
        let mut session = endpoint
            .open_session(&cx)
            .expect("modern endpoint session must open");
        let request = JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({
                "name": "http_final_progress_cancellation",
                "arguments": {},
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                    "progressToken": "final-http-cancelled-progress",
                    "io.modelcontextprotocol/logLevel": "info",
                },
            })),
            812_i64,
        );
        let ServerHttpEndpointResponse::ModernSse(sse) = block_on(
            session.handle_async(
                &cx,
                HttpRequest::new(HttpMethod::Post, "/mcp")
                    .with_header("content-type", "application/json")
                    .with_header("accept", "text/event-stream")
                    .with_header("mcp-protocol-version", MODERN_PROTOCOL_VERSION)
                    .with_header("mcp-method", "tools/call")
                    .with_header("mcp-name", "http_final_progress_cancellation")
                    .with_body(serde_json::to_vec(&request).expect("final request must encode")),
            ),
        )
        .expect("cancelled modern request must retain its owned SSE body") else {
            panic!("cancelled modern request must select SSE");
        };

        assert!(matches!(
            Codec::new()
                .decode_complete_message(
                    sse.recv_event(&cx)
                        .expect("terminal cancellation response must be queued")
                        .data
                        .as_bytes(),
                )
                .expect("terminal cancellation response must remain JSON-RPC"),
            JsonRpcMessage::Response(response)
                if response.id == Some(812_i64.into())
                    && response
                        .error
                        .as_ref()
                        .is_some_and(|error| error.code.as_i32() == Some(i32::from(McpErrorCode::RequestCancelled)))
        ));
    }

    #[test]
    fn public_http_request_scoped_notifications_reject_only_zero_quality_sse() {
        let cx = Cx::for_testing();
        let calls = Arc::new(AtomicUsize::new(0));
        let endpoint = Server::new("final-http-request-scoped", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .log_level(Level::Debug)
            .tool(HttpRequestScopedProgressTool {
                calls: Arc::clone(&calls),
            })
            .test_http_endpoint("http://final.test")
            .expect("modern endpoint must build");
        let mut session = endpoint
            .open_session(&cx)
            .expect("modern endpoint session must open");
        let request = JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({
                "name": "http_request_scoped_progress",
                "arguments": {},
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                    "progressToken": "final-http-progress",
                    "io.modelcontextprotocol/logLevel": "info",
                },
            })),
            811_i64,
        );
        let request = HttpRequest::new(HttpMethod::Post, "/mcp")
            .with_header("content-type", "application/json")
            .with_header("mcp-protocol-version", MODERN_PROTOCOL_VERSION)
            .with_header("mcp-method", "tools/call")
            .with_header("mcp-name", "http_request_scoped_progress")
            .with_body(serde_json::to_vec(&request).expect("final request must encode"));
        for accept in [
            "application/json, text/event-stream; Q=0.",
            "text/event-stream;q=0, */*;q=1",
            "*/*;q=1, text/event-stream;q=0",
            "text/*;q=0, */*;q=1",
            "text/event-stream, text/event-stream;q=0, application/json",
        ] {
            let response =
                block_on(session.handle_async(&cx, request.clone().with_header("accept", accept)))
                    .expect("zero-quality SSE request must be rejected before dispatch");
            assert!(matches!(
                response,
                ServerHttpEndpointResponse::Immediate(response)
                    if response.status == HttpStatus::NOT_ACCEPTABLE && response.body.is_empty()
            ));
            assert_eq!(
                calls.load(Ordering::Acquire),
                0,
                "an SSE exclusion must prevent handler entry even with a wildcard: {accept}",
            );
        }

        // Change only the exact SSE quality. JSON remains preferred by the
        // wildcard, but a positive SSE weight permits this method's stream.
        let response = block_on(session.handle_async(
            &cx,
            request.with_header("accept", "text/event-stream;q=0.1, */*;q=1"),
        ))
        .expect("an accepted required SSE representation must dispatch after refusals");
        let ServerHttpEndpointResponse::ModernSse(sse) = response else {
            panic!("the notification-capable method requires its accepted SSE body");
        };
        let progress = sse.recv_event(&cx).expect("progress frame must be queued");
        let log = sse.recv_event(&cx).expect("log frame must be queued");
        let terminal = sse
            .recv_event(&cx)
            .expect("terminal response must be queued");
        assert!(matches!(
            Codec::new().decode_complete_message(progress.data.as_bytes()),
            Ok(JsonRpcMessage::Request(notification))
                if notification.method == "notifications/progress"
        ));
        assert!(matches!(
            Codec::new().decode_complete_message(log.data.as_bytes()),
            Ok(JsonRpcMessage::Request(notification))
                if notification.method == "notifications/message"
        ));
        assert!(matches!(
            Codec::new().decode_complete_message(terminal.data.as_bytes()),
            Ok(JsonRpcMessage::Response(response))
                if response.id == Some(811_i64.into()) && response.error.is_none()
        ));
        assert_eq!(calls.load(Ordering::Acquire), 1);
    }

    #[test]
    fn public_http_ordinary_json_request_remains_one_response() {
        let cx = Cx::for_testing();
        let calls = Arc::new(AtomicUsize::new(0));
        let endpoint = Server::new("final-http-json-only", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .tool(HttpRequestScopedProgressTool {
                calls: Arc::clone(&calls),
            })
            .test_http_endpoint("http://final.test")
            .expect("modern endpoint must build");
        let mut session = endpoint
            .open_session(&cx)
            .expect("modern endpoint session must open");
        let request = JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({
                "name": "http_request_scoped_progress",
                "arguments": {},
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                },
            })),
            812_i64,
        );
        let response = block_on(
            session.handle_async(
                &cx,
                HttpRequest::new(HttpMethod::Post, "/mcp")
                    .with_header("content-type", "application/json")
                    .with_header("accept", "application/json")
                    .with_header("mcp-protocol-version", MODERN_PROTOCOL_VERSION)
                    .with_header("mcp-method", "tools/call")
                    .with_header("mcp-name", "http_request_scoped_progress")
                    .with_body(serde_json::to_vec(&request).expect("final request must encode")),
            ),
        )
        .expect("ordinary JSON-only request must dispatch");
        let ServerHttpEndpointResponse::Immediate(response) = response else {
            panic!("ordinary JSON-only request must retain its one-response representation");
        };
        assert!(matches!(
            Codec::new()
                .decode_complete_message(&response.body)
                .expect("JSON-only response must remain JSON-RPC"),
            JsonRpcMessage::Response(response)
                if response.id == Some(812_i64.into()) && response.error.is_none()
        ));
        assert_eq!(calls.load(Ordering::Acquire), 1);
    }

    #[test]
    fn final_runtime_emits_typed_log_message_with_server_metadata() {
        let cx = Cx::for_testing();
        let endpoint = Server::new("final-log-runtime", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .log_level(Level::Debug)
            .test_http_endpoint("http://final.test")
            .expect("modern endpoint must build");
        let mut session = endpoint
            .open_session(&cx)
            .expect("modern endpoint session must open");
        let request = JsonRpcRequest::new(
            "tools/list",
            Some(serde_json::json!({
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                    "io.modelcontextprotocol/logLevel": "info",
                },
            })),
            91_i64,
        );
        let ServerHttpEndpointResponse::ModernSse(sse) = block_on(
            session.handle_async(
                &cx,
                HttpRequest::new(HttpMethod::Post, "/mcp")
                    .with_header("content-type", "application/json")
                    .with_header("accept", "text/event-stream")
                    .with_header("mcp-protocol-version", MODERN_PROTOCOL_VERSION)
                    .with_header("mcp-method", "tools/list")
                    .with_body(serde_json::to_vec(&request).expect("final request must encode")),
            ),
        )
        .expect("public modern request must dispatch") else {
            panic!("public modern request must return an SSE body");
        };
        let log = sse
            .recv_event(&cx)
            .expect("typed final log must arrive before the response");
        let JsonRpcMessage::Request(log) = Codec::new()
            .decode_complete_message(log.data.as_bytes())
            .expect("typed final log must remain JSON-RPC")
        else {
            panic!("first SSE frame must be a typed final log notification");
        };
        let ServerNotification::Message(message) = ServerNotification::decode(&log)
            .expect("final runtime logging must use the typed final notification union")
        else {
            panic!("final runtime must emit notifications/message");
        };
        assert_eq!(message.level, LoggingLevel::Info);
        assert_eq!(message.logger.as_deref(), Some("fastmcp_rust::server"));
        assert_eq!(
            message
                .meta
                .as_ref()
                .and_then(|meta| meta.server_info().ok().flatten())
                .map(|info| info.name),
            Some("final-log-runtime".to_owned()),
            "typed final logging must retain final server metadata",
        );
        assert!(matches!(
            Codec::new()
                .decode_complete_message(
                    sse.recv_event(&cx)
                        .expect("request response must follow the log")
                        .data
                        .as_bytes(),
                )
                .expect("response must remain JSON-RPC"),
            JsonRpcMessage::Response(response)
                if response.id == Some(91_i64.into()) && response.error.is_none()
        ));
    }

    #[test]
    fn final_runtime_suppresses_info_log_when_only_log_level_changes_to_warning() {
        let cx = Cx::for_testing();
        let endpoint = Server::new("final-log-runtime", "1.0.0")
            .protocol_policy(ProtocolPolicy::ModernOnly)
            .expect("ModernOnly must be available to this test build")
            .log_level(Level::Debug)
            .test_http_endpoint("http://final.test")
            .expect("modern endpoint must build");
        let mut session = endpoint
            .open_session(&cx)
            .expect("modern endpoint session must open");
        let request = JsonRpcRequest::new(
            "tools/list",
            Some(serde_json::json!({
                "_meta": {
                    MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                    "io.modelcontextprotocol/logLevel": "warning",
                },
            })),
            91_i64,
        );
        let ServerHttpEndpointResponse::ModernSse(sse) = block_on(
            session.handle_async(
                &cx,
                HttpRequest::new(HttpMethod::Post, "/mcp")
                    .with_header("content-type", "application/json")
                    .with_header("accept", "text/event-stream")
                    .with_header("mcp-protocol-version", MODERN_PROTOCOL_VERSION)
                    .with_header("mcp-method", "tools/list")
                    .with_body(serde_json::to_vec(&request).expect("final request must encode")),
            ),
        )
        .expect("public modern request must dispatch") else {
            panic!("public modern request must return an SSE body");
        };
        assert!(
            matches!(
                Codec::new()
                    .decode_complete_message(
                        sse.recv_event(&cx)
                            .expect("request response must remain readable")
                            .data
                            .as_bytes(),
                    )
                    .expect("response must remain JSON-RPC"),
                JsonRpcMessage::Response(response)
                    if response.id == Some(91_i64.into()) && response.error.is_none()
            ),
            "changing only final logLevel from info to warning must suppress the info notification"
        );
        // The dispatch task owns the response sender, so a completed request
        // may legitimately close the body afterwards; the negative's
        // invariant is only that no suppressed notification was queued.
        assert!(
            !matches!(sse.pop_event(), Ok(Some(_))),
            "the log-level-only negative must leave no notification queued"
        );
    }

    #[test]
    fn public_stdio_peer_close_removes_without_terminal_completion() {
        // This mirrors the server-teardown positive above; only the terminal
        // authority changes from server termination to peer closure.
        let server = Arc::new(Server::new("final-listen-peer-cancel-test", "1.0.0").build());
        let sent = Arc::new(Mutex::new(Vec::<JsonRpcRequest>::new()));
        let sent_for_sender = Arc::clone(&sent);
        let (acknowledged, acknowledgement) = std::sync::mpsc::channel::<()>();
        let notification_sender: NotificationSender = Arc::new(move |notification| {
            sent_for_sender
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(notification);
            let _ = acknowledged.send(());
        });
        let subscription_id = RequestId::Number(74);
        let metadata = OpenMetadata::try_from_entries([
            (
                "io.modelcontextprotocol/protocolVersion".to_owned(),
                serde_json::json!(MODERN_PROTOCOL_VERSION),
            ),
            (
                FINAL_CLIENT_CAPABILITIES_META_KEY.to_owned(),
                serde_json::json!({}),
            ),
        ])
        .expect("final request metadata must be valid");
        let params = serde_json::to_value(FinalSubscriptionsListenParams {
            meta: metadata,
            notifications: SubscriptionFilter {
                tools_list_changed: Some(true),
                ..SubscriptionFilter::default()
            },
        })
        .expect("final listen parameters must serialize");
        let request =
            JsonRpcRequest::new(SUBSCRIPTIONS_LISTEN, Some(params), subscription_id.clone());
        let inbound = InboundRequestContext::new(
            Cx::for_testing(),
            request_id_to_u64(Some(&subscription_id)),
            InboundRequestTransport::Stdio,
        );
        let request_cancellation = McpRequestCancellation::new();
        // The peer closes the stream once the listener acknowledges. Waiting
        // is bounded in runnable time, so a loaded suite cannot expire it
        // while a missing acknowledgement still does. The peer closes either
        // way, so the dispatch always ends and the assertion reports the wait.
        let canceller = {
            let request_cancellation = request_cancellation.clone();
            let host = RunnableClock::start();
            std::thread::spawn(move || {
                let started = host.mark();
                let outcome = loop {
                    match acknowledgement.recv_timeout(Duration::from_millis(20)) {
                        Ok(()) => break Ok(()),
                        Err(std::sync::mpsc::RecvTimeoutError::Timeout)
                            if !host.expired(started, Duration::from_secs(10)) => {}
                        Err(error) => {
                            break Err(format!("{error} after {}", host.describe(started)));
                        }
                    }
                };
                request_cancellation.cancel();
                outcome
            })
        };
        let response = block_on(Arc::clone(&server).dispatch_with_protocol_policy_owned(
            ProtocolPolicy::ModernOnly,
            &inbound,
            request,
            None,
            None,
            None,
            None,
            request_cancellation,
            None,
            notification_sender,
        ));

        if let Err(waited) = canceller
            .join()
            .expect("peer cancellation helper must not panic")
        {
            panic!("the listener must acknowledge before the peer can close it: {waited}");
        }
        assert!(
            response.is_none(),
            "a peer-closed stream must not receive a result"
        );
        assert_eq!(
            sent.lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .len(),
            1,
            "changing only the terminal trigger to peer cancellation must not send server cancellation control",
        );
        assert!(
            server
                .final_subscriptions
                .inner
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .entries
                .is_empty(),
            "peer cancellation must release exactly its request-owned registry entry",
        );
    }

    #[test]
    fn final_subscription_termination_is_single_winner_and_idempotent() {
        let registry = Arc::new(FinalSubscriptionRegistry::default());
        let sent = Arc::new(Mutex::new(Vec::<JsonRpcRequest>::new()));
        let sent_for_sender = Arc::clone(&sent);
        let sender: NotificationSender = Arc::new(move |notification| {
            sent_for_sender
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(notification);
        });
        let cancellation = McpRequestCancellation::new();
        let _lease = registry
            .open(
                RequestId::Number(881),
                SubscriptionFilter::default(),
                false,
                None,
                cancellation.clone(),
                None,
                sender,
            )
            .expect("a final listen must register before termination");

        assert_eq!(registry.terminate(), 1);
        assert_eq!(registry.terminate(), 0);
        assert!(cancellation.is_cancel_requested());
        let sent = sent
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        assert_eq!(sent.len(), 2, "one acknowledgement and one control only");
        assert!(matches!(
            ServerNotification::decode(&sent[1]),
            Ok(ServerNotification::Cancelled(_))
        ));
    }

    #[test]
    fn final_subscription_stdio_shutdown_receipt_waits_for_terminal_consumption() {
        let registry = Arc::new(FinalSubscriptionRegistry::default());
        let terminal_delivery = Arc::new(FinalSubscriptionTerminalDelivery::default());
        let sender: NotificationSender = Arc::new(|_| {});
        let _lease = registry
            .open(
                RequestId::Number(887),
                SubscriptionFilter::default(),
                false,
                None,
                McpRequestCancellation::new(),
                Some(Arc::clone(&terminal_delivery)),
                sender,
            )
            .expect("a final listen must register before termination");

        let receipt = registry.terminate_with_receipt();
        assert_eq!(receipt.terminated, 1);
        assert!(
            !receipt.is_settled(),
            "queue admission alone must not masquerade as body consumption"
        );

        terminal_delivery.mark_drained();
        assert!(
            !receipt.is_settled(),
            "terminal control consumption must not stand in for final completion delivery"
        );
        terminal_delivery.mark_completion_enqueued();
        terminal_delivery.mark_completion_drained();
        assert!(receipt.is_settled());
    }

    #[test]
    fn cancelled_http_writer_fails_an_open_completion_so_dual_listen_drain_can_settle() {
        let delivery = FinalSubscriptionTerminalDelivery::default();
        delivery.mark_control_not_required();
        assert!(
            !delivery.is_settled(),
            "an unelected complete must keep the drain receipt open"
        );
        delivery.mark_failed();
        assert!(
            delivery.is_settled(),
            "a cancelled connection region must settle instead of burning the drain bound"
        );
    }

    #[test]
    fn cancelled_http_writer_fails_after_stream_election_without_a_control_frame() {
        let delivery = FinalSubscriptionTerminalDelivery::default();
        delivery.mark_control_not_required();
        assert!(
            delivery.is_committed(),
            "control-not-required is the committed control half so a cancelled request stays live until complete"
        );
        assert!(
            !delivery.is_settled(),
            "an unelected complete must keep the drain receipt open"
        );
        delivery.mark_failed();
        assert!(
            delivery.is_settled(),
            "as_proxy dual listen drain must settle when the peer drops after Stream"
        );
    }

    #[test]
    fn final_subscription_stdio_shutdown_receipt_fails_closed_after_backpressure_bound() {
        let registry = Arc::new(FinalSubscriptionRegistry::default());
        let terminal_delivery = Arc::new(FinalSubscriptionTerminalDelivery::default());
        let sender: NotificationSender = Arc::new(|_| {});
        let _lease = registry
            .open(
                RequestId::Number(888),
                SubscriptionFilter::default(),
                false,
                None,
                McpRequestCancellation::new(),
                Some(Arc::clone(&terminal_delivery)),
                sender,
            )
            .expect("a final listen must register before termination");

        let receipt = registry.terminate_with_receipt();
        assert!(!receipt.is_settled());
        receipt.fail_pending();
        assert!(
            receipt.is_settled(),
            "bounded shutdown must turn an unconsumed terminal into an explicit failure"
        );
        assert!(!terminal_delivery.is_drained());
    }

    #[test]
    fn modern_http_writer_exit_without_complete_fails_a_graceful_election_receipt() {
        let delivery = FinalSubscriptionTerminalDelivery::default();
        delivery.mark_control_not_required();
        assert!(
            delivery.is_committed(),
            "control-not-required is the committed control half; the H1 writer must keep waiting for complete"
        );
        assert!(
            !delivery.is_settled(),
            "an elected complete that was never flushed must not settle the receipt"
        );
        delivery.mark_failed();
        assert!(
            delivery.is_settled(),
            "an H1 writer that closes without flushing complete must fail the receipt immediately"
        );
    }

    #[test]
    fn final_subscription_peer_cancellation_wins_before_shutdown_without_control() {
        let registry = Arc::new(FinalSubscriptionRegistry::default());
        let sent = Arc::new(Mutex::new(Vec::<JsonRpcRequest>::new()));
        let sent_for_sender = Arc::clone(&sent);
        let sender: NotificationSender = Arc::new(move |notification| {
            sent_for_sender
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(notification);
        });
        let cancellation = McpRequestCancellation::new();
        let lease = registry
            .open(
                RequestId::String("peer-wins-882".to_owned()),
                SubscriptionFilter {
                    tools_list_changed: Some(true),
                    ..SubscriptionFilter::default()
                },
                false,
                Some(882),
                cancellation.clone(),
                None,
                sender,
            )
            .expect("a modern HTTP listen must register");

        assert!(registry.cancel_modern_http_owner(882));
        assert!(!registry.cancel_modern_http_owner(882));
        assert_eq!(
            registry
                .publish(ServerNotification::ToolsListChanged(None))
                .expect("post-terminal publication remains well-formed"),
            0,
            "a snapshotted entry cannot publish after its peer terminal election",
        );
        assert_eq!(registry.terminate(), 0);
        assert!(cancellation.is_cancel_requested());
        assert_eq!(
            sent.lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .len(),
            1,
            "peer winner leaves only the mandatory acknowledgement"
        );
        drop(lease);
    }

    #[test]
    fn final_subscription_peer_token_prevents_immediate_publication_and_shutdown_callbacks() {
        let registry = Arc::new(FinalSubscriptionRegistry::default());
        let sent = Arc::new(Mutex::new(Vec::<JsonRpcRequest>::new()));
        let sent_for_sender = Arc::clone(&sent);
        let sender: NotificationSender = Arc::new(move |notification| {
            sent_for_sender
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(notification);
        });
        let cancellation = McpRequestCancellation::new();
        let _lease = registry
            .open(
                RequestId::Number(885),
                SubscriptionFilter {
                    tools_list_changed: Some(true),
                    ..SubscriptionFilter::default()
                },
                false,
                Some(885),
                cancellation.clone(),
                None,
                sender,
            )
            .expect("a final listen must acknowledge before peer cancellation");

        cancellation.cancel();
        assert_eq!(
            registry
                .publish(ServerNotification::ToolsListChanged(None))
                .expect("peer-cancelled publication remains well-formed"),
            0,
            "a peer-cancelled token must stop the callback before lease cleanup",
        );
        assert_eq!(registry.terminate(), 0);
        assert_eq!(
            sent.lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .len(),
            1,
            "peer cancellation leaves only the acknowledgement",
        );
    }

    #[test]
    fn final_subscription_callback_cancellation_is_not_counted_as_delivery() {
        let registry = Arc::new(FinalSubscriptionRegistry::default());
        let sent = Arc::new(Mutex::new(Vec::<JsonRpcRequest>::new()));
        let cancellation = McpRequestCancellation::new();
        let sent_for_sender = Arc::clone(&sent);
        let cancellation_for_sender = cancellation.clone();
        let sender: NotificationSender = Arc::new(move |notification| {
            let mut sent = sent_for_sender
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if !sent.is_empty() {
                cancellation_for_sender.cancel();
            }
            sent.push(notification);
        });
        let _lease = registry
            .open(
                RequestId::Number(886),
                SubscriptionFilter {
                    tools_list_changed: Some(true),
                    ..SubscriptionFilter::default()
                },
                false,
                Some(886),
                cancellation,
                None,
                sender,
            )
            .expect("a final listen must acknowledge before callback cancellation");

        assert_eq!(
            registry
                .publish(ServerNotification::ToolsListChanged(None))
                .expect("callback cancellation remains a well-formed publication"),
            0,
            "a callback that observes peer closure must not report a delivery",
        );
        assert_eq!(registry.terminate(), 0);
        assert_eq!(
            sent.lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .len(),
            2,
            "the attempted event is retained by this planted sender, but no terminal control follows",
        );
    }

    #[test]
    fn final_subscription_open_acknowledgement_is_atomic_with_termination() {
        let registry = Arc::new(FinalSubscriptionRegistry::default());
        let gate = Arc::new((Mutex::new((false, false)), Condvar::new()));
        let sent = Arc::new(Mutex::new(Vec::<JsonRpcRequest>::new()));
        let sender_gate = Arc::clone(&gate);
        let sender_sent = Arc::clone(&sent);
        let sender: NotificationSender = Arc::new(move |notification| {
            let (lock, ready) = &*sender_gate;
            let mut state = lock
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner);
            if !state.0 {
                state.0 = true;
                ready.notify_all();
                while !state.1 {
                    state = ready
                        .wait(state)
                        .unwrap_or_else(std::sync::PoisonError::into_inner);
                }
            }
            drop(state);
            sender_sent
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .push(notification);
        });
        let cancellation = McpRequestCancellation::new();
        let opener_registry = Arc::clone(&registry);
        let opener_cancellation = cancellation.clone();
        let opener = thread::spawn(move || {
            opener_registry.open(
                RequestId::Number(883),
                SubscriptionFilter {
                    tools_list_changed: Some(true),
                    ..SubscriptionFilter::default()
                },
                false,
                Some(883),
                opener_cancellation,
                None,
                sender,
            )
        });

        let (lock, ready) = &*gate;
        let mut state = lock
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        while !state.0 {
            state = ready
                .wait(state)
                .unwrap_or_else(std::sync::PoisonError::into_inner);
        }
        drop(state);

        assert_eq!(
            registry
                .publish(ServerNotification::ToolsListChanged(None))
                .expect("publication during a held acknowledgement must be admitted"),
            1,
        );

        let (started_sender, started_receiver) = sync_channel(1);
        let (terminated_sender, terminated_receiver) = sync_channel(1);
        let terminator_registry = Arc::clone(&registry);
        let terminator = thread::spawn(move || {
            let _ = started_sender.send(());
            let _ = terminated_sender.send(terminator_registry.terminate());
        });
        started_receiver
            .recv()
            .expect("terminator must reach the teardown attempt");
        let deadline = Instant::now() + Duration::from_secs(1);
        while !registry.is_terminating() {
            assert!(
                Instant::now() < deadline,
                "terminator did not begin while acknowledgement was held"
            );
            thread::yield_now();
        }
        assert_eq!(
            terminated_receiver
                .recv()
                .expect("terminator must report its winner count"),
            1,
            "shutdown must claim the opening entry without waiting on its acknowledgement callback"
        );
        terminator.join().expect("terminator must not panic");
        assert!(
            !cancellation.is_cancel_requested(),
            "shutdown must not wake the opener before its acknowledgement callback returns"
        );
        assert!(
            registry
                .inner
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .entries
                .is_empty(),
            "teardown must remove an opening entry without waiting on its callback"
        );

        let mut state = lock
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        state.1 = true;
        ready.notify_all();
        drop(state);

        let lease = opener
            .join()
            .expect("subscription opener must not panic")
            .expect("the shutdown winner must finish the acknowledged stream gracefully");
        assert!(lease.has_graceful_completion());
        assert!(
            cancellation.is_cancel_requested(),
            "the acknowledged opener wakes only after graceful completion wins"
        );
        assert_eq!(
            sent.lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .len(),
            1,
            "server termination must discard the queued event and modern HTTP emits no stdio cancellation control"
        );
    }

    #[test]
    fn sse_body_observation_treats_only_mailbox_contention_as_pending() {
        let busy = DualEraHttpEndpointError::Transport(TransportError::Io(std::io::Error::new(
            std::io::ErrorKind::WouldBlock,
            "streamable response mailbox is busy",
        )));
        assert!(matches!(sse_body_observation(Err(busy)), Ok(None)));
        // Near-identical negative: the same transport I/O failure of another
        // kind is a real body failure and must still end the stream.
        let broken = DualEraHttpEndpointError::Transport(TransportError::Io(std::io::Error::new(
            std::io::ErrorKind::BrokenPipe,
            "streamable response mailbox is busy",
        )));
        assert!(matches!(
            sse_body_observation(Err(broken)),
            Err(DualEraHttpEndpointError::Transport(TransportError::Io(error)))
                if error.kind() == std::io::ErrorKind::BrokenPipe
        ));
    }

    /// bd-a8tbq: a live writer read its body while a handler committed a
    /// notification, saw the mailbox busy, and dropped the listen connection.
    #[test]
    fn live_listen_body_reader_survives_concurrent_notification_commits() {
        const COMMITS: usize = 2_000;
        run_live_http_test(|cx| async move {
            let endpoint = Server::new("public-http-listen-contention", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .test_http_endpoint("http://legacy.test")
                .map_err(|error| format!("public endpoint setup failed: {error}"))?;
            let mut session = endpoint
                .open_session(&cx)
                .map_err(|error| format!("public listen session failed: {error}"))?;
            let listen = JsonRpcRequest::new(
                SUBSCRIPTIONS_LISTEN,
                Some(serde_json::json!({
                    "_meta": {
                        MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                        FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                    },
                    "notifications": {"toolsListChanged": true},
                })),
                RequestId::Number(885),
            );
            let request = HttpRequest::new(HttpMethod::Post, "/mcp")
                .with_header("content-type", "application/json")
                .with_header("accept", "text/event-stream")
                .with_header("mcp-protocol-version", MODERN_PROTOCOL_VERSION)
                .with_header("mcp-method", SUBSCRIPTIONS_LISTEN)
                .with_body(
                    serde_json::to_vec(&listen).expect("typed listen request must serialize"),
                );
            let ServerHttpEndpointResponse::ModernSse(sse) = session
                .handle_async(&cx, request)
                .await
                .map_err(|error| format!("public listen failed: {error}"))?
            else {
                return Err("public listen did not return SSE".to_owned());
            };
            let deadline = Instant::now() + Duration::from_secs(2);
            loop {
                match sse.pop_event() {
                    Ok(Some(_acknowledgement)) => break,
                    Ok(None) if Instant::now() < deadline => {
                        asupersync::time::sleep(cx.now(), Duration::from_millis(1)).await;
                    }
                    Ok(None) => return Err("public listen acknowledgement timed out".to_owned()),
                    Err(error) => return Err(format!("public listen closed early: {error}")),
                }
            }

            // Commit from another thread while this one keeps reading, so the
            // two sides contend for the response mailbox as a live handler
            // and the listen writer do.
            let sender = sse.inner.sender();
            let producer = thread::spawn(move || {
                let cx = Cx::for_testing();
                for index in 0..COMMITS {
                    let notification = JsonRpcRequest::notification(
                        "notifications/resources/updated",
                        Some(serde_json::json!({"uri": format!("file:///contention/{index}")})),
                    );
                    loop {
                        match sender.send_notification(&cx, notification.clone()) {
                            Ok(()) => break,
                            Err(error) if retryable_http_sse_transport_error(&error) => {
                                thread::yield_now();
                            }
                            Err(error) => return Err(format!("commit {index} failed: {error}")),
                        }
                    }
                }
                Ok(())
            });
            let mut received = 0;
            let deadline = Instant::now() + Duration::from_secs(20);
            while received < COMMITS {
                match pop_sse_body_event(&sse.inner) {
                    Ok(Some(_)) => received += 1,
                    Ok(None) if Instant::now() < deadline => thread::yield_now(),
                    Ok(None) => {
                        return Err(format!(
                            "only {received} of {COMMITS} commits were observed"
                        ));
                    }
                    Err(error) => {
                        return Err(format!(
                            "contention ended the live body after {received} events: {error}"
                        ));
                    }
                }
            }
            producer
                .join()
                .map_err(|_| "notification producer panicked".to_owned())??;
            Ok(())
        });
    }

    #[test]
    fn public_http_response_body_drop_cancels_only_its_owned_listen() {
        run_live_http_test(|cx| async move {
            let endpoint = Server::new("public-http-listen", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .test_http_endpoint("http://legacy.test")
                .map_err(|error| format!("public endpoint setup failed: {error}"))?;
            let mut first_session = endpoint
                .open_session(&cx)
                .map_err(|error| format!("first public listen session failed: {error}"))?;
            let mut second_session = endpoint
                .open_session(&cx)
                .map_err(|error| format!("second public listen session failed: {error}"))?;
            let listen_request = || {
                let listen = JsonRpcRequest::new(
                    SUBSCRIPTIONS_LISTEN,
                    Some(serde_json::json!({
                        "_meta": {
                            MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                            FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                        },
                        "notifications": {"toolsListChanged": true},
                    })),
                    RequestId::Number(884),
                );
                HttpRequest::new(HttpMethod::Post, "/mcp")
                    .with_header("content-type", "application/json")
                    .with_header("accept", "text/event-stream")
                    .with_header("mcp-protocol-version", MODERN_PROTOCOL_VERSION)
                    .with_header("mcp-method", SUBSCRIPTIONS_LISTEN)
                    .with_body(
                        serde_json::to_vec(&listen).expect("typed listen request must serialize"),
                    )
            };
            let first = first_session
                .handle_async(&cx, listen_request())
                .await
                .map_err(|error| format!("first public listen failed: {error}"))?;
            let second = second_session
                .handle_async(&cx, listen_request())
                .await
                .map_err(|error| format!("second public listen failed: {error}"))?;
            let ServerHttpEndpointResponse::ModernSse(first_sse) = first else {
                return Err("first public listen did not return SSE".to_owned());
            };
            let ServerHttpEndpointResponse::ModernSse(second_sse) = second else {
                return Err("second public listen did not return SSE".to_owned());
            };
            let first_guard = first_sse.cancellation();
            let second_guard = second_sse.cancellation();
            let deadline = Instant::now() + Duration::from_secs(2);
            for sse in [&first_sse, &second_sse] {
                loop {
                    match sse.pop_event() {
                        Ok(Some(_acknowledgement)) => break,
                        Ok(None) if Instant::now() < deadline => {
                            asupersync::time::sleep(cx.now(), Duration::from_millis(1)).await;
                        }
                        Ok(None) => {
                            return Err("public listen acknowledgement timed out".to_owned());
                        }
                        Err(error) => return Err(format!("public listen closed early: {error}")),
                    }
                }
            }
            if first_guard.checkpoint(&cx).is_err() || second_guard.checkpoint(&cx).is_err() {
                return Err("an acknowledged response body was not pending".to_owned());
            }

            let mut rejected_session = endpoint
                .open_session(&cx)
                .map_err(|error| format!("rejected cancellation session failed: {error}"))?;
            let cancellation = JsonRpcRequest::notification(
                "notifications/cancelled",
                Some(serde_json::json!({
                    "requestId": 884,
                    "_meta": {
                        MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                    },
                })),
            );
            let rejected = rejected_session
                .handle_async(
                    &cx,
                    HttpRequest::new(HttpMethod::Post, "/mcp")
                        .with_header("content-type", "application/json")
                        .with_header("accept", "application/json")
                        .with_header("mcp-protocol-version", MODERN_PROTOCOL_VERSION)
                        .with_header("mcp-method", "notifications/cancelled")
                        .with_body(
                            serde_json::to_vec(&cancellation)
                                .expect("typed cancellation notification must serialize"),
                        ),
                )
                .await
                .map_err(|error| format!("cancellation rejection failed: {error}"))?;
            let ServerHttpEndpointResponse::Immediate(rejected) = rejected else {
                return Err(
                    "HTTP cancellation notification was not rejected immediately".to_owned(),
                );
            };
            // Accepted with 202 (a notification), yet it carries no authority
            // over either in-flight response body.
            if rejected.status != HttpStatus::ACCEPTED
                || first_guard.checkpoint(&cx).is_err()
                || second_guard.checkpoint(&cx).is_err()
            {
                return Err("HTTP cancellation POST affected a response body".to_owned());
            }

            let mut streaming_rejected_session = endpoint
                .open_session(&cx)
                .map_err(|error| format!("streaming cancellation session failed: {error}"))?;
            let streaming_rejected = streaming_rejected_session
                .begin_modern_sse(
                    &cx,
                    HttpRequest::new(HttpMethod::Post, "/mcp")
                        .with_header("content-type", "application/json")
                        .with_header("accept", "text/event-stream")
                        .with_header("mcp-protocol-version", MODERN_PROTOCOL_VERSION)
                        .with_header("mcp-method", "notifications/cancelled")
                        .with_body(
                            serde_json::to_vec(&cancellation)
                                .expect("typed cancellation notification must serialize"),
                        ),
                    TransportAuthorization::default(),
                    None,
                )
                .await
                .map_err(|error| format!("streaming cancellation rejection failed: {error}"))?
                .map_err(|response| *response);
            let Err(ServerHttpEndpointResponse::Immediate(streaming_rejected)) = streaming_rejected
            else {
                return Err("live SSE cancellation POST was not rejected immediately".to_owned());
            };
            if streaming_rejected.status != HttpStatus::ACCEPTED {
                return Err("live SSE cancellation POST used the wrong status".to_owned());
            }
            streaming_rejected_session.close(&cx).await;

            drop(first_sse);
            if first_guard.checkpoint(&cx).is_ok() || second_guard.checkpoint(&cx).is_err() {
                return Err("response-body drop did not isolate cancellation".to_owned());
            }
            drop(first_session);
            let removal_deadline = Instant::now() + Duration::from_secs(2);
            while endpoint
                .server
                .final_subscriptions
                .inner
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .entries
                .len()
                != 1
            {
                if Instant::now() >= removal_deadline {
                    return Err("dropped response body was not removed".to_owned());
                }
                asupersync::time::sleep(cx.now(), Duration::from_millis(1)).await;
            }
            if endpoint
                .server
                .publish_subscription_notification(ServerNotification::ToolsListChanged(None))
                .map_err(|error| format!("surviving listen publish failed: {error}"))?
                != 1
                || !matches!(second_sse.pop_event(), Ok(Some(_)))
            {
                return Err("dropped body affected the surviving listen".to_owned());
            }

            if endpoint.server.terminate_subscription_streams() != 1 {
                return Err("server teardown did not elect the surviving listen".to_owned());
            }
            if second_guard.checkpoint(&cx).is_err() || second_sse.is_finished() {
                return Err("HTTP completion was confused with a closed public body".to_owned());
            }
            let completion_deadline = Instant::now() + Duration::from_secs(2);
            let completion = loop {
                match second_sse.pop_event() {
                    Ok(Some(event)) => break event,
                    Ok(None) if Instant::now() < completion_deadline => {
                        asupersync::time::sleep(cx.now(), Duration::from_millis(1)).await;
                    }
                    Ok(None) => return Err("terminal completion remained pending".to_owned()),
                    Err(error) => {
                        return Err(format!("terminal completion was not readable: {error}"));
                    }
                }
            };
            if let Ok(notification) = serde_json::from_str::<JsonRpcRequest>(&completion.data) {
                if final_subscription_terminal_notification(&notification) {
                    return Err(
                        "HTTP graceful teardown emitted notifications/cancelled instead of its complete result"
                            .to_owned(),
                    );
                }
                return Err(
                    "HTTP graceful teardown emitted a notification instead of its complete result"
                        .to_owned(),
                );
            }
            let completion: JsonRpcResponse = serde_json::from_str(&completion.data)
                .map_err(|error| format!("terminal completion was invalid JSON-RPC: {error}"))?;
            if completion.id != Some(RequestId::Number(884))
                || !final_subscription_completion_response(&completion)
            {
                return Err(
                    "server teardown did not complete the exact public listen request".to_owned(),
                );
            }
            if !second_sse.is_finished() || second_guard.checkpoint(&cx).is_ok() {
                return Err("terminal completion did not finish the public SSE body".to_owned());
            }
            if !matches!(second_sse.pop_event(), Err(ServerHttpEndpointError::Closed)) {
                return Err(
                    "terminal completion did not close the public SSE response body".to_owned(),
                );
            }

            second_session.close(&cx).await;
            if second_guard.checkpoint(&cx).is_ok()
                || !endpoint
                    .server
                    .final_subscriptions
                    .inner
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .entries
                    .is_empty()
                || second_sse.pop_event().is_ok()
                || second_session.has_modern_dispatches()
            {
                return Err("session close remained indistinguishable from pending".to_owned());
            }
            second_session.close(&cx).await;
            Ok(())
        });
    }

    #[test]
    fn public_http_peer_close_revokes_listen_without_terminal_completion() {
        run_live_http_test(|cx| async move {
            let endpoint = Server::new("public-http-last-session-drop", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .test_http_endpoint("http://legacy.test")
                .map_err(|error| format!("public endpoint setup failed: {error}"))?;
            let mut session = endpoint
                .open_session(&cx)
                .map_err(|error| format!("public listen session failed: {error}"))?;
            let listen = JsonRpcRequest::new(
                SUBSCRIPTIONS_LISTEN,
                Some(serde_json::json!({
                    "_meta": {
                        MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                        FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                    },
                    "notifications": {"toolsListChanged": true},
                })),
                RequestId::Number(889),
            );
            let response = session
                .handle_async(
                    &cx,
                    HttpRequest::new(HttpMethod::Post, "/mcp")
                        .with_header("content-type", "application/json")
                        .with_header("accept", "text/event-stream")
                        .with_header("mcp-protocol-version", MODERN_PROTOCOL_VERSION)
                        .with_header("mcp-method", SUBSCRIPTIONS_LISTEN)
                        .with_body(
                            serde_json::to_vec(&listen)
                                .expect("typed listen request must serialize"),
                        ),
                )
                .await
                .map_err(|error| format!("public listen failed: {error}"))?;
            let ServerHttpEndpointResponse::ModernSse(sse) = response else {
                return Err("public listen did not return SSE".to_owned());
            };
            let guard = sse.cancellation();
            let deadline = Instant::now() + Duration::from_secs(2);
            loop {
                match sse.pop_event() {
                    Ok(Some(_acknowledgement)) => break,
                    Ok(None) if Instant::now() < deadline => {
                        asupersync::time::sleep(cx.now(), Duration::from_millis(1)).await;
                    }
                    Ok(None) => return Err("public listen acknowledgement timed out".to_owned()),
                    Err(error) => return Err(format!("public listen closed early: {error}")),
                }
            }
            if guard.checkpoint(&cx).is_err() {
                return Err("acknowledged listen was not pending before session drop".to_owned());
            }

            drop(session);
            if guard.checkpoint(&cx).is_ok()
                || !endpoint
                    .server
                    .final_subscriptions
                    .inner
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .entries
                    .is_empty()
            {
                return Err("peer close did not revoke its exact request".to_owned());
            }
            if !matches!(sse.pop_event(), Err(ServerHttpEndpointError::Closed)) {
                return Err(
                    "peer-close path emitted an event instead of closing without completion"
                        .to_owned(),
                );
            }
            Ok(())
        });
    }

    #[test]
    fn public_http_live_session_keeps_acknowledged_listen_open_without_peer_close() {
        // Differs from the peer-close test above only in that the session
        // stays open: the listen must stay pending, registered and silent.
        run_live_http_test(|cx| async move {
            let endpoint = Server::new("public-http-last-session-drop", "1.0.0")
                .protocol_policy(ProtocolPolicy::ModernOnly)
                .expect("ModernOnly must be available to this test build")
                .test_http_endpoint("http://legacy.test")
                .map_err(|error| format!("public endpoint setup failed: {error}"))?;
            let mut session = endpoint
                .open_session(&cx)
                .map_err(|error| format!("public listen session failed: {error}"))?;
            let listen = JsonRpcRequest::new(
                SUBSCRIPTIONS_LISTEN,
                Some(serde_json::json!({
                    "_meta": {
                        MODERN_PROTOCOL_VERSION_METADATA_KEY: MODERN_PROTOCOL_VERSION,
                        FINAL_CLIENT_CAPABILITIES_META_KEY: {},
                    },
                    "notifications": {"toolsListChanged": true},
                })),
                RequestId::Number(889),
            );
            let response = session
                .handle_async(
                    &cx,
                    HttpRequest::new(HttpMethod::Post, "/mcp")
                        .with_header("content-type", "application/json")
                        .with_header("accept", "text/event-stream")
                        .with_header("mcp-protocol-version", MODERN_PROTOCOL_VERSION)
                        .with_header("mcp-method", SUBSCRIPTIONS_LISTEN)
                        .with_body(
                            serde_json::to_vec(&listen)
                                .expect("typed listen request must serialize"),
                        ),
                )
                .await
                .map_err(|error| format!("public listen failed: {error}"))?;
            let ServerHttpEndpointResponse::ModernSse(sse) = response else {
                return Err("public listen did not return SSE".to_owned());
            };
            let guard = sse.cancellation();
            let deadline = Instant::now() + Duration::from_secs(2);
            loop {
                match sse.pop_event() {
                    Ok(Some(_acknowledgement)) => break,
                    Ok(None) if Instant::now() < deadline => {
                        asupersync::time::sleep(cx.now(), Duration::from_millis(1)).await;
                    }
                    Ok(None) => return Err("public listen acknowledgement timed out".to_owned()),
                    Err(error) => return Err(format!("public listen closed early: {error}")),
                }
            }
            if guard.checkpoint(&cx).is_err() {
                return Err("acknowledged listen was not pending before session drop".to_owned());
            }

            if guard.checkpoint(&cx).is_err()
                || endpoint
                    .server
                    .final_subscriptions
                    .inner
                    .lock()
                    .unwrap_or_else(std::sync::PoisonError::into_inner)
                    .entries
                    .is_empty()
            {
                return Err("an open session revoked its acknowledged listen".to_owned());
            }
            if !matches!(sse.pop_event(), Ok(None)) {
                return Err(
                    "an open session's listen emitted an event or closed without a peer close"
                        .to_owned(),
                );
            }
            drop(session);
            Ok(())
        });
    }

    #[cfg(feature = "tasks")]
    struct IdleHostedTaskSupervisor;

    #[cfg(feature = "tasks")]
    impl ApplicationTaskSupervisor for IdleHostedTaskSupervisor {
        fn resume<'a>(
            &'a self,
            _cx: &'a Cx,
            _handoff: FinalTaskSupervisorHandoff,
        ) -> FinalTaskSupervisorFuture<'a> {
            Box::pin(async { Ok(()) })
        }
    }

    /// Serves `bound` until `runtime` reports a ready Task service or a bound
    /// passes, then cancels the serve. Returns whether the service was ready.
    #[cfg(feature = "tasks")]
    async fn serve_until_task_service_ready(
        cx: &Cx,
        bound: BoundHttpServer,
        runtime: FinalTaskRuntime,
    ) -> Result<bool, String> {
        let caller_cx = cx.clone();
        let mut observer = cx
            .spawn(move |observer_cx| async move {
                let mut ready = false;
                for _ in 0..2_000 {
                    if runtime.is_task_service_ready() {
                        ready = true;
                        break;
                    }
                    asupersync::time::sleep(observer_cx.now(), Duration::from_millis(1)).await;
                }
                caller_cx.cancel_with(CancelKind::User, Some("hosted Task service observed"));
                ready
            })
            .map_err(|error| format!("observer admission failed: {error}"))?;
        let serve = bound.serve(cx).await;
        let ready = observer
            .join(cx)
            .await
            .map_err(|error| format!("observer failed: {error:?}"))?;
        let shutdown = serve.map_err(|error| format!("hosted Tasks serve failed: {error}"))?;
        require_quiescent_http_shutdown(shutdown, "hosted Tasks serve").await?;
        Ok(ready)
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn live_http_hosts_a_ready_task_service_and_settles_it_when_serve_is_cancelled() {
        run_live_http_test(|cx| async move {
            let server = Server::new("live-hosted-tasks", "1.0.0")
                .task_supervisor(Arc::new(IdleHostedTaskSupervisor))
                .build();
            let runtime = server
                .final_task_runtime()
                .cloned()
                .ok_or_else(|| "the default Tasks runtime is installed".to_owned())?;
            if runtime.is_task_service_ready() {
                return Err("building must not start the Task service".to_owned());
            }
            let bound = server
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("hosted Tasks bind failed: {error}"))?;
            if !serve_until_task_service_ready(&cx, bound, runtime.clone()).await? {
                return Err("the serve must host a ready Task service".to_owned());
            }
            if runtime.is_task_service_ready() {
                return Err("no Task service runner may still run after serve returns".to_owned());
            }
            Ok(())
        });
    }

    #[cfg(feature = "tasks")]
    #[test]
    fn live_http_without_a_task_supervisor_hosts_no_task_service() {
        run_live_http_test(|cx| async move {
            let server = Server::new("live-unhosted-tasks", "1.0.0").build();
            let runtime = server
                .final_task_runtime()
                .cloned()
                .ok_or_else(|| "the default Tasks runtime is installed".to_owned())?;
            let bound = server
                .bind_http(&cx, "127.0.0.1:0")
                .await
                .map_err(|error| format!("unhosted Tasks bind failed: {error}"))?;
            if serve_until_task_service_ready(&cx, bound, runtime).await? {
                return Err("a server without task_supervisor must host no Task service".to_owned());
            }
            Ok(())
        });
    }
}