fastmcp-client 0.7.0

MCP client implementation for FastMCP
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
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
//! Transport-neutral request execution and response correlation.
//!
//! This module owns the correlation rules that are independent of a concrete
//! MCP transport. A transport supplies typed JSON-RPC frames; the executor
//! commits requests, preserves out-of-order final responses for their exact
//! owners, retains bounded tombstones for retired owners, and never turns
//! malformed peer ingress into a peer-directed JSON-RPC response.

use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{Duration, Instant};

use asupersync::Cx;
use fastmcp_core::{McpError, McpErrorCode, McpResult, Sha256Digest, sha256_bounded};
#[cfg(any(feature = "tasks", test))]
use fastmcp_protocol::FinalCoreResult;
use fastmcp_protocol::methods::{
    FINAL_2026_07_28_METHODS, Final2026EnvelopeKind, Final2026Peer, INITIALIZE,
    LEGACY_2024_11_05_METHODS, Legacy2024Direction, Legacy2024EnvelopeKind, SUBSCRIPTIONS_LISTEN,
    TOOLS_CALL, validate_legacy_2024_11_05_method_params,
};
use fastmcp_protocol::protocol_policy::ProtocolEra;
#[cfg(feature = "tasks")]
use fastmcp_protocol::tasks_extension::{
    CancelTaskParams, CancelTaskResult, GetTaskParams, GetTaskResult, TASK_STATUS_NOTIFICATION,
    Task, TaskId, TaskInputLedger, TaskMethodRequest, TaskStatusNotification, UpdateTaskParams,
    UpdateTaskResult, task_subscription_ids,
};
use fastmcp_protocol::{
    CancellationSender, CancellationWireMessage, CancelledParams, CoreRequest, CoreResult,
    CoreResultDiscriminatorPolicy, CorrelationKey, DecodedResult, FINAL_SUBSCRIPTION_ID_META_KEY,
    FinalCancelledNotificationParams, JsonRpcMessage, JsonRpcRequest, JsonRpcResponse,
    ProgressMarker, RequestId, ResultPeerDiagnostic, ResultPeerEra, decode_peer_result,
    decode_strict_jsonrpc_response,
};
#[cfg(feature = "tasks")]
use fastmcp_protocol::{
    FinalSubscriptionsAcknowledgedNotificationParams, FinalSubscriptionsListenParams,
    SubscriptionFilter,
};
use fastmcp_transport::{ReceivedTransportFrame, Transport, TransportError};
use serde_json::Value;

use crate::{RequestTimeoutPolicy, transport_error_to_mcp};

/// Bounded compatibility diagnostic for a peer's final cache TTL.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FinalCacheTtlDiagnostic {
    /// A cacheable final complete result omitted its required `ttlMs` member.
    Missing,
    /// A cacheable final complete result supplied a negative `ttlMs`.
    Negative,
}

/// Default maximum number of active request owners.
pub const DEFAULT_MAX_IN_FLIGHT_EXECUTIONS: usize = 1_024;
/// Absolute ceiling for active request owners.
pub const MAX_IN_FLIGHT_EXECUTIONS: usize = 16_384;
/// Default maximum number of retained response correlations.
pub const DEFAULT_MAX_RESPONSE_CORRELATIONS: usize = 4_096;
/// Absolute ceiling for retained response correlations.
pub const MAX_RESPONSE_CORRELATIONS: usize = 65_536;
/// Default period for retaining a retired execution's exact response ID.
pub const DEFAULT_TOMBSTONE_RETENTION: Duration = Duration::from_mins(10);
/// Longest admitted period for retaining a retired response ID.
pub const MAX_TOMBSTONE_RETENTION: Duration = Duration::from_hours(1);

const MAX_RETAINED_PEER_ACTIVITY: usize = 1_024;
/// Minimum automatic-pagination page bound admitted by CLT-01 B.
pub const MIN_AUTOMATIC_PAGINATION_PAGES: usize = 1_000;
/// Minimum automatic-pagination item bound admitted by CLT-01 B.
pub const MIN_AUTOMATIC_PAGINATION_ITEMS: usize = 100_000;
/// Minimum automatic-pagination decoded-byte bound admitted by CLT-01 B.
pub const MIN_AUTOMATIC_PAGINATION_DECODED_BYTES: usize = 256 * 1024 * 1024;
/// Minimum automatic-pagination deadline admitted by CLT-01 B.
pub const MIN_AUTOMATIC_PAGINATION_DEADLINE: Duration = Duration::from_mins(5);
/// Hard automatic-pagination page ceiling.
pub const MAX_AUTOMATIC_PAGINATION_PAGES: usize = 10_000;
/// Hard automatic-pagination item ceiling.
pub const MAX_AUTOMATIC_PAGINATION_ITEMS: usize = 1_000_000;
/// Hard automatic-pagination decoded-byte ceiling.
pub const MAX_AUTOMATIC_PAGINATION_DECODED_BYTES: usize = 2 * 1024 * 1024 * 1024;
/// Hard automatic-pagination deadline ceiling.
pub const MAX_AUTOMATIC_PAGINATION_DEADLINE: Duration = Duration::from_mins(30);
const CLT_01_A_MANIFEST_ROWS: &str = concat!(
    "CLT-01-A\n",
    "01 reordered correlated finals\n",
    "02 duplicate response ID\n",
    "03 unknown late tombstoned ID\n",
    "04 notification interleaving\n",
    "05 malformed peer ingress without reverse response\n",
    "06 typed complete input-required result siblings\n",
    "07 send queue backpressure\n",
    "08 connection-loss waiter fanout\n",
    "pending correlation_key request_id execution_generation request_state send_committed idle_deadline absolute_deadline terminal_state cancellation_committed tombstone_generation\n",
);
const CLT_01_B_MANIFEST_ROWS: &str = concat!(
    "CLT-01-B\n",
    "09 explicit caller cancellation/drop\n",
    "10 idle expiry and exact matching-progress reset\n",
    "11 non-resettable absolute expiry under progress/log/keepalive flood\n",
    "12 final-response/caller-cancel/timeout/connection-loss same-tick race\n",
    "13 reverse request and streaming notification ordering\n",
    "14 opaque pagination empty/repeated/absent cursors plus page/item/byte/deadline bounds\n",
    "15 shutdown/connection-close cleanup\n",
    "terminal_state terminal_reason final_delivered cancellation_committed cancellation_transport_attempts local_cancellation_event waiter_release tombstone\n",
);

/// Bounds for one multi-round model-request tool retry (MRTR) operation.
///
/// The caller chooses the operation's absolute deadline separately. These
/// bounds limit only how many input-required continuations and total supplied
/// input values that operation may admit before it sends another request.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct MrtrDriverLimits {
    max_continuation_rounds: usize,
    max_total_input_responses: usize,
}

impl MrtrDriverLimits {
    /// Creates validated MRTR continuation bounds.
    ///
    /// Both bounds must be nonzero. A continuation round is one peer
    /// `input_required` result followed by one possible caller retry.
    pub(crate) fn new(
        max_continuation_rounds: usize,
        max_total_input_responses: usize,
    ) -> McpResult<Self> {
        if max_continuation_rounds == 0 {
            return Err(McpError::invalid_params(
                "MRTR continuation-round limit must be at least one",
            ));
        }
        if max_total_input_responses == 0 {
            return Err(McpError::invalid_params(
                "MRTR total input-response limit must be at least one",
            ));
        }
        Ok(Self {
            max_continuation_rounds,
            max_total_input_responses,
        })
    }
}

/// Caller-owned state for one bounded multi-round MRTR operation.
///
/// This type deliberately does not own transport state or spawn work. The
/// stdio client keeps transport ownership while this driver makes the caller's
/// cancellation context, one absolute deadline, and the continuation/input
/// counters explicit at every retry boundary.
#[derive(Debug)]
pub(crate) struct MrtrDriver<'cx> {
    cx: &'cx Cx,
    deadline: Instant,
    limits: MrtrDriverLimits,
    continuation_rounds: usize,
    total_input_responses: usize,
}

impl<'cx> MrtrDriver<'cx> {
    /// Starts one MRTR operation using exactly the supplied caller context and
    /// absolute deadline.
    pub(crate) fn new(cx: &'cx Cx, deadline: Instant, limits: MrtrDriverLimits) -> McpResult<Self> {
        let driver = Self {
            cx,
            deadline,
            limits,
            continuation_rounds: 0,
            total_input_responses: 0,
        };
        driver.before_request()?;
        Ok(driver)
    }

    /// Returns the operation-wide absolute deadline.
    #[must_use]
    pub(crate) const fn deadline(&self) -> Instant {
        self.deadline
    }

    /// Checks caller cancellation and the operation-wide deadline before a
    /// request can be committed.
    pub(crate) fn before_request(&self) -> McpResult<()> {
        if self.cx.checkpoint().is_err() {
            return Err(McpError::request_cancelled());
        }
        if Instant::now() >= self.deadline {
            return Err(McpError::internal_error(
                "MRTR operation absolute deadline elapsed",
            ));
        }
        Ok(())
    }

    /// Admits one peer `input_required` continuation before the callback is
    /// invoked. This prevents a callback effect or another wire request after
    /// the configured round bound has been reached.
    pub(crate) fn begin_continuation(&mut self) -> McpResult<()> {
        self.before_request()?;
        let continuation_rounds = self.continuation_rounds.checked_add(1).ok_or_else(|| {
            McpError::internal_error("MRTR continuation-round counter overflowed")
        })?;
        if continuation_rounds > self.limits.max_continuation_rounds {
            return Err(McpError::invalid_params(
                "MRTR continuation-round limit exceeded",
            ));
        }
        self.continuation_rounds = continuation_rounds;
        Ok(())
    }

    /// Admits the response entries selected for the current continuation.
    ///
    /// A state-only continuation supplies zero entries and is therefore
    /// admitted as long as the caller has not exceeded the round limit.
    pub(crate) fn admit_input_responses(&mut self, input_response_count: usize) -> McpResult<()> {
        self.before_request()?;
        let total_input_responses = self
            .total_input_responses
            .checked_add(input_response_count)
            .ok_or_else(|| {
                McpError::internal_error("MRTR total input-response counter overflowed")
            })?;
        if total_input_responses > self.limits.max_total_input_responses {
            return Err(McpError::invalid_params(
                "MRTR total input-response limit exceeded",
            ));
        }
        self.total_input_responses = total_input_responses;
        self.before_request()
    }
}

/// A client-authored JSON-RPC request that expects one final response.
pub type Request = JsonRpcRequest;

/// Returns the canonical CLT-01 A case-and-pending-record manifest digest.
///
/// The manifest is an executable acceptance input, not a source-file hash: it
/// binds the public executor's ordered groups 01–08 and every observable
/// pending-map field exercised by the public-surface tests.
#[must_use]
pub fn clt_01_a_manifest_digest() -> Sha256Digest {
    sha256_bounded(
        CLT_01_A_MANIFEST_ROWS.as_bytes(),
        CLT_01_A_MANIFEST_ROWS.len(),
    )
    .expect("the fixed CLT-01 A manifest is within its exact byte bound")
}

/// Returns the canonical CLT-01 B lifecycle-and-pagination manifest digest.
///
/// The digest binds ordered groups 09–15 and the terminal predicate; it is
/// deliberately a fixed acceptance input rather than a hash of this source.
#[must_use]
pub fn clt_01_b_manifest_digest() -> Sha256Digest {
    sha256_bounded(
        CLT_01_B_MANIFEST_ROWS.as_bytes(),
        CLT_01_B_MANIFEST_ROWS.len(),
    )
    .expect("the fixed CLT-01 B manifest is within its exact byte bound")
}

/// Decodes a core response through the exact request and negotiated-era type.
///
/// The request owns the method-specific result shape, so this cannot conflate a
/// final `tools/call` response with a legacy result or with another core
/// method's complete payload. The caller owns connection policy after a peer
/// violates this contract.
pub(crate) fn decode_core_result(request: &CoreRequest, result: &Value) -> McpResult<CoreResult> {
    decode_core_result_from_source(request, result, None)
}

pub(crate) fn decode_core_result_from_source(
    request: &CoreRequest,
    result: &Value,
    result_source: Option<&str>,
) -> McpResult<CoreResult> {
    let encoded = match result_source {
        Some(source) => {
            let admitted: Value = serde_json::from_str(source).map_err(|_| {
                McpError::invalid_request("Peer core result source is not valid JSON")
            })?;
            if &admitted != result {
                return Err(McpError::invalid_request(
                    "Peer core result source differs from its typed response",
                ));
            }
            Cow::Borrowed(source)
        }
        None => Cow::Owned(serde_json::to_string(result).map_err(|_| {
            McpError::invalid_request(
                "Peer core result could not be encoded for protocol admission",
            )
        })?),
    };
    request
        .decode_result(&encoded)
        .map_err(|_| McpError::invalid_request("Peer core result failed protocol decoding"))
}

/// Decodes a core result while applying the final cache-TTL compatibility rule
/// at the client ingress boundary. Missing or negative peer TTLs are
/// normalized to zero freshness and reported through a bounded local
/// diagnostic. All other malformed shapes continue through strict protocol
/// decoding unchanged.
pub(crate) fn decode_core_result_with_cache_ttl(
    request: &CoreRequest,
    result: &Value,
) -> McpResult<(CoreResult, Option<FinalCacheTtlDiagnostic>)> {
    decode_core_result_with_cache_ttl_from_source(request, result, None)
}

pub(crate) fn decode_core_result_with_cache_ttl_from_source(
    request: &CoreRequest,
    result: &Value,
    result_source: Option<&str>,
) -> McpResult<(CoreResult, Option<FinalCacheTtlDiagnostic>)> {
    let mut normalized = result.clone();
    let diagnostic = tolerant_final_cache_ttl(request, &mut normalized);
    let normalized_source = result_source
        .map(|source| normalize_final_cache_ttl_source(source, diagnostic))
        .transpose()?;
    decode_core_result_from_source(request, &normalized, normalized_source.as_deref())
        .map(|result| (result, diagnostic))
}

fn normalize_final_cache_ttl_source(
    source: &str,
    diagnostic: Option<FinalCacheTtlDiagnostic>,
) -> McpResult<Cow<'_, str>> {
    match diagnostic {
        None => Ok(Cow::Borrowed(source)),
        Some(FinalCacheTtlDiagnostic::Missing) => {
            let end = source.trim_end().len();
            let Some(close) = end
                .checked_sub(1)
                .filter(|index| source.as_bytes()[*index] == b'}')
            else {
                return Err(McpError::invalid_request(
                    "Peer cacheable result source is not an object",
                ));
            };
            let open = source.find('{').ok_or_else(|| {
                McpError::invalid_request("Peer cacheable result is not an object")
            })?;
            let separator = if source[open + 1..close].trim().is_empty() {
                ""
            } else {
                ","
            };
            Ok(Cow::Owned(format!(
                "{}{}\"ttlMs\":0{}",
                &source[..close],
                separator,
                &source[close..]
            )))
        }
        Some(FinalCacheTtlDiagnostic::Negative) => {
            let range = top_level_json_member_value_range(source, "ttlMs").ok_or_else(|| {
                McpError::invalid_request("Peer cache TTL source member could not be located")
            })?;
            let mut normalized = String::with_capacity(source.len());
            normalized.push_str(&source[..range.start]);
            normalized.push('0');
            normalized.push_str(&source[range.end..]);
            Ok(Cow::Owned(normalized))
        }
    }
}

fn top_level_json_member_value_range(
    source: &str,
    expected_name: &str,
) -> Option<std::ops::Range<usize>> {
    let bytes = source.as_bytes();
    let mut cursor = bytes.iter().position(|byte| !byte.is_ascii_whitespace())?;
    if bytes.get(cursor) != Some(&b'{') {
        return None;
    }
    cursor += 1;
    loop {
        while bytes.get(cursor).is_some_and(u8::is_ascii_whitespace) {
            cursor += 1;
        }
        if bytes.get(cursor) == Some(&b'}') {
            return None;
        }
        let key_start = cursor;
        let key_end = json_string_end(bytes, cursor)?;
        let key: String = serde_json::from_str(&source[key_start..key_end]).ok()?;
        cursor = key_end;
        while bytes.get(cursor).is_some_and(u8::is_ascii_whitespace) {
            cursor += 1;
        }
        if bytes.get(cursor) != Some(&b':') {
            return None;
        }
        cursor += 1;
        while bytes.get(cursor).is_some_and(u8::is_ascii_whitespace) {
            cursor += 1;
        }
        let value_start = cursor;
        let value_end = json_value_end(bytes, cursor)?;
        if key == expected_name {
            return Some(value_start..value_end);
        }
        cursor = value_end;
        while bytes.get(cursor).is_some_and(u8::is_ascii_whitespace) {
            cursor += 1;
        }
        match bytes.get(cursor) {
            Some(b',') => cursor += 1,
            Some(b'}') => return None,
            _ => return None,
        }
    }
}

fn json_string_end(bytes: &[u8], start: usize) -> Option<usize> {
    if bytes.get(start) != Some(&b'"') {
        return None;
    }
    let mut cursor = start + 1;
    while let Some(byte) = bytes.get(cursor) {
        match byte {
            b'"' => return Some(cursor + 1),
            b'\\' => cursor = cursor.checked_add(2)?,
            _ => cursor += 1,
        }
    }
    None
}

fn json_value_end(bytes: &[u8], start: usize) -> Option<usize> {
    if bytes.get(start) == Some(&b'"') {
        return json_string_end(bytes, start);
    }
    if matches!(bytes.get(start), Some(b'{' | b'[')) {
        let mut stack = vec![*bytes.get(start)?];
        let mut cursor = start + 1;
        while let Some(byte) = bytes.get(cursor) {
            match byte {
                b'"' => cursor = json_string_end(bytes, cursor)?,
                b'{' | b'[' => {
                    stack.push(*byte);
                    cursor += 1;
                }
                b'}' if stack.last() == Some(&b'{') => {
                    stack.pop();
                    cursor += 1;
                    if stack.is_empty() {
                        return Some(cursor);
                    }
                }
                b']' if stack.last() == Some(&b'[') => {
                    stack.pop();
                    cursor += 1;
                    if stack.is_empty() {
                        return Some(cursor);
                    }
                }
                _ => cursor += 1,
            }
        }
        return None;
    }
    let mut cursor = start;
    while !matches!(bytes.get(cursor), None | Some(b',' | b'}')) {
        cursor += 1;
    }
    let mut end = cursor;
    while end > start && bytes[end - 1].is_ascii_whitespace() {
        end -= 1;
    }
    (end > start).then_some(end)
}

fn tolerant_final_cache_ttl(
    request: &CoreRequest,
    result: &mut Value,
) -> Option<FinalCacheTtlDiagnostic> {
    let CoreRequest::Final(request) = request else {
        return None;
    };
    if !matches!(
        request,
        fastmcp_protocol::FinalCoreRequest::ToolsList(_)
            | fastmcp_protocol::FinalCoreRequest::ResourcesList(_)
            | fastmcp_protocol::FinalCoreRequest::ResourceTemplatesList(_)
            | fastmcp_protocol::FinalCoreRequest::ResourcesRead(_)
            | fastmcp_protocol::FinalCoreRequest::PromptsList(_)
    ) {
        return None;
    }
    let members = result.as_object_mut()?;
    if members
        .get("resultType")
        .is_some_and(|result_type| result_type.as_str() != Some("complete"))
    {
        return None;
    }

    match members.get("ttlMs") {
        None => {
            members.insert("ttlMs".to_owned(), Value::Number(0_u64.into()));
            Some(FinalCacheTtlDiagnostic::Missing)
        }
        Some(Value::Number(ttl)) if ttl.to_string().starts_with('-') => {
            members.insert("ttlMs".to_owned(), Value::Number(0_u64.into()));
            Some(FinalCacheTtlDiagnostic::Negative)
        }
        _ => None,
    }
}

/// Public snapshot of one active correlation record.
///
/// The executor exposes these records so callers can audit exactly which
/// request owns a response slot without access to the concrete transport.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PendingRequestRecord {
    /// Canonical key for this correlation; numeric wire aliases share one key.
    pub correlation_key: CorrelationKey,
    /// Exact JSON-RPC request ID sent to the peer.
    pub request_id: RequestId,
    /// Monotonic generation for a request ID that may later be tombstoned.
    pub execution_generation: u64,
    /// Whether the request has entered the response-wait phase.
    pub request_state: ExecutionTerminalState,
    /// Whether the request bytes were committed to the transport.
    pub send_committed: bool,
    /// Post-send idle deadline recorded for the execution owner.
    pub idle_deadline: Instant,
    /// Non-resettable post-send absolute deadline recorded for the owner.
    pub absolute_deadline: Instant,
    /// Current terminal state; active entries are always [`Self::request_state`].
    pub terminal_state: ExecutionTerminalState,
    /// Whether a cancellation transition has been selected for this owner.
    pub cancellation_committed: bool,
    /// Generation retained by a later tombstone, if this record has retired.
    pub tombstone_generation: Option<u64>,
}

/// Exactly-once execution state visible to callers.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExecutionTerminalState {
    /// The execution remains eligible to receive one final response.
    Pending,
    /// A final JSON-RPC response was accepted for the exact owner.
    Response,
    /// The transport or peer protocol failed the owner.
    Failed,
    /// The owner was abandoned and a cancellation request was selected.
    Cancelled,
}

/// The one local cause that won an execution's terminal transition.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExecutionTerminalReason {
    /// The peer final response won the terminal transition.
    FinalResponse,
    /// The caller explicitly cancelled the execution.
    CallerCancelled,
    /// The request-owned handle was dropped before its final response.
    CallerDropped,
    /// A valid, accepted peer subscription teardown selected cancellation.
    PeerSubscriptionTeardown,
    /// The committed request made no qualifying progress before idle expiry.
    IdleTimeout,
    /// The non-resettable committed request lifetime elapsed.
    AbsoluteTimeout,
    /// The shared connection or peer ingress failed.
    ConnectionLost,
    /// The exact owner received an invalid final MCP result envelope.
    PeerProtocol,
    /// Local executor shutdown selected the terminal transition.
    Shutdown,
}

/// Typed, local-only cancellation indication for an execution owner.
///
/// This intentionally exposes a classifier rather than peer-provided text;
/// raw cancellation reasons are never copied into an observer event.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CancellationRequested {
    /// Exact request ID whose cancellation was selected.
    pub request_id: RequestId,
    /// Local classifier for the selected cancellation source.
    pub reason: ExecutionTerminalReason,
}

/// Cooperative cancellation handle owned by one exact-2024 reverse request.
///
/// The executor cancels this handle only after accepting an ID-free legacy
/// `notifications/cancelled` notification that names this request's live
/// owner. A callback must use its own checkpoints before producing effects.
const REVERSE_CALLBACK_OPEN: u8 = 0;
const REVERSE_CALLBACK_CANCELLED: u8 = 1;
const REVERSE_CALLBACK_RESPONSE_SENT: u8 = 2;

#[derive(Clone, Debug)]
pub struct ReverseRequestCancellation(Arc<AtomicU8>);

impl ReverseRequestCancellation {
    pub(crate) fn new() -> Self {
        Self(Arc::new(AtomicU8::new(REVERSE_CALLBACK_OPEN)))
    }

    pub(crate) fn cancel(&self) {
        let _ = self.0.compare_exchange(
            REVERSE_CALLBACK_OPEN,
            REVERSE_CALLBACK_CANCELLED,
            Ordering::AcqRel,
            Ordering::Acquire,
        );
    }

    pub(crate) fn is_open(&self) -> bool {
        self.0.load(Ordering::Acquire) == REVERSE_CALLBACK_OPEN
    }

    pub(crate) fn record_response_sent(&self) {
        let previous = self.0.compare_exchange(
            REVERSE_CALLBACK_OPEN,
            REVERSE_CALLBACK_RESPONSE_SENT,
            Ordering::AcqRel,
            Ordering::Acquire,
        );
        debug_assert!(
            previous.is_ok(),
            "only an elected open callback can record a response write"
        );
    }

    pub(crate) fn belongs_to_same_request(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }

    /// Returns whether the server or owning connection cancelled this request.
    #[must_use]
    pub fn is_cancel_requested(&self) -> bool {
        self.0.load(Ordering::Acquire) == REVERSE_CALLBACK_CANCELLED
    }

    /// Returns `RequestCancelled` when this reverse request is no longer live.
    pub fn checkpoint(&self) -> McpResult<()> {
        if self.is_cancel_requested() {
            return Err(McpError::request_cancelled());
        }
        Ok(())
    }
}

/// One exact-2024 server-authored reverse request together with its response
/// capability.
///
/// The capability is local to both this request incarnation and this executor
/// connection. It cannot answer a later request that happens to reuse the
/// same JSON-RPC ID, including after a matching cancellation.
#[derive(Clone, Debug)]
pub struct ReverseRequest {
    request: JsonRpcRequest,
    cancellation: ReverseRequestCancellation,
    owner: Arc<()>,
}

impl ReverseRequest {
    /// Returns the exact server-authored request frame.
    #[must_use]
    pub fn request(&self) -> &JsonRpcRequest {
        &self.request
    }

    /// Returns the exact response ID carried by this request.
    #[must_use]
    pub fn request_id(&self) -> &RequestId {
        self.request
            .id
            .as_ref()
            .expect("reverse request owners always retain a request ID")
    }

    /// Returns the cooperative cancellation handle for this request owner.
    #[must_use]
    pub fn cancellation(&self) -> &ReverseRequestCancellation {
        &self.cancellation
    }
}

#[derive(Clone, Debug)]
struct ActiveReverseRequest {
    request_id: RequestId,
    cancellation: ReverseRequestCancellation,
    owner: Arc<()>,
}

/// Immutable receipt for the terminal CAS of one execution.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExecutionTerminalRecord {
    /// State selected by the single terminal transition.
    pub terminal_state: ExecutionTerminalState,
    /// Cause selected by the single terminal transition.
    pub terminal_reason: ExecutionTerminalReason,
    /// Whether a peer final response, rather than a local error, was delivered.
    pub final_delivered: bool,
    /// Whether this terminal path selected cancellation.
    pub cancellation_committed: bool,
    /// Number of cancellation transport sends attempted for this execution.
    pub cancellation_transport_attempts: u8,
    /// Whether the one typed local cancellation event was published.
    pub local_cancellation_event: bool,
    /// Whether the response waiter was released.
    pub waiter_release: bool,
    /// Whether the canonical request ID is retained to discard a late final response.
    pub tombstone: bool,
}

/// Bounds for an automatic opaque-cursor pagination sequence.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PaginationBounds {
    max_pages: usize,
    max_items: usize,
    max_decoded_bytes: usize,
    deadline: Duration,
}

impl PaginationBounds {
    /// Creates bounds within the frozen CLT-01 B admission interval.
    pub fn new(
        max_pages: usize,
        max_items: usize,
        max_decoded_bytes: usize,
        deadline: Duration,
    ) -> McpResult<Self> {
        if !(MIN_AUTOMATIC_PAGINATION_PAGES..=MAX_AUTOMATIC_PAGINATION_PAGES).contains(&max_pages)
            || !(MIN_AUTOMATIC_PAGINATION_ITEMS..=MAX_AUTOMATIC_PAGINATION_ITEMS)
                .contains(&max_items)
            || !(MIN_AUTOMATIC_PAGINATION_DECODED_BYTES..=MAX_AUTOMATIC_PAGINATION_DECODED_BYTES)
                .contains(&max_decoded_bytes)
            || !(MIN_AUTOMATIC_PAGINATION_DEADLINE..=MAX_AUTOMATIC_PAGINATION_DEADLINE)
                .contains(&deadline)
        {
            return Err(McpError::invalid_params(
                "Automatic pagination bounds fall outside the CLT-01 B admission interval",
            ));
        }
        Ok(Self {
            max_pages,
            max_items,
            max_decoded_bytes,
            deadline,
        })
    }
}

impl Default for PaginationBounds {
    fn default() -> Self {
        Self {
            max_pages: MIN_AUTOMATIC_PAGINATION_PAGES,
            max_items: MIN_AUTOMATIC_PAGINATION_ITEMS,
            max_decoded_bytes: MIN_AUTOMATIC_PAGINATION_DECODED_BYTES,
            deadline: MIN_AUTOMATIC_PAGINATION_DEADLINE,
        }
    }
}

/// State machine for opaque pagination cursors.
///
/// A present cursor, including the empty string and a repeated value, always
/// means another page. Only an absent field finishes the sequence.
#[derive(Clone, Debug)]
pub struct OpaquePagination {
    bounds: PaginationBounds,
    started_at: Instant,
    pages: usize,
    items: usize,
    decoded_bytes: usize,
    next_cursor: Option<String>,
    complete: bool,
}

impl OpaquePagination {
    /// Starts a bounded pagination sequence at `started_at`.
    #[must_use]
    pub fn new(bounds: PaginationBounds, started_at: Instant) -> Self {
        Self {
            bounds,
            started_at,
            pages: 0,
            items: 0,
            decoded_bytes: 0,
            next_cursor: None,
            complete: false,
        }
    }

    /// Admits one decoded page and records its next cursor verbatim.
    ///
    /// Returns `true` when the next cursor field is present, independently of
    /// its contents; callers must issue another request in that case.
    pub fn accept_page(
        &mut self,
        next_cursor: Option<String>,
        item_count: usize,
        decoded_bytes: usize,
        observed_at: Instant,
    ) -> McpResult<bool> {
        if self.complete {
            return Err(McpError::invalid_request(
                "Automatic pagination received a page after cursor absence completed it",
            ));
        }
        if observed_at.duration_since(self.started_at) > self.bounds.deadline {
            return Err(McpError::internal_error(
                "Automatic pagination deadline elapsed",
            ));
        }
        self.pages = self.pages.checked_add(1).ok_or_else(|| {
            McpError::internal_error("Automatic pagination page counter overflowed")
        })?;
        self.items = self.items.checked_add(item_count).ok_or_else(|| {
            McpError::internal_error("Automatic pagination item counter overflowed")
        })?;
        self.decoded_bytes = self
            .decoded_bytes
            .checked_add(decoded_bytes)
            .ok_or_else(|| {
                McpError::internal_error("Automatic pagination byte counter overflowed")
            })?;
        if self.pages > self.bounds.max_pages
            || self.items > self.bounds.max_items
            || self.decoded_bytes > self.bounds.max_decoded_bytes
        {
            return Err(McpError::internal_error(
                "Automatic pagination exceeded a local bound",
            ));
        }
        self.complete = next_cursor.is_none();
        self.next_cursor = next_cursor;
        Ok(!self.complete)
    }

    /// Returns the opaque next cursor without normalization or interpretation.
    #[must_use]
    pub fn next_cursor(&self) -> Option<&str> {
        self.next_cursor.as_deref()
    }
}

#[derive(Debug)]
struct PendingExecution {
    record: PendingRequestRecord,
    owner_dropped: OwnerDropped,
    timeout_policy: RequestTimeoutPolicy,
    /// The exact optional marker the request advertised in `_meta`.
    ///
    /// Progress is never correlated from a JSON-RPC request ID alone: a peer
    /// notification belongs to this request only when it repeats this marker.
    advertised_progress_marker: Option<ProgressMarker>,
    last_progress: Option<f64>,
    method: String,
}

/// Returns the exact progress marker a client request advertised, when valid.
///
/// A generic raw request may omit `_meta` or supply an invalid marker. Neither
/// case grants a peer progress notification ownership of that execution.
fn advertised_progress_marker(params: Option<&Value>) -> Option<ProgressMarker> {
    let marker = params
        .and_then(Value::as_object)
        .and_then(|params| params.get("_meta"))
        .and_then(Value::as_object)
        .and_then(|meta| meta.get("progressToken"))?;
    serde_json::from_value(marker.clone()).ok()
}

/// Returns one valid typed marker from a peer progress notification.
fn progress_notification_marker(notification: &JsonRpcRequest) -> Option<ProgressMarker> {
    let marker = notification
        .params
        .as_ref()
        .and_then(Value::as_object)
        .and_then(|params| params.get("progressToken"))?;
    serde_json::from_value(marker.clone()).ok()
}

/// Shared dropped-owner marker. This replaces the executor's local
/// `Rc<Cell<bool>>` ownership so cloned execution handles can cross the
/// negotiated stdio boundary without relying on thread-local state.
#[derive(Clone, Debug)]
struct OwnerDropped(Arc<AtomicBool>);

impl OwnerDropped {
    fn new() -> Self {
        Self(Arc::new(AtomicBool::new(false)))
    }

    fn get(&self) -> bool {
        self.0.load(Ordering::Acquire)
    }

    fn set(&self, value: bool) {
        self.0.store(value, Ordering::Release);
    }
}

/// Mutex-backed executor state ownership.
///
/// The transport-neutral adapter retains its historical synchronous API. The
/// negotiated stdio client uses its own sole ingress arbiter and shared
/// response registry; this wrapper removes the old `Rc<RefCell<_>>` ownership
/// from public request handles.
#[derive(Debug)]
struct SharedExecutorState<T>(Arc<Mutex<ExecutorState<T>>>);

impl<T> Clone for SharedExecutorState<T> {
    fn clone(&self) -> Self {
        Self(Arc::clone(&self.0))
    }
}

impl<T> SharedExecutorState<T> {
    fn new(state: ExecutorState<T>) -> Self {
        Self(Arc::new(Mutex::new(state)))
    }

    fn borrow(&self) -> MutexGuard<'_, ExecutorState<T>> {
        self.0
            .lock()
            .expect("request executor state mutex poisoned")
    }

    fn borrow_mut(&self) -> MutexGuard<'_, ExecutorState<T>> {
        self.borrow()
    }

    fn try_borrow_mut(&self) -> Result<MutexGuard<'_, ExecutorState<T>>, ()> {
        self.0.try_lock().map_err(|_| ())
    }

    fn ptr_eq(left: &Self, right: &Self) -> bool {
        Arc::ptr_eq(&left.0, &right.0)
    }
}

#[cfg(feature = "tasks")]
#[derive(Clone, Debug)]
enum TaskExecutionOperation {
    ToolCall,
    Get(TaskId),
    Update(TaskId),
    Cancel(TaskId),
    Subscription,
}

#[cfg(feature = "tasks")]
#[derive(Debug)]
struct TaskSubscription {
    requested_filter: SubscriptionFilter,
    accepted_filter: Option<SubscriptionFilter>,
    notifications: VecDeque<TaskStatusNotification>,
}

#[derive(Debug)]
enum ExecutionOutcome {
    Response(Box<DecodedFinalResponse>),
    Failure(McpError),
}

/// One admitted JSON-RPC final response and its lossless result envelope.
///
/// JSON-RPC error responses have no result envelope, so their `decoded` field
/// is absent and the caller receives the peer's typed JSON-RPC error instead.
#[derive(Debug)]
struct DecodedFinalResponse {
    response: JsonRpcResponse,
    raw_result: Option<String>,
    decoded: Option<AdmittedFinalResult>,
}

#[derive(Debug)]
enum AdmittedFinalResult {
    Core(Box<DecodedResult>, Option<ResultPeerDiagnostic>),
    Task,
    /// `subscriptions/listen` completion is method-shaped, not a generic
    /// complete-result payload. Keep the admitted source for the typed
    /// listener instead of forcing it through [`CoreResultDiscriminatorPolicy`].
    SubscriptionListen,
}

impl DecodedFinalResponse {
    fn admit(
        response: JsonRpcResponse,
        raw_result: Option<String>,
        peer_era: ResultPeerEra,
        accepts_task_result: bool,
        retain_subscription_listen: bool,
    ) -> McpResult<Self> {
        if raw_result.is_some() && response.result.is_none() {
            return Err(McpError::invalid_request(
                "Peer final result source does not match the response kind",
            ));
        }
        if let Some(source) = raw_result.as_deref() {
            let admitted: Value = serde_json::from_str(source).map_err(|_| {
                McpError::invalid_request("Peer final result source is not valid JSON")
            })?;
            if response.result.as_ref() != Some(&admitted) {
                return Err(McpError::invalid_request(
                    "Peer final result source differs from its typed response",
                ));
            }
        }
        let decoded = response
            .result
            .as_ref()
            .map(|result| {
                if retain_subscription_listen {
                    return Ok(AdmittedFinalResult::SubscriptionListen);
                }
                if accepts_task_result
                    && result.get("resultType").and_then(Value::as_str) == Some("task")
                {
                    return Ok(AdmittedFinalResult::Task);
                }
                let encoded = raw_result.as_deref().map_or_else(
                    || {
                        serde_json::to_string(result).map_err(|_| {
                            McpError::invalid_request(
                                "Peer final result could not be encoded for protocol admission",
                            )
                        })
                    },
                    |source| Ok(source.to_owned()),
                )?;
                decode_peer_result(&encoded, peer_era, &CoreResultDiscriminatorPolicy)
                    .map_err(|_| {
                        McpError::invalid_request("Peer final result failed protocol decoding")
                    })
                    .map(|(result, diagnostic)| {
                        AdmittedFinalResult::Core(Box::new(result), diagnostic)
                    })
            })
            .transpose()?;
        Ok(Self {
            response,
            raw_result,
            decoded,
        })
    }

    fn into_decoded(self) -> McpResult<(DecodedResult, Option<ResultPeerDiagnostic>)> {
        match self.decoded {
            Some(AdmittedFinalResult::Core(decoded, diagnostic)) => Ok((*decoded, diagnostic)),
            Some(AdmittedFinalResult::Task) => Err(McpError::invalid_request(
                "Tasks result requires its typed Tasks execution surface",
            )),
            Some(AdmittedFinalResult::SubscriptionListen) => Err(McpError::invalid_request(
                "Listen result requires its typed subscription surface",
            )),
            None => {
                let error = self
                    .response
                    .error
                    .expect("validated JSON-RPC final responses have either result or error");
                match error.data {
                    Some(data) => Err(McpError::with_data(
                        error
                            .code
                            .as_i32()
                            .map(McpErrorCode::from)
                            .unwrap_or(McpErrorCode::InternalError),
                        error.message,
                        data,
                    )),
                    None => Err(McpError::new(
                        error
                            .code
                            .as_i32()
                            .map(McpErrorCode::from)
                            .unwrap_or(McpErrorCode::InternalError),
                        error.message,
                    )),
                }
            }
        }
    }
}

#[derive(Debug)]
struct Tombstone {
    generation: u64,
    expires_at: Instant,
    /// Peer-produced terminal outcomes remain observable as duplicate
    /// diagnostics; abandoned-owner finals are silently discarded instead.
    retain_late_response_diagnostic: bool,
}

#[derive(Debug)]
struct DeferredDropCancellation {
    request_id: RequestId,
    generation: u64,
    message: JsonRpcMessage,
}

#[derive(Debug)]
struct ExecutorState<T> {
    transport: T,
    receive_frame: Option<fn(&mut T, &Cx) -> Result<ReceivedTransportFrame, TransportError>>,
    ingress_owner: IngressOwner,
    pending: HashMap<CorrelationKey, PendingExecution>,
    completed: HashMap<(RequestId, u64), ExecutionOutcome>,
    tombstones: HashMap<CorrelationKey, Tombstone>,
    notifications: VecDeque<JsonRpcRequest>,
    reverse_requests: VecDeque<ReverseRequest>,
    pending_reverse_requests: HashMap<CorrelationKey, ActiveReverseRequest>,
    stream_notifications: HashMap<(RequestId, u64), VecDeque<JsonRpcRequest>>,
    uncorrelated_responses: VecDeque<JsonRpcResponse>,
    terminal_records: HashMap<(RequestId, u64), ExecutionTerminalRecord>,
    terminal_expirations: HashMap<(RequestId, u64), Instant>,
    cancellation_events: VecDeque<CancellationRequested>,
    deferred_drop_cancellations: VecDeque<DeferredDropCancellation>,
    #[cfg(feature = "tasks")]
    task_subscriptions: HashMap<(RequestId, u64), TaskSubscription>,
    next_generation: u64,
    result_peer_era: ResultPeerEra,
    terminal_error: Option<McpError>,
    shutdown: bool,
}

/// The one authority allowed to take the next inbound transport frame.
///
/// An executor starts unclaimed. Its ordinary [`RequestExecutor::drive`]
/// claims self-reader mode, while [`RequestExecutor::drive_frame`] claims the
/// externally driven mode used by a connection-owned selected-I/O arbiter.
/// The modes never switch for a live executor, preventing a response frame
/// from being consumed by a second reader after a request owner has chosen
/// its ingress path.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum IngressOwner {
    Unclaimed,
    SelfReader,
    ExternalDriver,
}

impl<T> ExecutorState<T> {
    fn retain_notification(&mut self, request: JsonRpcRequest) -> bool {
        if self.notifications.len() >= MAX_RETAINED_PEER_ACTIVITY {
            return false;
        }
        self.notifications.push_back(request);
        true
    }

    fn retain_uncorrelated_response(&mut self, response: JsonRpcResponse) -> bool {
        if self.uncorrelated_responses.len() >= MAX_RETAINED_PEER_ACTIVITY {
            return false;
        }
        self.uncorrelated_responses.push_back(response);
        true
    }

    fn retain_reverse_request(&mut self, request: JsonRpcRequest) -> McpResult<()> {
        let request_id = request.id.clone().ok_or_else(|| {
            McpError::invalid_request("Client reverse request omitted a JSON-RPC request ID")
        })?;
        let key = request_id.correlation_key().map_err(|_| {
            McpError::invalid_request("Client reverse request has an invalid JSON-RPC request ID")
        })?;
        if self.pending_reverse_requests.contains_key(&key) {
            return Err(McpError::invalid_request(
                "Client reverse request ID is already active",
            ));
        }
        if self.reverse_requests.len() >= MAX_RETAINED_PEER_ACTIVITY {
            return Err(McpError::internal_error(
                "Client reverse-request queue is full",
            ));
        }
        let cancellation = ReverseRequestCancellation::new();
        let owner = Arc::new(());
        self.pending_reverse_requests.insert(
            key,
            ActiveReverseRequest {
                request_id: request_id.clone(),
                cancellation: cancellation.clone(),
                owner: Arc::clone(&owner),
            },
        );
        self.reverse_requests.push_back(ReverseRequest {
            request,
            cancellation,
            owner,
        });
        Ok(())
    }

    fn prune_tombstones(&mut self, now: Instant) {
        self.tombstones
            .retain(|_, tombstone| tombstone.expires_at > now);
    }

    fn retain_terminal(
        &mut self,
        key: (RequestId, u64),
        record: ExecutionTerminalRecord,
        outcome: ExecutionOutcome,
    ) {
        let now = Instant::now();
        let expires_at = now.checked_add(DEFAULT_TOMBSTONE_RETENTION).unwrap_or(now);
        self.terminal_records.insert(key.clone(), record);
        self.terminal_expirations.insert(key.clone(), expires_at);
        self.completed.insert(key, outcome);
    }

    fn release_terminal(&mut self, key: &(RequestId, u64)) {
        self.completed.remove(key);
        self.terminal_records.remove(key);
        self.terminal_expirations.remove(key);
    }

    fn prune_retained_terminals(&mut self, now: Instant) {
        let expired = self
            .terminal_expirations
            .iter()
            .filter_map(|(key, expires_at)| (*expires_at <= now).then_some(key.clone()))
            .collect::<Vec<_>>();
        for key in expired {
            self.release_terminal(&key);
            self.stream_notifications.remove(&key);
            #[cfg(feature = "tasks")]
            self.task_subscriptions.remove(&key);
        }
    }

    fn cancel_reverse_requests(&mut self) {
        for reverse_request in self.pending_reverse_requests.values() {
            reverse_request.cancellation.cancel();
        }
        self.pending_reverse_requests.clear();
        self.reverse_requests.clear();
    }

    fn fail_all(&mut self, error: McpError, reason: ExecutionTerminalReason) {
        if self.terminal_error.is_some() {
            return;
        }
        self.terminal_error = Some(error.clone());
        self.tombstones.clear();
        self.cancel_reverse_requests();
        #[cfg(feature = "tasks")]
        self.task_subscriptions.clear();
        self.deferred_drop_cancellations.clear();
        let pending = std::mem::take(&mut self.pending);
        for (_, pending) in pending {
            let request_id = pending.record.request_id.clone();
            self.stream_notifications
                .remove(&(request_id.clone(), pending.record.execution_generation));
            self.retain_terminal(
                (request_id.clone(), pending.record.execution_generation),
                ExecutionTerminalRecord {
                    terminal_state: ExecutionTerminalState::Failed,
                    terminal_reason: reason,
                    final_delivered: false,
                    cancellation_committed: false,
                    cancellation_transport_attempts: 0,
                    local_cancellation_event: false,
                    waiter_release: true,
                    tombstone: false,
                },
                ExecutionOutcome::Failure(error.clone()),
            );
        }
    }
}

/// A transport-neutral request executor.
///
/// Multiple executions may be started before either is waited. The one
/// transport reader routes each final response by its exact request ID, so a
/// reordered final response becomes available to its owner rather than being
/// consumed by the request currently driving the reader.
#[derive(Debug)]
pub struct RequestExecutor<T> {
    state: SharedExecutorState<T>,
    tombstone_retention: Duration,
    max_in_flight: usize,
    max_correlations: usize,
}

impl<T> Clone for RequestExecutor<T> {
    fn clone(&self) -> Self {
        Self {
            state: self.state.clone(),
            tombstone_retention: self.tombstone_retention,
            max_in_flight: self.max_in_flight,
            max_correlations: self.max_correlations,
        }
    }
}

impl<T> RequestExecutor<T>
where
    T: Transport,
{
    /// Creates an executor with the frozen CLT-01 A correlation bounds.
    #[must_use]
    pub fn new(transport: T) -> Self {
        Self::with_result_peer_era(transport, ResultPeerEra::Legacy)
    }

    /// Creates an executor bound to the negotiated peer era.
    ///
    /// The caller must select this from the completed initialize handshake and
    /// keep it immutable for the connection. The era controls exact result
    /// decoding and whether legacy server-to-client requests reach the
    /// handler boundary. [`Self::new`] retains the legacy-era default for
    /// callers that have not yet integrated negotiation.
    #[must_use]
    pub fn with_result_peer_era(transport: T, result_peer_era: ResultPeerEra) -> Self {
        Self::with_source_frame_receiver(transport, result_peer_era, None)
    }

    /// Creates an executor for a transport whose MCP era was already selected.
    ///
    /// Custom transports must complete their own bounded handshake before
    /// constructing this executor. The selected era is then immutable for the
    /// connection: modern executions use final-result decoding plus
    /// request-owned progress and subscription handling, while exact legacy
    /// executions retain the 2024-11-05 compatibility path. This constructor
    /// deliberately has no `Auto` policy or retry surface, so it cannot replay
    /// requests across transport instances.
    #[must_use]
    pub fn with_protocol_era(transport: T, protocol_era: ProtocolEra) -> Self {
        Self::with_result_peer_era(transport, protocol_era.into())
    }

    /// Creates an executor whose one transport reader can retain admitted
    /// source frames.
    ///
    /// The receiver remains owned by this executor's transport; callers use
    /// this only for a transport that has already selected one immutable peer
    /// era. Passing `None` retains the ordinary typed [`Transport`] ingress
    /// behavior used by [`Self::new`] and [`Self::with_result_peer_era`].
    #[must_use]
    pub fn with_source_frame_receiver(
        transport: T,
        result_peer_era: ResultPeerEra,
        receive_frame: Option<fn(&mut T, &Cx) -> Result<ReceivedTransportFrame, TransportError>>,
    ) -> Self {
        Self {
            state: SharedExecutorState::new(ExecutorState {
                transport,
                receive_frame,
                ingress_owner: IngressOwner::Unclaimed,
                pending: HashMap::new(),
                completed: HashMap::new(),
                tombstones: HashMap::new(),
                notifications: VecDeque::new(),
                reverse_requests: VecDeque::new(),
                pending_reverse_requests: HashMap::new(),
                stream_notifications: HashMap::new(),
                uncorrelated_responses: VecDeque::new(),
                terminal_records: HashMap::new(),
                terminal_expirations: HashMap::new(),
                cancellation_events: VecDeque::new(),
                deferred_drop_cancellations: VecDeque::new(),
                #[cfg(feature = "tasks")]
                task_subscriptions: HashMap::new(),
                next_generation: 0,
                result_peer_era,
                terminal_error: None,
                shutdown: false,
            }),
            tombstone_retention: DEFAULT_TOMBSTONE_RETENTION,
            max_in_flight: DEFAULT_MAX_IN_FLIGHT_EXECUTIONS,
            max_correlations: DEFAULT_MAX_RESPONSE_CORRELATIONS,
        }
    }

    /// Returns the immutable peer era governing this multiplexed connection.
    #[must_use]
    pub fn result_peer_era(&self) -> ResultPeerEra {
        self.state.borrow().result_peer_era
    }

    /// Returns the immutable MCP era selected before this executor was built.
    #[must_use]
    pub fn protocol_era(&self) -> ProtocolEra {
        match self.result_peer_era() {
            ResultPeerEra::Legacy => ProtocolEra::Legacy2024,
            ResultPeerEra::Modern => ProtocolEra::Modern2026,
        }
    }

    /// Returns whether an admitted final response belongs to this executor.
    ///
    /// A connection-owned ingress arbiter uses this before handing a response
    /// frame to the executor. Retained tombstones count as owned so a late
    /// exact final cannot fall through to an adjacent request registry.
    pub(crate) fn owns_response_id(&self, response_id: &RequestId) -> bool {
        let Ok(key) = response_id.correlation_key() else {
            return false;
        };
        let state = self.state.borrow();
        state.pending.contains_key(&key) || state.tombstones.contains_key(&key)
    }

    /// Returns whether a progress notification names one live request owner.
    ///
    /// The caller must still pass the full admitted frame to [`Self::drive_frame`]
    /// so semantic validation, stream retention, and idle-deadline policy
    /// remain centralized here.
    pub(crate) fn owns_progress_notification(&self, notification: &JsonRpcRequest) -> bool {
        if notification.id.is_some() || notification.method != "notifications/progress" {
            return false;
        }
        let Some(marker) = progress_notification_marker(notification) else {
            return false;
        };
        self.state
            .borrow()
            .pending
            .values()
            .filter(|pending| pending.advertised_progress_marker.as_ref() == Some(&marker))
            .take(2)
            .count()
            == 1
    }

    /// Returns whether a modern server cancellation names this executor's live
    /// `subscriptions/listen` owner.
    ///
    /// Final MCP limits server-originated wire cancellation to that stream.
    /// A connection ingress arbiter uses this predicate before handing the
    /// complete admitted frame to [`Self::drive_frame`], which performs the
    /// terminal transition. Foreign, malformed, and metadata-conflicting
    /// controls deliberately remain outside this executor.
    pub(crate) fn owns_modern_subscription_cancellation(
        &self,
        notification: &JsonRpcRequest,
    ) -> bool {
        let state = self.state.borrow();
        if state.result_peer_era != ResultPeerEra::Modern {
            return false;
        }
        let Ok(CancellationWireMessage::Modern2026 { params, .. }) =
            CancellationWireMessage::decode(
                ProtocolEra::Modern2026,
                CancellationSender::Server,
                notification,
            )
        else {
            return false;
        };
        if let Some(metadata_subscription_id) = params
            .meta
            .as_ref()
            .and_then(|metadata| metadata.get(FINAL_SUBSCRIPTION_ID_META_KEY))
            .and_then(|value| serde_json::from_value::<RequestId>(value.clone()).ok())
            && !metadata_subscription_id.correlates_with(&params.request_id)
        {
            return false;
        }
        state.pending.values().any(|pending| {
            pending.method == SUBSCRIPTIONS_LISTEN
                && pending
                    .record
                    .request_id
                    .correlates_with(&params.request_id)
        })
    }

    /// Starts one request-owned execution after its request is committed.
    ///
    /// `request` must be a JSON-RPC request with an ID. Notifications have no
    /// final result slot and are intentionally rejected by this surface.
    pub fn execute(&self, cx: &Cx, request: Request) -> McpResult<RequestExecution<T>> {
        self.execute_with_timeout_policy(cx, request, RequestTimeoutPolicy::default())
    }

    /// Starts an execution with a per-request bounded timeout policy.
    pub fn execute_with_timeout_policy(
        &self,
        cx: &Cx,
        request: Request,
        timeout_policy: RequestTimeoutPolicy,
    ) -> McpResult<RequestExecution<T>> {
        if cx.checkpoint().is_err() {
            return Err(McpError::request_cancelled());
        }
        let request_id = request.id.clone().ok_or_else(|| {
            McpError::invalid_params("Request execution requires a JSON-RPC request ID")
        })?;
        let correlation_key = request_id.correlation_key().map_err(|_| {
            McpError::invalid_params("Request execution requires a valid JSON-RPC request ID")
        })?;
        let advertised_progress_marker = advertised_progress_marker(request.params.as_ref());

        let mut state = self.state.borrow_mut();
        self.drain_abandoned_locked(cx, &mut state)?;
        state.prune_tombstones(Instant::now());
        state.prune_retained_terminals(Instant::now());
        if state.shutdown {
            return Err(McpError::internal_error(
                "Client request executor is shut down",
            ));
        }
        if let Some(error) = &state.terminal_error {
            return Err(error.clone());
        }
        if state.pending.contains_key(&correlation_key) {
            return Err(McpError::invalid_request("Duplicate in-flight request ID"));
        }
        if state.tombstones.contains_key(&correlation_key) {
            return Err(McpError::invalid_request(
                "Tombstoned request ID cannot be reused",
            ));
        }
        if state.pending.len() >= self.max_in_flight {
            return Err(McpError::internal_error(
                "Client in-flight execution limit reached",
            ));
        }
        let retained_terminals = state.completed.len().max(state.terminal_records.len());
        if state
            .pending
            .len()
            .saturating_add(state.tombstones.len())
            .saturating_add(retained_terminals)
            >= self.max_correlations
        {
            return Err(McpError::internal_error(
                "Client response correlation limit reached",
            ));
        }
        let generation = state
            .next_generation
            .checked_add(1)
            .ok_or_else(|| McpError::internal_error("Client execution generation exhausted"))?;
        state.next_generation = generation;

        state
            .transport
            .send(cx, &JsonRpcMessage::Request(request.clone()))
            .map_err(|error| self.handle_send_error_locked(&mut state, error))?;

        let committed_at = Instant::now();
        let idle_deadline = committed_at
            .checked_add(timeout_policy.idle_timeout())
            .ok_or_else(|| {
                McpError::internal_error("Client execution idle deadline exceeds the clock range")
            })?;
        let absolute_deadline = committed_at
            .checked_add(timeout_policy.absolute_timeout())
            .ok_or_else(|| {
                McpError::internal_error(
                    "Client execution absolute deadline exceeds the clock range",
                )
            })?;
        let owner_dropped = OwnerDropped::new();
        state.pending.insert(
            correlation_key.clone(),
            PendingExecution {
                record: PendingRequestRecord {
                    correlation_key,
                    request_id: request_id.clone(),
                    execution_generation: generation,
                    request_state: ExecutionTerminalState::Pending,
                    send_committed: true,
                    idle_deadline,
                    absolute_deadline,
                    terminal_state: ExecutionTerminalState::Pending,
                    cancellation_committed: false,
                    tombstone_generation: None,
                },
                owner_dropped: owner_dropped.clone(),
                timeout_policy,
                advertised_progress_marker,
                last_progress: None,
                method: request.method.clone(),
            },
        );

        Ok(RequestExecution {
            request_id,
            generation,
            owner_dropped,
            state: self.state.clone(),
            method: request.method,
            params: request.params,
            #[cfg(feature = "tasks")]
            task_operation: None,
            tombstone_retention: self.tombstone_retention,
            completed: false,
        })
    }

    #[cfg(feature = "tasks")]
    pub fn execute_task_tool_call(
        &self,
        cx: &Cx,
        request: Request,
    ) -> McpResult<RequestExecution<T>> {
        self.require_modern_tasks_era()?;
        let core_request = self.decode_final_core_request(&request)?;
        if core_request.method() != TOOLS_CALL {
            return Err(McpError::invalid_params(
                "Tasks tool execution requires a final tools/call request",
            ));
        }
        let mut execution = self.execute(cx, request)?;
        execution.task_operation = Some(TaskExecutionOperation::ToolCall);
        Ok(execution)
    }

    #[cfg(feature = "tasks")]
    pub fn execute_tasks_get(&self, cx: &Cx, request: Request) -> McpResult<RequestExecution<T>> {
        self.require_modern_tasks_era()?;
        let task = self.decode_tasks_get_request(&request)?;
        let mut execution = self.execute(cx, request)?;
        execution.task_operation = Some(TaskExecutionOperation::Get(task.task_id));
        Ok(execution)
    }

    #[cfg(feature = "tasks")]
    pub fn execute_tasks_update(
        &self,
        cx: &Cx,
        request: Request,
        task: &Task,
    ) -> McpResult<RequestExecution<T>> {
        self.require_modern_tasks_era()?;
        let Task::InputRequired {
            base,
            input_requests,
        } = task
        else {
            return Err(McpError::invalid_params(
                "tasks/update requires an input_required final task",
            ));
        };
        let ledger = TaskInputLedger::from_requests(input_requests).map_err(|_| {
            McpError::invalid_params("Task input requests are not an admitted ledger")
        })?;
        let update = self.decode_tasks_update_request(&request, &ledger)?;
        if update.task_id != base.task_id {
            return Err(McpError::invalid_params(
                "tasks/update request taskId does not match the retained task",
            ));
        }
        let mut execution = self.execute(cx, request)?;
        execution.task_operation = Some(TaskExecutionOperation::Update(update.task_id));
        Ok(execution)
    }

    #[cfg(feature = "tasks")]
    pub fn execute_tasks_cancel(
        &self,
        cx: &Cx,
        request: Request,
    ) -> McpResult<RequestExecution<T>> {
        self.require_modern_tasks_era()?;
        let task = self.decode_tasks_cancel_request(&request)?;
        let mut execution = self.execute(cx, request)?;
        execution.task_operation = Some(TaskExecutionOperation::Cancel(task.task_id));
        Ok(execution)
    }

    #[cfg(feature = "tasks")]
    pub fn execute_tasks_subscription(
        &self,
        cx: &Cx,
        request: Request,
    ) -> McpResult<RequestExecution<T>> {
        self.require_modern_tasks_era()?;
        let requested_filter = self.decode_tasks_subscription_request(&request)?;
        let mut execution = self.execute(cx, request)?;
        execution.task_operation = Some(TaskExecutionOperation::Subscription);
        self.state.borrow_mut().task_subscriptions.insert(
            (execution.request_id.clone(), execution.generation),
            TaskSubscription {
                requested_filter,
                accepted_filter: None,
                notifications: VecDeque::new(),
            },
        );
        Ok(execution)
    }

    /// Drives exactly one peer frame through the correlation registry.
    ///
    /// A malformed or closed transport fails all known owners with the same
    /// typed local outcome and never sends a JSON-RPC response back to the
    /// peer. Notifications are retained separately and never consume a final
    /// response slot.
    pub fn drive(&self, cx: &Cx) -> McpResult<()> {
        let mut state = self.state.borrow_mut();
        self.claim_ingress_owner_locked(&mut state, IngressOwner::SelfReader)?;
        self.prepare_drive_locked(cx, &mut state)?;
        let (message, raw_result) = match state.receive_frame {
            Some(receive_frame) => {
                let frame = match receive_frame(&mut state.transport, cx) {
                    Ok(frame) => frame,
                    Err(error) => {
                        let error = transport_error_to_mcp(error);
                        state.fail_all(error.clone(), ExecutionTerminalReason::ConnectionLost);
                        return Err(error);
                    }
                };
                let (message, source) = frame.into_parts();
                let raw_result = match exact_result_source_from_admitted_frame(&message, &source) {
                    Ok(raw_result) => raw_result,
                    Err(error) => {
                        state.fail_all(error.clone(), ExecutionTerminalReason::PeerProtocol);
                        return Err(error);
                    }
                };
                (message, raw_result)
            }
            None => match state.transport.recv(cx) {
                // A typed Transport has already discarded the exact frame
                // spelling. Preserve that distinction: protocol admission may
                // encode the typed value internally, but callers must never
                // receive reconstructed JSON as a peer-authored raw source.
                Ok(message) => (message, None),
                Err(error) => {
                    let error = transport_error_to_mcp(error);
                    state.fail_all(error.clone(), ExecutionTerminalReason::ConnectionLost);
                    return Err(error);
                }
            },
        };
        self.route_inbound_message_locked(cx, &mut state, message, raw_result)
    }

    /// Drives one source-preserving peer frame through the correlation registry.
    ///
    /// The frame is admitted by the sole negotiated transport reader before it
    /// reaches this executor. Successful JSON-RPC responses retain the exact
    /// `result` member source from that same frame; it is never reconstructed
    /// from the typed value. Requests and notifications follow the identical
    /// cancellation, reverse-request, and request-owned progress routes used
    /// by [`Self::drive`].
    ///
    /// This method performs no transport read. A negotiated client can retain
    /// its one reader and pass each admitted frame here without creating a
    /// competing response path.
    pub fn drive_frame(&self, cx: &Cx, frame: ReceivedTransportFrame) -> McpResult<()> {
        let (message, source) = frame.into_parts();
        let mut state = self.state.borrow_mut();
        self.claim_ingress_owner_locked(&mut state, IngressOwner::ExternalDriver)?;
        self.prepare_drive_locked(cx, &mut state)?;
        let raw_result = match exact_result_source_from_admitted_frame(&message, &source) {
            Ok(raw_result) => raw_result,
            Err(error) => {
                state.fail_all(error.clone(), ExecutionTerminalReason::PeerProtocol);
                return Err(error);
            }
        };
        self.route_inbound_message_locked(cx, &mut state, message, raw_result)
    }

    fn claim_ingress_owner_locked(
        &self,
        state: &mut ExecutorState<T>,
        requested_owner: IngressOwner,
    ) -> McpResult<()> {
        match state.ingress_owner {
            IngressOwner::Unclaimed => {
                state.ingress_owner = requested_owner;
                Ok(())
            }
            owner if owner == requested_owner => Ok(()),
            IngressOwner::SelfReader => Err(McpError::invalid_request(
                "Client request executor already owns transport ingress",
            )),
            IngressOwner::ExternalDriver => Err(McpError::invalid_request(
                "Client request executor is driven by external admitted frames",
            )),
        }
    }

    fn prepare_drive_locked(&self, cx: &Cx, state: &mut ExecutorState<T>) -> McpResult<()> {
        self.drain_abandoned_locked(cx, state)?;
        self.expire_timeouts_locked(cx, state, Instant::now())?;
        if let Some(error) = &state.terminal_error {
            return Err(error.clone());
        }
        Ok(())
    }

    fn route_inbound_message_locked(
        &self,
        cx: &Cx,
        state: &mut ExecutorState<T>,
        message: JsonRpcMessage,
        raw_result: Option<String>,
    ) -> McpResult<()> {
        if message.validate().is_err() {
            let error = McpError::invalid_request("Peer sent an invalid JSON-RPC message");
            state.fail_all(error.clone(), ExecutionTerminalReason::ConnectionLost);
            return Err(error);
        }
        match message {
            JsonRpcMessage::Response(response) => {
                self.route_response_with_raw_result_locked(state, response, raw_result)?;
            }
            JsonRpcMessage::Request(request) => {
                if request.method == "notifications/cancelled" {
                    self.route_cancellation_notification_locked(cx, state, &request)?;
                } else if request.id.is_some() {
                    if !server_request_is_admitted(state.result_peer_era, &request) {
                        self.reject_reverse_request_locked(cx, state, request)?;
                    } else if !legacy_reverse_request_params_are_admitted(
                        state.result_peer_era,
                        &request,
                    ) {
                        self.reject_reverse_request_with_error_locked(
                            cx,
                            state,
                            request,
                            McpError::invalid_params(
                                "Peer reverse request parameters are not exact MCP 2024-11-05",
                            ),
                        )?;
                    } else if let Err(error) = state.retain_reverse_request(request) {
                        state.fail_all(error.clone(), ExecutionTerminalReason::ConnectionLost);
                        return Err(error);
                    }
                } else {
                    #[cfg(feature = "tasks")]
                    let handled = self
                        .route_task_subscription_acknowledgement_locked(state, &request)?
                        || self.route_task_subscription_notification_locked(state, &request)?
                        || self.route_stream_notification_locked(state, &request)?;
                    #[cfg(not(feature = "tasks"))]
                    let handled = self.route_stream_notification_locked(state, &request)?;
                    if !handled && !state.retain_notification(request) {
                        let error = McpError::internal_error("Client peer-activity queue is full");
                        state.fail_all(error.clone(), ExecutionTerminalReason::ConnectionLost);
                        return Err(error);
                    }
                }
            }
        }
        Ok(())
    }

    /// Routes one already-admitted final response while retaining its exact
    /// result-member source for request-owned decoding.
    ///
    /// This is the exact-source ingress companion to [`Self::drive`]. The
    /// typed transport path does not fabricate a source after decoding; a raw
    /// transport admission supplies the peer's original result source here.
    pub fn route_response_with_raw_result(
        &self,
        cx: &Cx,
        response: JsonRpcResponse,
        raw_result: Option<String>,
    ) -> McpResult<()> {
        let mut state = self.state.borrow_mut();
        self.drain_abandoned_locked(cx, &mut state)?;
        self.expire_timeouts_locked(cx, &mut state, Instant::now())?;
        if state.shutdown {
            return Err(McpError::internal_error(
                "Client request executor is shut down",
            ));
        }
        if let Some(error) = &state.terminal_error {
            return Err(error.clone());
        }
        if response.validate().is_err() {
            let error = McpError::invalid_request("Peer sent an invalid JSON-RPC response");
            state.fail_all(error.clone(), ExecutionTerminalReason::ConnectionLost);
            return Err(error);
        }
        self.route_response_with_raw_result_locked(&mut state, response, raw_result)?;
        Ok(())
    }

    /// Waits for one execution's exact final response while routing peer
    /// traffic for every other live execution.
    pub fn wait(&self, cx: &Cx, execution: &mut RequestExecution<T>) -> McpResult<JsonRpcResponse> {
        let (outcome, _) = self.wait_for_terminal(cx, execution)?;
        match outcome {
            ExecutionOutcome::Response(response) => Ok(response.response),
            ExecutionOutcome::Failure(error) => Err(error),
        }
    }

    /// Takes an already-routed final response without reading the transport.
    ///
    /// A connection-owned ingress driver uses this for request-owned handles:
    /// it alone admits frames through [`Self::drive_frame`], while callers
    /// observe their own completed execution without accidentally claiming a
    /// second transport reader. The returned response retains the normal
    /// JSON-RPC error envelope; use [`Self::wait`] when self-reader mode is
    /// intentionally selected instead.
    pub fn try_take_response(
        &self,
        execution: &mut RequestExecution<T>,
    ) -> McpResult<Option<JsonRpcResponse>> {
        execution.ensure_owner(&self.state)?;
        let Some((outcome, _)) = execution.take_terminal_outcome()? else {
            return Ok(None);
        };
        match outcome {
            ExecutionOutcome::Response(response) => Ok(Some(response.response)),
            ExecutionOutcome::Failure(error) => Err(error),
        }
    }

    /// Takes an already-routed final response with its exact admitted result
    /// source, without reading the transport.
    ///
    /// This is the source-preserving companion to [`Self::try_take_response`]
    /// for a negotiated connection whose Client owns transport ingress.
    pub fn try_take_response_with_raw_result(
        &self,
        execution: &mut RequestExecution<T>,
    ) -> McpResult<Option<(JsonRpcResponse, Option<String>)>> {
        execution.ensure_owner(&self.state)?;
        let Some((outcome, _)) = execution.take_terminal_outcome()? else {
            return Ok(None);
        };
        match outcome {
            ExecutionOutcome::Response(response) => {
                Ok(Some((response.response, response.raw_result)))
            }
            ExecutionOutcome::Failure(error) => Err(error),
        }
    }

    /// Waits for a final response and returns preceding request-owned progress.
    ///
    /// The returned stream preserves peer arrival order and is drained exactly
    /// once with the terminal outcome, so a caller cannot accidentally reuse
    /// stale progress after consuming the final response.
    pub fn wait_with_stream(
        &self,
        cx: &Cx,
        execution: &mut RequestExecution<T>,
    ) -> McpResult<(JsonRpcResponse, Vec<JsonRpcRequest>)> {
        let (outcome, stream) = self.wait_for_terminal(cx, execution)?;
        match outcome {
            ExecutionOutcome::Response(response) => Ok((response.response, stream)),
            ExecutionOutcome::Failure(error) => Err(error),
        }
    }

    /// Waits for a final response and returns its exact admitted result source.
    ///
    /// The source is absent for a JSON-RPC error response and for typed
    /// transport ingress that could not retain raw JSON.
    pub fn wait_with_raw_result(
        &self,
        cx: &Cx,
        execution: &mut RequestExecution<T>,
    ) -> McpResult<(JsonRpcResponse, Option<String>)> {
        let (outcome, _) = self.wait_for_terminal(cx, execution)?;
        match outcome {
            ExecutionOutcome::Response(response) => Ok((response.response, response.raw_result)),
            ExecutionOutcome::Failure(error) => Err(error),
        }
    }

    /// Waits for and decodes a final MCP result envelope.
    ///
    /// JSON-RPC errors become their local [`McpError`] equivalent. Successful
    /// result envelopes are decoded through the negotiated peer era, retaining
    /// inert unknown members and exact JSON-number lexemes.
    pub fn wait_decoded(
        &self,
        cx: &Cx,
        execution: &mut RequestExecution<T>,
    ) -> McpResult<(DecodedResult, Option<ResultPeerDiagnostic>)> {
        let (outcome, _) = self.wait_for_terminal(cx, execution)?;
        match outcome {
            ExecutionOutcome::Response(response) => (*response).into_decoded(),
            ExecutionOutcome::Failure(error) => Err(error),
        }
    }

    /// Waits for a decoded final result and all preceding request-owned progress.
    pub fn wait_decoded_with_stream(
        &self,
        cx: &Cx,
        execution: &mut RequestExecution<T>,
    ) -> McpResult<(
        DecodedResult,
        Option<ResultPeerDiagnostic>,
        Vec<JsonRpcRequest>,
    )> {
        let (outcome, stream) = self.wait_for_terminal(cx, execution)?;
        match outcome {
            ExecutionOutcome::Response(response) => {
                let (decoded, diagnostic) = (*response).into_decoded()?;
                Ok((decoded, diagnostic, stream))
            }
            ExecutionOutcome::Failure(error) => Err(error),
        }
    }

    #[cfg(feature = "tasks")]
    pub fn wait_task_tool_call(
        &self,
        cx: &Cx,
        execution: &mut RequestExecution<T>,
    ) -> McpResult<fastmcp_protocol::CreateTaskResult> {
        self.require_modern_tasks_era()?;
        execution.ensure_task_operation(|operation| {
            matches!(operation, TaskExecutionOperation::ToolCall)
        })?;
        let core_request = self.decode_final_core_request_from_execution(execution)?;
        let (response, result_source) = self.wait_with_raw_result(cx, execution)?;
        let result_source = result_source.as_deref().ok_or_else(|| {
            McpError::invalid_request("Peer tools/call Task result lost its admitted result source")
        })?;
        match core_request.decode_response_result(&response, result_source) {
            Ok(CoreResult::Final(FinalCoreResult::ToolsCallTask { result })) => Ok(result),
            Ok(_) | Err(_) => Err(McpError::invalid_request(
                "Peer tools/call result is not a final Tasks creation result",
            )),
        }
    }

    #[cfg(feature = "tasks")]
    pub fn wait_tasks_get(
        &self,
        cx: &Cx,
        execution: &mut RequestExecution<T>,
    ) -> McpResult<GetTaskResult> {
        self.require_modern_tasks_era()?;
        let expected = execution.task_id_for(|operation| match operation {
            TaskExecutionOperation::Get(task_id) => Some(task_id),
            TaskExecutionOperation::ToolCall
            | TaskExecutionOperation::Update(_)
            | TaskExecutionOperation::Cancel(_)
            | TaskExecutionOperation::Subscription => None,
        })?;
        let response = self.wait(cx, execution)?;
        let result = decode_task_response::<GetTaskResult>(&response, "tasks/get")?;
        if result.task.base().task_id != expected {
            return Err(McpError::invalid_request(
                "tasks/get response taskId does not match its request",
            ));
        }
        Ok(result)
    }

    #[cfg(feature = "tasks")]
    pub fn wait_tasks_update(
        &self,
        cx: &Cx,
        execution: &mut RequestExecution<T>,
    ) -> McpResult<UpdateTaskResult> {
        self.require_modern_tasks_era()?;
        execution.ensure_task_operation(|operation| {
            matches!(operation, TaskExecutionOperation::Update(_))
        })?;
        let response = self.wait(cx, execution)?;
        decode_task_response(&response, "tasks/update")
    }

    #[cfg(feature = "tasks")]
    pub fn wait_tasks_cancel(
        &self,
        cx: &Cx,
        execution: &mut RequestExecution<T>,
    ) -> McpResult<CancelTaskResult> {
        self.require_modern_tasks_era()?;
        execution.ensure_task_operation(|operation| {
            matches!(operation, TaskExecutionOperation::Cancel(_))
        })?;
        let response = self.wait(cx, execution)?;
        decode_task_response(&response, "tasks/cancel")
    }

    #[cfg(feature = "tasks")]
    pub fn take_tasks_subscription_notifications(
        &self,
        execution: &RequestExecution<T>,
    ) -> McpResult<Vec<TaskStatusNotification>> {
        execution.ensure_task_operation(|operation| {
            matches!(operation, TaskExecutionOperation::Subscription)
        })?;
        let mut state = self.state.borrow_mut();
        let subscription = state
            .task_subscriptions
            .get_mut(&(execution.request_id.clone(), execution.generation))
            .ok_or_else(|| McpError::invalid_request("Tasks subscription is no longer active"))?;
        Ok(subscription.notifications.drain(..).collect())
    }

    /// Returns the exact filter acknowledged for one live Tasks subscription.
    ///
    /// The caller may poll this without reading transport ingress.  This keeps
    /// the acknowledgement observable before the terminal response while the
    /// connection-owned driver remains the sole reader.
    #[cfg(feature = "tasks")]
    pub fn tasks_subscription_acknowledgement(
        &self,
        execution: &RequestExecution<T>,
    ) -> McpResult<Option<SubscriptionFilter>> {
        execution.ensure_task_operation(|operation| {
            matches!(operation, TaskExecutionOperation::Subscription)
        })?;
        let state = self.state.borrow();
        let subscription = state
            .task_subscriptions
            .get(&(execution.request_id.clone(), execution.generation))
            .ok_or_else(|| McpError::invalid_request("Tasks subscription is no longer active"))?;
        Ok(subscription.accepted_filter.clone())
    }

    /// Takes a terminal Tasks subscription response after its ingress was
    /// already routed by the connection owner.
    ///
    /// This deliberately never reads the transport.  It is the incremental
    /// companion to [`Self::wait_tasks_subscription`] for stdio relays that
    /// must forward notifications as they arrive.
    #[cfg(feature = "tasks")]
    pub fn try_take_tasks_subscription_terminal(
        &self,
        execution: &mut RequestExecution<T>,
    ) -> McpResult<Option<SubscriptionFilter>> {
        self.require_modern_tasks_era()?;
        execution.ensure_task_operation(|operation| {
            matches!(operation, TaskExecutionOperation::Subscription)
        })?;
        let core_request = self.decode_final_core_request_from_execution(execution)?;
        let key = (execution.request_id.clone(), execution.generation);
        let Some(response) = self.try_take_response(execution)? else {
            return Ok(None);
        };
        let terminal = match core_request.decode_response(&response) {
            Ok(CoreResult::Final(FinalCoreResult::SubscriptionsListen { .. })) => Ok(()),
            Ok(_) | Err(_) => Err(McpError::invalid_request(
                "Tasks subscription terminal result is not a matching subscriptions/listen completion",
            )),
        };
        let subscription = self
            .state
            .borrow_mut()
            .task_subscriptions
            .remove(&key)
            .ok_or_else(|| McpError::invalid_request("Tasks subscription state is unavailable"))?;
        terminal?;
        subscription.accepted_filter.map(Some).ok_or_else(|| {
            McpError::invalid_request("Tasks subscription terminated before acknowledgement")
        })
    }

    #[cfg(feature = "tasks")]
    pub fn wait_tasks_subscription(
        &self,
        cx: &Cx,
        execution: &mut RequestExecution<T>,
    ) -> McpResult<(SubscriptionFilter, Vec<TaskStatusNotification>)> {
        self.require_modern_tasks_era()?;
        execution.ensure_task_operation(|operation| {
            matches!(operation, TaskExecutionOperation::Subscription)
        })?;
        let core_request = self.decode_final_core_request_from_execution(execution)?;
        let key = (execution.request_id.clone(), execution.generation);
        let response = match self.wait(cx, execution) {
            Ok(response) => response,
            Err(error) => {
                self.state.borrow_mut().task_subscriptions.remove(&key);
                return Err(error);
            }
        };
        let terminal = match core_request.decode_response(&response) {
            Ok(CoreResult::Final(FinalCoreResult::SubscriptionsListen { .. })) => Ok(()),
            Ok(_) | Err(_) => Err(McpError::invalid_request(
                "Tasks subscription terminal result is not a matching subscriptions/listen completion",
            )),
        };
        let subscription = self
            .state
            .borrow_mut()
            .task_subscriptions
            .remove(&key)
            .ok_or_else(|| McpError::invalid_request("Tasks subscription state is unavailable"))?;
        terminal?;
        let accepted_filter = subscription.accepted_filter.ok_or_else(|| {
            McpError::invalid_request("Tasks subscription terminated before acknowledgement")
        })?;
        Ok((
            accepted_filter,
            subscription.notifications.into_iter().collect(),
        ))
    }

    /// Returns whether a notification could belong to one active Tasks
    /// subscription.  The caller must still route the frame through
    /// [`Self::drive_frame`], which validates the exact subscription ID,
    /// acknowledgement order, and task filter.
    #[cfg(feature = "tasks")]
    pub fn owns_task_subscription_notification(&self, notification: &JsonRpcRequest) -> bool {
        notification.id.is_none()
            && matches!(
                notification.method.as_str(),
                "notifications/subscriptions/acknowledged" | TASK_STATUS_NOTIFICATION
            )
            && !self.state.borrow().task_subscriptions.is_empty()
    }

    /// Returns snapshots of every active request correlation.
    #[must_use]
    pub fn pending_records(&self) -> Vec<PendingRequestRecord> {
        self.state
            .borrow()
            .pending
            .values()
            .map(|pending| pending.record.clone())
            .collect()
    }

    /// Removes and returns retained peer notifications in arrival order.
    pub fn take_notifications(&self) -> Vec<JsonRpcRequest> {
        self.state.borrow_mut().notifications.drain(..).collect()
    }

    /// Removes and returns exact-legacy peer requests that require a client response.
    ///
    /// Each returned request retains its own response capability and
    /// cancellation handle. Pass the same value to
    /// [`Self::respond_to_reverse_request`] so an old callback cannot respond
    /// to a later peer request that reuses its JSON-RPC ID.
    pub fn take_reverse_requests(&self) -> Vec<ReverseRequest> {
        self.state.borrow_mut().reverse_requests.drain(..).collect()
    }

    /// Sends one final result for an exact-legacy peer-authored reverse request.
    pub fn respond_to_reverse_request(
        &self,
        cx: &Cx,
        request: &ReverseRequest,
        result: Value,
    ) -> McpResult<()> {
        let mut state = self.state.borrow_mut();
        if state.shutdown {
            return Err(McpError::internal_error(
                "Client request executor is shut down",
            ));
        }
        if state.terminal_error.is_some() {
            return Err(McpError::internal_error(
                "Client request executor connection is no longer usable",
            ));
        }
        let request_id = request.request_id();
        let key = request_id.correlation_key().map_err(|_| {
            McpError::invalid_request("Client reverse response has an invalid JSON-RPC request ID")
        })?;
        let Some(active) = state.pending_reverse_requests.get(&key) else {
            return Err(McpError::invalid_request(
                "Client reverse response does not own a live peer request ID",
            ));
        };
        if !Arc::ptr_eq(&active.owner, &request.owner)
            || !active
                .cancellation
                .belongs_to_same_request(&request.cancellation)
            || !active.request_id.correlates_with(request_id)
            || !request.cancellation.is_open()
        {
            return Err(McpError::invalid_request(
                "Client reverse response does not own a live peer request ID",
            ));
        }
        let owned_request_id = active.request_id.clone();
        state
            .transport
            .send(
                cx,
                &JsonRpcMessage::Response(JsonRpcResponse::success(
                    owned_request_id.clone(),
                    result,
                )),
            )
            .map_err(|error| self.handle_send_error_locked(&mut state, error))?;
        request.cancellation.record_response_sent();
        let removed = state.pending_reverse_requests.remove(&key);
        debug_assert!(removed.is_some());
        state
            .reverse_requests
            .retain(|request| !request.request_id().correlates_with(&owned_request_id));
        Ok(())
    }

    /// Removes and returns bounded, typed local cancellation indications.
    pub fn take_cancellation_events(&self) -> Vec<CancellationRequested> {
        self.state
            .borrow_mut()
            .cancellation_events
            .drain(..)
            .collect()
    }

    /// Returns terminal receipts retained for unconsumed request executions.
    #[must_use]
    pub fn terminal_records(&self) -> Vec<ExecutionTerminalRecord> {
        let mut state = self.state.borrow_mut();
        state.prune_retained_terminals(Instant::now());
        state.terminal_records.values().cloned().collect()
    }

    /// Selects explicit caller cancellation for one live execution.
    pub fn cancel(&self, cx: &Cx, execution: &mut RequestExecution<T>) -> McpResult<()> {
        execution.ensure_owner(&self.state)?;
        let mut state = self.state.borrow_mut();
        self.cancel_pending_locked(
            cx,
            &mut state,
            &execution.request_id,
            ExecutionTerminalReason::CallerCancelled,
        )
    }

    /// Accepts a peer subscription teardown for one request-owned execution.
    ///
    /// The peer's raw reason is intentionally not retained. Callers invoke
    /// this only after their subscription policy accepts the teardown frame.
    pub fn accept_subscription_teardown(
        &self,
        cx: &Cx,
        execution: &mut RequestExecution<T>,
    ) -> McpResult<()> {
        execution.ensure_owner(&self.state)?;
        let mut state = self.state.borrow_mut();
        let is_active_modern_subscription = state.result_peer_era == ResultPeerEra::Modern
            && state
                .pending
                .get(&execution.request_id.correlation_key().map_err(|_| {
                    McpError::invalid_params(
                        "Request execution owns an invalid JSON-RPC request ID",
                    )
                })?)
                .is_some_and(|pending| pending.method == SUBSCRIPTIONS_LISTEN);
        if !is_active_modern_subscription {
            return Err(McpError::invalid_request(
                "Peer cancellation is only valid for an active modern subscriptions/listen request",
            ));
        }
        self.cancel_pending_without_notification_locked(
            cx,
            &mut state,
            &execution.request_id,
            ExecutionTerminalReason::PeerSubscriptionTeardown,
        )
    }

    /// Expires committed request deadlines at a runtime-supplied monotonic instant.
    pub fn poll_timeouts_at(&self, cx: &Cx, observed_at: Instant) -> McpResult<()> {
        let mut state = self.state.borrow_mut();
        self.drain_abandoned_locked(cx, &mut state)?;
        self.expire_timeouts_locked(cx, &mut state, observed_at)
    }

    /// Returns the earliest live request deadline for an external ingress
    /// driver. It does not mutate correlation state or read the transport.
    pub(crate) fn next_pending_deadline(&self) -> Option<Instant> {
        self.state
            .borrow()
            .pending
            .values()
            .fold(None, |earliest, pending| {
                let deadline = pending
                    .record
                    .idle_deadline
                    .min(pending.record.absolute_deadline);
                Some(earliest.map_or(deadline, |earliest| earliest.min(deadline)))
            })
    }

    /// Releases every request owner after the connection's sole ingress driver
    /// has selected a terminal transport or protocol failure. The driver owns
    /// transport teardown; this only publishes the same terminal outcome to
    /// request-owned handles.
    pub(crate) fn fail_connection(&self, error: McpError) {
        self.state
            .borrow_mut()
            .fail_all(error, ExecutionTerminalReason::ConnectionLost);
    }

    /// Cancels live owners, releases their waiters, and closes the transport.
    pub fn shutdown(&self, cx: &Cx) -> McpResult<()> {
        let mut state = self.state.borrow_mut();
        if state.shutdown {
            return Ok(());
        }
        let mut cleanup_error = self
            .flush_deferred_drop_cancellations_locked(cx, &mut state)
            .err();
        state.shutdown = true;
        let request_ids = state
            .pending
            .values()
            .map(|pending| pending.record.request_id.clone())
            .collect::<Vec<_>>();
        for request_id in request_ids {
            if let Err(error) = self.cancel_pending_locked(
                cx,
                &mut state,
                &request_id,
                ExecutionTerminalReason::Shutdown,
            ) {
                cleanup_error.get_or_insert(error);
            }
        }
        state.cancel_reverse_requests();
        if let Err(error) = state.transport.close() {
            let error = transport_error_to_mcp(error);
            state.fail_all(error.clone(), ExecutionTerminalReason::ConnectionLost);
            cleanup_error.get_or_insert(error);
        }
        if let Some(error) = cleanup_error {
            return Err(error);
        }
        state.terminal_error.get_or_insert_with(|| {
            McpError::internal_error("Client request executor is shut down")
        });
        Ok(())
    }

    /// Removes and returns unmatched final responses in arrival order.
    ///
    /// Unknown, duplicate, and expired-owner response IDs are retained as
    /// bounded diagnostics instead of being guessed as another owner's result.
    pub fn take_uncorrelated_responses(&self) -> Vec<JsonRpcResponse> {
        self.state
            .borrow_mut()
            .uncorrelated_responses
            .drain(..)
            .collect()
    }

    fn handle_send_error_locked(
        &self,
        state: &mut ExecutorState<T>,
        transport_error: TransportError,
    ) -> McpError {
        if matches!(&transport_error, TransportError::Codec(_))
            || matches!(&transport_error, TransportError::Io(error) if error.kind() == std::io::ErrorKind::WouldBlock)
        {
            return transport_error_to_mcp(transport_error);
        }
        let error = transport_error_to_mcp(transport_error);
        state.fail_all(error.clone(), ExecutionTerminalReason::ConnectionLost);
        error
    }

    fn reject_reverse_request_locked(
        &self,
        cx: &Cx,
        state: &mut ExecutorState<T>,
        request: JsonRpcRequest,
    ) -> McpResult<()> {
        let error = McpError::method_not_found(&request.method);
        self.reject_reverse_request_with_error_locked(cx, state, request, error)
    }

    fn reject_reverse_request_with_error_locked(
        &self,
        cx: &Cx,
        state: &mut ExecutorState<T>,
        request: JsonRpcRequest,
        error: McpError,
    ) -> McpResult<()> {
        let request_id = request.id.expect("reverse request has an ID");
        let rejection =
            JsonRpcMessage::Response(JsonRpcResponse::error(Some(request_id), error.into()));
        state
            .transport
            .send(cx, &rejection)
            .map_err(|error| self.handle_send_error_locked(state, error))
    }

    fn wait_for_terminal(
        &self,
        cx: &Cx,
        execution: &mut RequestExecution<T>,
    ) -> McpResult<(ExecutionOutcome, Vec<JsonRpcRequest>)> {
        execution.ensure_owner(&self.state)?;
        loop {
            if let Some(outcome) = execution.take_terminal_outcome()? {
                return Ok(outcome);
            }
            if cx.checkpoint().is_err() {
                self.cancel(cx, execution)?;
                return Ok(execution
                    .take_terminal_outcome()?
                    .expect("caller cancellation selects a terminal execution outcome"));
            }
            self.drive(cx)?;
        }
    }

    fn route_response_with_raw_result_locked(
        &self,
        state: &mut ExecutorState<T>,
        response: JsonRpcResponse,
        raw_result: Option<String>,
    ) -> McpResult<()> {
        let Some(response_id) = response.id.clone() else {
            let error = McpError::invalid_request("Peer response omitted a request ID");
            state.fail_all(error, ExecutionTerminalReason::ConnectionLost);
            return Ok(());
        };
        let Ok(correlation_key) = response_id.correlation_key() else {
            let error = McpError::invalid_request("Peer response used an invalid request ID");
            state.fail_all(error, ExecutionTerminalReason::ConnectionLost);
            return Ok(());
        };
        let retain_late_response_diagnostic =
            state.tombstones.get(&correlation_key).map(|tombstone| {
                debug_assert!(tombstone.generation > 0);
                tombstone.retain_late_response_diagnostic
            });
        if let Some(retain_late_response_diagnostic) = retain_late_response_diagnostic {
            if retain_late_response_diagnostic && !state.retain_uncorrelated_response(response) {
                state.fail_all(
                    McpError::internal_error("Client uncorrelated-response queue is full"),
                    ExecutionTerminalReason::ConnectionLost,
                );
            }
            return Ok(());
        }
        let Some(pending) = state.pending.get(&correlation_key) else {
            if !state.retain_uncorrelated_response(response) {
                state.fail_all(
                    McpError::internal_error("Client uncorrelated-response queue is full"),
                    ExecutionTerminalReason::ConnectionLost,
                );
            }
            return Ok(());
        };
        let generation = pending.record.execution_generation;
        let expires_at = Instant::now()
            .checked_add(self.tombstone_retention)
            .ok_or_else(|| {
                McpError::internal_error("Tombstone retention exceeds the clock range")
            })?;
        let pending = state
            .pending
            .remove(&correlation_key)
            .expect("the exact pending owner remains live until its terminal transition");
        let owned_request_id = pending.record.request_id.clone();
        state.tombstones.insert(
            correlation_key,
            Tombstone {
                generation,
                expires_at,
                retain_late_response_diagnostic: true,
            },
        );
        let accepts_task_result =
            state.result_peer_era == ResultPeerEra::Modern && pending.method == TOOLS_CALL;
        let retain_subscription_listen = pending.method == SUBSCRIPTIONS_LISTEN;
        let decoded = match DecodedFinalResponse::admit(
            response,
            raw_result,
            state.result_peer_era,
            accepts_task_result,
            retain_subscription_listen,
        ) {
            Ok(decoded) => decoded,
            Err(error) => {
                state
                    .stream_notifications
                    .remove(&(owned_request_id.clone(), generation));
                state.retain_terminal(
                    (owned_request_id.clone(), generation),
                    ExecutionTerminalRecord {
                        terminal_state: ExecutionTerminalState::Failed,
                        terminal_reason: ExecutionTerminalReason::PeerProtocol,
                        final_delivered: false,
                        cancellation_committed: false,
                        cancellation_transport_attempts: 0,
                        local_cancellation_event: false,
                        waiter_release: true,
                        tombstone: true,
                    },
                    ExecutionOutcome::Failure(error),
                );
                return Ok(());
            }
        };
        state.retain_terminal(
            (owned_request_id.clone(), generation),
            ExecutionTerminalRecord {
                terminal_state: ExecutionTerminalState::Response,
                terminal_reason: ExecutionTerminalReason::FinalResponse,
                final_delivered: true,
                cancellation_committed: false,
                cancellation_transport_attempts: 0,
                local_cancellation_event: false,
                waiter_release: true,
                tombstone: true,
            },
            ExecutionOutcome::Response(Box::new(decoded)),
        );
        Ok(())
    }

    fn drain_abandoned_locked(&self, cx: &Cx, state: &mut ExecutorState<T>) -> McpResult<()> {
        let now = Instant::now();
        state.prune_tombstones(now);
        state.prune_retained_terminals(now);
        self.flush_deferred_drop_cancellations_locked(cx, state)?;
        let abandoned = state
            .pending
            .values()
            .filter(|pending| pending.owner_dropped.get())
            .map(|pending| {
                (
                    pending.record.request_id.clone(),
                    pending.record.execution_generation,
                )
            })
            .collect::<Vec<_>>();
        for (request_id, generation) in abandoned {
            let cancellation = self.cancel_pending_locked(
                cx,
                state,
                &request_id,
                ExecutionTerminalReason::CallerDropped,
            );
            // A dropped owner has no waiter that can consume the local
            // outcome, so retain only its correlation tombstone.
            state.release_terminal(&(request_id, generation));
            cancellation?;
        }
        Ok(())
    }

    fn flush_deferred_drop_cancellations_locked(
        &self,
        cx: &Cx,
        state: &mut ExecutorState<T>,
    ) -> McpResult<()> {
        while let Some(cancellation) = state.deferred_drop_cancellations.pop_front() {
            if let Some(record) = state
                .terminal_records
                .get_mut(&(cancellation.request_id.clone(), cancellation.generation))
            {
                record.cancellation_transport_attempts =
                    record.cancellation_transport_attempts.saturating_add(1);
            }
            if let Err(error) = state.transport.send(cx, &cancellation.message) {
                let error = transport_error_to_mcp(error);
                state.fail_all(error.clone(), ExecutionTerminalReason::ConnectionLost);
                return Err(error);
            }
        }
        Ok(())
    }

    fn cancel_pending_locked(
        &self,
        cx: &Cx,
        state: &mut ExecutorState<T>,
        request_id: &RequestId,
        reason: ExecutionTerminalReason,
    ) -> McpResult<()> {
        self.cancel_pending_with_notification_locked(cx, state, request_id, reason, true)
    }

    fn cancel_pending_without_notification_locked(
        &self,
        cx: &Cx,
        state: &mut ExecutorState<T>,
        request_id: &RequestId,
        reason: ExecutionTerminalReason,
    ) -> McpResult<()> {
        self.cancel_pending_with_notification_locked(cx, state, request_id, reason, false)
    }

    fn cancel_pending_with_notification_locked(
        &self,
        cx: &Cx,
        state: &mut ExecutorState<T>,
        request_id: &RequestId,
        reason: ExecutionTerminalReason,
        notify_peer: bool,
    ) -> McpResult<()> {
        let correlation_key = request_id.correlation_key().map_err(|_| {
            McpError::invalid_params("Request cancellation requires a valid JSON-RPC request ID")
        })?;
        let Some(pending) = state.pending.get(&correlation_key) else {
            return Ok(());
        };
        // MCP forbids client cancellation of initialize. A local owner still
        // transitions to cancellation, but no peer notification is emitted.
        let notify_peer = notify_peer && pending.method != INITIALIZE;
        // Assemble the selected-era notification before the terminal CAS so a
        // local encoding failure leaves the still-live owner unchanged.
        let cancellation = if notify_peer {
            Some(self.cancellation_control_message(state, request_id)?)
        } else {
            None
        };
        let Some(mut pending) = state.pending.remove(&correlation_key) else {
            return Ok(());
        };
        let owned_request_id = pending.record.request_id.clone();
        pending.record.cancellation_committed = true;
        pending.record.terminal_state = ExecutionTerminalState::Cancelled;
        let generation = pending.record.execution_generation;
        #[cfg(feature = "tasks")]
        state
            .task_subscriptions
            .remove(&(owned_request_id.clone(), generation));
        let expires_at = Instant::now()
            .checked_add(self.tombstone_retention)
            .ok_or_else(|| {
                McpError::internal_error("Tombstone retention exceeds the clock range")
            })?;
        state.tombstones.insert(
            correlation_key,
            Tombstone {
                generation,
                expires_at,
                retain_late_response_diagnostic: false,
            },
        );
        state
            .stream_notifications
            .remove(&(owned_request_id.clone(), generation));
        state.retain_terminal(
            (owned_request_id.clone(), generation),
            ExecutionTerminalRecord {
                terminal_state: ExecutionTerminalState::Cancelled,
                terminal_reason: reason,
                final_delivered: false,
                cancellation_committed: true,
                cancellation_transport_attempts: u8::from(notify_peer),
                local_cancellation_event: true,
                waiter_release: true,
                tombstone: true,
            },
            ExecutionOutcome::Failure(McpError::request_cancelled()),
        );
        if state.cancellation_events.len() >= MAX_RETAINED_PEER_ACTIVITY {
            // Cancellation is never held behind observer backpressure. The
            // bounded observer queue evicts its oldest already-observed event
            // so the current terminal transition retains its typed signal.
            let _ = state.cancellation_events.pop_front();
        }
        state.cancellation_events.push_back(CancellationRequested {
            request_id: owned_request_id,
            reason,
        });
        if !notify_peer {
            return Ok(());
        }
        let Some(cancellation) = cancellation else {
            return Ok(());
        };
        if let Err(error) = state.transport.send(cx, &cancellation) {
            let error = transport_error_to_mcp(error);
            state.fail_all(error.clone(), ExecutionTerminalReason::ConnectionLost);
            return Err(error);
        }
        Ok(())
    }

    fn route_cancellation_notification_locked(
        &self,
        cx: &Cx,
        state: &mut ExecutorState<T>,
        notification: &JsonRpcRequest,
    ) -> McpResult<bool> {
        if notification.method != "notifications/cancelled" {
            return Ok(false);
        }
        let era = match state.result_peer_era {
            ResultPeerEra::Legacy => ProtocolEra::Legacy2024,
            ResultPeerEra::Modern => ProtocolEra::Modern2026,
        };
        let Ok(cancellation) =
            CancellationWireMessage::decode(era, CancellationSender::Server, notification)
        else {
            return Ok(true);
        };
        match cancellation {
            CancellationWireMessage::Legacy2024 { params, .. } => {
                let key = params.request_id.correlation_key().ok();
                if let Some(active) = key
                    .as_ref()
                    .and_then(|key| state.pending_reverse_requests.remove(key))
                {
                    active.cancellation.cancel();
                    state
                        .reverse_requests
                        .retain(|request| !Arc::ptr_eq(&request.owner, &active.owner));
                }
            }
            CancellationWireMessage::Modern2026 { params, .. } => {
                if let Some(metadata_subscription_id) = params
                    .meta
                    .as_ref()
                    .and_then(|metadata| metadata.get(FINAL_SUBSCRIPTION_ID_META_KEY))
                    .and_then(|value| serde_json::from_value::<RequestId>(value.clone()).ok())
                    && !metadata_subscription_id.correlates_with(&params.request_id)
                {
                    return Ok(true);
                }
                let active_subscription_id = state.pending.values().find_map(|pending| {
                    (pending.method == SUBSCRIPTIONS_LISTEN
                        && pending
                            .record
                            .request_id
                            .correlates_with(&params.request_id))
                    .then(|| pending.record.request_id.clone())
                });
                if let Some(active_subscription_id) = active_subscription_id {
                    self.cancel_pending_without_notification_locked(
                        cx,
                        state,
                        &active_subscription_id,
                        ExecutionTerminalReason::PeerSubscriptionTeardown,
                    )?;
                }
            }
        }
        Ok(true)
    }

    fn cancellation_control_message(
        &self,
        state: &ExecutorState<T>,
        request_id: &RequestId,
    ) -> McpResult<JsonRpcMessage> {
        cancellation_control_message_for_era(state.result_peer_era, request_id)
    }

    #[cfg(feature = "tasks")]
    fn route_task_subscription_acknowledgement_locked(
        &self,
        state: &mut ExecutorState<T>,
        notification: &JsonRpcRequest,
    ) -> McpResult<bool> {
        if notification.id.is_some()
            || notification.method != "notifications/subscriptions/acknowledged"
            || state.task_subscriptions.is_empty()
        {
            return Ok(false);
        }
        let Some(params) = notification.params.clone() else {
            return Ok(false);
        };
        let acknowledgement: FinalSubscriptionsAcknowledgedNotificationParams =
            serde_json::from_value(params).map_err(|_| {
                McpError::invalid_request("Tasks subscription acknowledgement is invalid")
            })?;
        let Some(subscription_id) = acknowledgement
            .meta
            .as_ref()
            .and_then(|metadata| metadata.get(FINAL_SUBSCRIPTION_ID_META_KEY))
            .and_then(|value| serde_json::from_value::<RequestId>(value.clone()).ok())
        else {
            return Ok(false);
        };
        let Some((owned_subscription_id, generation)) = state
            .pending
            .values()
            .find(|pending| pending.record.request_id.correlates_with(&subscription_id))
            .map(|pending| {
                (
                    pending.record.request_id.clone(),
                    pending.record.execution_generation,
                )
            })
        else {
            return Ok(false);
        };
        let key = (owned_subscription_id, generation);
        let Some(subscription) = state.task_subscriptions.get(&key) else {
            return Ok(false);
        };
        if subscription.accepted_filter.is_some() {
            return Err(McpError::invalid_request(
                "Tasks subscription received a duplicate acknowledgement",
            ));
        }
        validate_task_subscription_filter(
            &subscription.requested_filter,
            &acknowledgement.notifications,
        )?;
        let subscription = state.task_subscriptions.get_mut(&key).ok_or_else(|| {
            McpError::internal_error("Tasks subscription disappeared during acknowledgement")
        })?;
        subscription.accepted_filter = Some(acknowledgement.notifications);
        Ok(true)
    }

    #[cfg(feature = "tasks")]
    fn route_task_subscription_notification_locked(
        &self,
        state: &mut ExecutorState<T>,
        notification: &JsonRpcRequest,
    ) -> McpResult<bool> {
        if notification.id.is_some()
            || notification.method != TASK_STATUS_NOTIFICATION
            || state.task_subscriptions.is_empty()
        {
            return Ok(false);
        }
        let Some(params) = notification.params.clone() else {
            return Ok(false);
        };
        let task_notification: TaskStatusNotification = serde_json::from_value(serde_json::json!({
            "jsonrpc": fastmcp_protocol::JSONRPC_VERSION,
            "method": TASK_STATUS_NOTIFICATION,
            "params": params,
        }))
        .map_err(|_| McpError::invalid_request("Tasks subscription event is invalid"))?;
        let Some(subscription_id) = task_notification
            .params
            .meta
            .as_ref()
            .and_then(|metadata| metadata.get(FINAL_SUBSCRIPTION_ID_META_KEY))
            .and_then(|value| serde_json::from_value::<RequestId>(value.clone()).ok())
        else {
            return Ok(false);
        };
        let Some((owned_subscription_id, generation)) = state
            .pending
            .values()
            .find(|pending| pending.record.request_id.correlates_with(&subscription_id))
            .map(|pending| {
                (
                    pending.record.request_id.clone(),
                    pending.record.execution_generation,
                )
            })
        else {
            return Ok(false);
        };
        let key = (owned_subscription_id, generation);
        let Some(subscription) = state.task_subscriptions.get(&key) else {
            return Ok(false);
        };
        let Some(accepted_filter) = subscription.accepted_filter.as_ref() else {
            return Err(McpError::invalid_request(
                "Tasks subscription event arrived before acknowledgement",
            ));
        };
        let accepted_task_ids = task_subscription_ids(accepted_filter).map_err(|_| {
            McpError::internal_error("Tasks subscription retained an invalid acknowledgement")
        })?;
        if !accepted_task_ids.as_ref().is_some_and(|task_ids| {
            task_ids
                .iter()
                .any(|task_id| task_id == &task_notification.params.task.base().task_id)
        }) {
            return Err(McpError::invalid_request(
                "Tasks subscription event taskId is outside the acknowledged filter",
            ));
        }
        if subscription.notifications.len() >= MAX_RETAINED_PEER_ACTIVITY {
            return Err(McpError::internal_error(
                "Tasks subscription event queue is full",
            ));
        }
        state
            .task_subscriptions
            .get_mut(&key)
            .ok_or_else(|| {
                McpError::internal_error("Tasks subscription disappeared during event routing")
            })?
            .notifications
            .push_back(task_notification);
        Ok(true)
    }

    #[cfg(feature = "tasks")]
    fn require_modern_tasks_era(&self) -> McpResult<()> {
        if self.state.borrow().result_peer_era != ResultPeerEra::Modern {
            return Err(McpError::invalid_request(
                "The final Tasks extension requires a modern peer era",
            ));
        }
        Ok(())
    }

    #[cfg(feature = "tasks")]
    fn decode_final_core_request(&self, request: &Request) -> McpResult<CoreRequest> {
        CoreRequest::decode(
            ProtocolEra::Modern2026,
            &request.method,
            request.params.as_ref(),
        )
        .map_err(|_| McpError::invalid_params("Invalid final core request for Tasks execution"))
    }

    #[cfg(feature = "tasks")]
    fn decode_final_core_request_from_execution(
        &self,
        execution: &RequestExecution<T>,
    ) -> McpResult<CoreRequest> {
        CoreRequest::decode(
            ProtocolEra::Modern2026,
            &execution.method,
            execution.params.as_ref(),
        )
        .map_err(|_| McpError::invalid_params("Invalid final core request for Tasks execution"))
    }

    #[cfg(feature = "tasks")]
    fn task_request_wire(&self, request: &Request) -> McpResult<Value> {
        let request_id = request.id.clone().ok_or_else(|| {
            McpError::invalid_params("Tasks execution requires a JSON-RPC request ID")
        })?;
        Ok(serde_json::json!({
            "jsonrpc": fastmcp_protocol::JSONRPC_VERSION,
            "id": request_id,
            "method": request.method,
            "params": request.params,
        }))
    }

    #[cfg(feature = "tasks")]
    fn decode_tasks_get_request(&self, request: &Request) -> McpResult<GetTaskParams> {
        TaskMethodRequest::<GetTaskParams>::decode(self.task_request_wire(request)?)
            .map(|request| request.params)
            .map_err(|_| McpError::invalid_params("Invalid final tasks/get request"))
    }

    #[cfg(feature = "tasks")]
    fn decode_tasks_update_request(
        &self,
        request: &Request,
        ledger: &TaskInputLedger,
    ) -> McpResult<UpdateTaskParams> {
        TaskMethodRequest::<UpdateTaskParams>::decode_update(
            self.task_request_wire(request)?,
            ledger,
        )
        .map(|request| request.params)
        .map_err(|_| McpError::invalid_params("Invalid final tasks/update request"))
    }

    #[cfg(feature = "tasks")]
    fn decode_tasks_cancel_request(&self, request: &Request) -> McpResult<CancelTaskParams> {
        TaskMethodRequest::<CancelTaskParams>::decode_cancel(self.task_request_wire(request)?)
            .map(|request| request.params)
            .map_err(|_| McpError::invalid_params("Invalid final tasks/cancel request"))
    }

    #[cfg(feature = "tasks")]
    fn decode_tasks_subscription_request(
        &self,
        request: &Request,
    ) -> McpResult<SubscriptionFilter> {
        if request.method != SUBSCRIPTIONS_LISTEN {
            return Err(McpError::invalid_params(
                "Tasks subscription execution requires subscriptions/listen",
            ));
        }
        self.decode_final_core_request(request)?;
        let params: FinalSubscriptionsListenParams = request
            .params
            .clone()
            .ok_or_else(|| McpError::invalid_params("Tasks subscription requires parameters"))
            .and_then(|params| {
                serde_json::from_value(params).map_err(|_| {
                    McpError::invalid_params("Tasks subscription parameters are invalid")
                })
            })?;
        if task_subscription_ids(&params.notifications)
            .map_err(|_| McpError::invalid_params("Tasks subscription filter is invalid"))?
            .is_none()
        {
            return Err(McpError::invalid_params(
                "Tasks subscription requires a taskIds filter",
            ));
        }
        Ok(params.notifications)
    }

    fn expire_timeouts_locked(
        &self,
        cx: &Cx,
        state: &mut ExecutorState<T>,
        observed_at: Instant,
    ) -> McpResult<()> {
        let expired = state
            .pending
            .values()
            .filter_map(|pending| {
                let reason = if observed_at >= pending.record.absolute_deadline {
                    Some(ExecutionTerminalReason::AbsoluteTimeout)
                } else if observed_at >= pending.record.idle_deadline {
                    Some(ExecutionTerminalReason::IdleTimeout)
                } else {
                    None
                }?;
                Some((pending.record.request_id.clone(), reason))
            })
            .collect::<Vec<_>>();
        for (request_id, reason) in expired {
            self.cancel_pending_locked(cx, state, &request_id, reason)?;
        }
        Ok(())
    }

    fn route_stream_notification_locked(
        &self,
        state: &mut ExecutorState<T>,
        notification: &JsonRpcRequest,
    ) -> McpResult<bool> {
        if notification.method != "notifications/progress" {
            return Ok(false);
        }
        let Some(params) = notification.params.as_ref().and_then(Value::as_object) else {
            return Ok(false);
        };
        let Some(marker) = progress_notification_marker(notification) else {
            return Ok(false);
        };
        let Some(progress) = params.get("progress").and_then(Value::as_f64) else {
            return Ok(false);
        };
        if !progress.is_finite() {
            return Ok(false);
        }
        let matching_keys = state
            .pending
            .iter()
            .filter_map(|(key, pending)| {
                (pending.advertised_progress_marker.as_ref() == Some(&marker))
                    .then_some(key.clone())
            })
            .collect::<Vec<_>>();
        let [correlation_key] = matching_keys.as_slice() else {
            return Ok(false);
        };
        let Some(pending) = state.pending.get_mut(correlation_key) else {
            return Ok(false);
        };
        if pending.last_progress.is_some_and(|prior| progress <= prior) {
            return Ok(false);
        }
        pending.last_progress = Some(progress);
        if pending.timeout_policy.resets_idle_on_matching_progress() {
            let reset_at = Instant::now();
            let next_idle = reset_at
                .checked_add(pending.timeout_policy.idle_timeout())
                .ok_or_else(|| {
                    McpError::internal_error("Client idle deadline exceeds the clock range")
                })?;
            pending.record.idle_deadline = next_idle.min(pending.record.absolute_deadline);
        }
        let generation = pending.record.execution_generation;
        let owned_request_id = pending.record.request_id.clone();
        let stream = state
            .stream_notifications
            .entry((owned_request_id, generation))
            .or_default();
        if stream.len() >= MAX_RETAINED_PEER_ACTIVITY {
            return Err(McpError::internal_error(
                "Client request stream queue is full",
            ));
        }
        stream.push_back(notification.clone());
        Ok(true)
    }
}

fn exact_result_source_from_admitted_frame(
    message: &JsonRpcMessage,
    source: &[u8],
) -> McpResult<Option<String>> {
    let JsonRpcMessage::Response(response) = message else {
        return Ok(None);
    };
    let admission = decode_strict_jsonrpc_response(source, source.len()).map_err(|_| {
        McpError::invalid_request("Admitted peer response could not retain its exact result source")
    })?;
    if admission.response() != response {
        return Err(McpError::invalid_request(
            "Admitted peer response differs from its exact source frame",
        ));
    }
    Ok(admission.into_parts().1)
}

/// Returns whether the selected protocol table admits an ID-bearing request
/// from the server at the client ingress boundary.
///
/// This is deliberately table-driven instead of treating every JSON-RPC
/// request as a callback. In particular, `completion/complete` is always
/// client-to-server, elicitation is absent from both selected core tables,
/// and the final table deliberately excludes historical reverse callbacks.
fn server_request_is_admitted(peer_era: ResultPeerEra, request: &JsonRpcRequest) -> bool {
    if request.id.is_none() {
        return false;
    }
    match peer_era {
        ResultPeerEra::Legacy => LEGACY_2024_11_05_METHODS.iter().any(|method| {
            method.name == request.method
                && method.envelope == Legacy2024EnvelopeKind::Request
                && matches!(
                    method.direction,
                    Legacy2024Direction::ServerToClient | Legacy2024Direction::Bidirectional
                )
        }),
        ResultPeerEra::Modern => FINAL_2026_07_28_METHODS.iter().any(|method| {
            method.name == request.method
                && method.envelope == Final2026EnvelopeKind::Request
                && method.direction.admits_sender(Final2026Peer::Server)
        }),
    }
}

/// Applies the pinned method-level schema after the selected-era table has
/// admitted a reverse request. Final-era request admission is unchanged: its
/// active table contains no server-to-client request methods.
fn legacy_reverse_request_params_are_admitted(
    peer_era: ResultPeerEra,
    request: &JsonRpcRequest,
) -> bool {
    match peer_era {
        ResultPeerEra::Legacy => {
            validate_legacy_2024_11_05_method_params(&request.method, request.params.as_ref())
                .is_ok()
        }
        ResultPeerEra::Modern => true,
    }
}

fn cancellation_control_message_for_era(
    peer_era: ResultPeerEra,
    request_id: &RequestId,
) -> McpResult<JsonRpcMessage> {
    let cancellation = match peer_era {
        ResultPeerEra::Legacy => CancellationWireMessage::Legacy2024 {
            sender: CancellationSender::Client,
            params: CancelledParams {
                request_id: request_id.clone(),
                reason: None,
            },
        },
        ResultPeerEra::Modern => CancellationWireMessage::Modern2026 {
            sender: CancellationSender::Client,
            params: FinalCancelledNotificationParams {
                request_id: request_id.clone(),
                reason: None,
                meta: None,
                additional: BTreeMap::new(),
            },
        },
    };
    cancellation
        .encode()
        .map(JsonRpcMessage::Request)
        .map_err(|error| {
            McpError::invalid_params(format!("Invalid cancellation control parameters: {error}"))
        })
}

#[cfg(feature = "tasks")]
fn decode_task_response<R>(response: &JsonRpcResponse, method: &'static str) -> McpResult<R>
where
    R: serde::de::DeserializeOwned,
{
    let result = response.result.clone().ok_or_else(|| {
        McpError::invalid_request(format!("Peer {method} response did not contain a result"))
    })?;
    serde_json::from_value(result)
        .map_err(|_| McpError::invalid_request(format!("Peer {method} result is invalid")))
}

#[cfg(feature = "tasks")]
fn validate_task_subscription_filter(
    requested_filter: &SubscriptionFilter,
    accepted_filter: &SubscriptionFilter,
) -> McpResult<()> {
    let requested_task_ids = task_subscription_ids(requested_filter)
        .map_err(|_| McpError::internal_error("Tasks subscription request filter is invalid"))?
        .ok_or_else(|| McpError::internal_error("Tasks subscription omitted its taskIds filter"))?;
    let accepted_task_ids = task_subscription_ids(accepted_filter).map_err(|_| {
        McpError::invalid_request("Tasks subscription acknowledgement filter is invalid")
    })?;
    if let Some(accepted_task_ids) = accepted_task_ids {
        for (index, task_id) in accepted_task_ids.iter().enumerate() {
            if !requested_task_ids
                .iter()
                .any(|requested| requested == task_id)
                || accepted_task_ids[..index]
                    .iter()
                    .any(|previous| previous == task_id)
            {
                return Err(McpError::invalid_request(
                    "Tasks subscription acknowledgement contains an unrequested taskId",
                ));
            }
        }
    }
    Ok(())
}

/// One request-owned response stream handle.
///
/// Dropping a live handle promptly selects its local terminal transition and
/// queues its one bounded cancellation notification. The next executor
/// operation owns the transport send, so `Drop` never performs I/O while it
/// holds the shared executor state.
#[derive(Debug)]
pub struct RequestExecution<T> {
    request_id: RequestId,
    generation: u64,
    owner_dropped: OwnerDropped,
    state: SharedExecutorState<T>,
    method: String,
    params: Option<Value>,
    #[cfg(feature = "tasks")]
    task_operation: Option<TaskExecutionOperation>,
    tombstone_retention: Duration,
    completed: bool,
}

impl<T> RequestExecution<T> {
    /// Returns the exact request ID committed for this execution.
    #[must_use]
    pub fn request_id(&self) -> &RequestId {
        &self.request_id
    }

    /// Returns this request ID's monotonic local execution generation.
    #[must_use]
    pub const fn generation(&self) -> u64 {
        self.generation
    }

    /// Removes request-owned streaming notifications in peer arrival order.
    ///
    /// Only structurally valid progress with this execution's exact token can
    /// enter this queue; generic notifications remain executor-level activity.
    pub fn take_stream_notifications(&mut self) -> McpResult<Vec<JsonRpcRequest>> {
        if self.completed {
            return Err(McpError::invalid_request(
                "Request execution result was already consumed",
            ));
        }
        Ok(self
            .state
            .borrow_mut()
            .stream_notifications
            .remove(&(self.request_id.clone(), self.generation))
            .map_or_else(Vec::new, |events| events.into_iter().collect()))
    }

    fn ensure_owner(&self, state: &SharedExecutorState<T>) -> McpResult<()> {
        if !SharedExecutorState::ptr_eq(&self.state, state) {
            return Err(McpError::invalid_params(
                "Request execution belongs to a different executor",
            ));
        }
        if self.completed {
            return Err(McpError::invalid_request(
                "Request execution result was already consumed",
            ));
        }
        Ok(())
    }

    #[cfg(feature = "tasks")]
    fn ensure_task_operation(
        &self,
        accepts: impl FnOnce(&TaskExecutionOperation) -> bool,
    ) -> McpResult<()> {
        self.ensure_owner(&self.state)?;
        if self
            .task_operation
            .as_ref()
            .is_none_or(|operation| !accepts(operation))
        {
            return Err(McpError::invalid_params(
                "Request execution does not own the required Tasks operation",
            ));
        }
        Ok(())
    }

    #[cfg(feature = "tasks")]
    fn task_id_for(
        &self,
        select: impl FnOnce(&TaskExecutionOperation) -> Option<&TaskId>,
    ) -> McpResult<TaskId> {
        self.ensure_owner(&self.state)?;
        self.task_operation
            .as_ref()
            .and_then(select)
            .cloned()
            .ok_or_else(|| {
                McpError::invalid_params(
                    "Request execution does not own the required Tasks operation",
                )
            })
    }

    fn take_terminal_outcome(
        &mut self,
    ) -> McpResult<Option<(ExecutionOutcome, Vec<JsonRpcRequest>)>> {
        if self.completed {
            return Err(McpError::invalid_request(
                "Request execution result was already consumed",
            ));
        }
        let mut state = self.state.borrow_mut();
        let now = Instant::now();
        state.prune_retained_terminals(now);
        let key = (self.request_id.clone(), self.generation);
        let outcome = state.completed.remove(&key);
        let Some(outcome) = outcome else {
            let correlation_key = self.request_id.correlation_key().map_err(|_| {
                McpError::invalid_params("Request execution owns an invalid JSON-RPC request ID")
            })?;
            if state
                .pending
                .get(&correlation_key)
                .is_some_and(|pending| pending.record.execution_generation == self.generation)
            {
                return Ok(None);
            }
            return Err(McpError::internal_error(
                "Request execution terminal result expired before it was consumed",
            ));
        };
        state.terminal_records.remove(&key);
        state.terminal_expirations.remove(&key);
        let stream = state
            .stream_notifications
            .remove(&key)
            .map_or_else(Vec::new, |events| events.into_iter().collect());
        self.completed = true;
        Ok(Some((outcome, stream)))
    }
}

impl<T> Drop for RequestExecution<T> {
    fn drop(&mut self) {
        let key = (self.request_id.clone(), self.generation);
        if self.completed {
            if let Ok(mut state) = self.state.try_borrow_mut() {
                state.release_terminal(&key);
                #[cfg(feature = "tasks")]
                state.task_subscriptions.remove(&key);
            }
            return;
        }

        self.owner_dropped.set(true);
        let Ok(mut state) = self.state.try_borrow_mut() else {
            return;
        };
        let Ok(correlation_key) = self.request_id.correlation_key() else {
            return;
        };
        let Some(pending) = state.pending.get(&correlation_key) else {
            state.release_terminal(&key);
            #[cfg(feature = "tasks")]
            state.task_subscriptions.remove(&key);
            state.stream_notifications.remove(&key);
            return;
        };
        if pending.record.execution_generation != self.generation {
            state.release_terminal(&key);
            #[cfg(feature = "tasks")]
            state.task_subscriptions.remove(&key);
            state.stream_notifications.remove(&key);
            return;
        }
        let Some(pending) = state.pending.remove(&correlation_key) else {
            return;
        };
        #[cfg(feature = "tasks")]
        state
            .task_subscriptions
            .remove(&(self.request_id.clone(), self.generation));
        state
            .stream_notifications
            .remove(&(self.request_id.clone(), self.generation));
        let now = Instant::now();
        let expires_at = now.checked_add(self.tombstone_retention).unwrap_or(now);
        state.tombstones.insert(
            correlation_key,
            Tombstone {
                generation: self.generation,
                expires_at,
                retain_late_response_diagnostic: false,
            },
        );
        let cancellation = (pending.method != INITIALIZE)
            .then(|| cancellation_control_message_for_era(state.result_peer_era, &self.request_id))
            .transpose()
            .ok()
            .flatten();
        state.retain_terminal(
            key.clone(),
            ExecutionTerminalRecord {
                terminal_state: ExecutionTerminalState::Cancelled,
                terminal_reason: ExecutionTerminalReason::CallerDropped,
                final_delivered: false,
                cancellation_committed: true,
                cancellation_transport_attempts: 0,
                local_cancellation_event: true,
                waiter_release: true,
                tombstone: true,
            },
            ExecutionOutcome::Failure(McpError::request_cancelled()),
        );
        if state.cancellation_events.len() >= MAX_RETAINED_PEER_ACTIVITY {
            let _ = state.cancellation_events.pop_front();
        }
        state.cancellation_events.push_back(CancellationRequested {
            request_id: self.request_id.clone(),
            reason: ExecutionTerminalReason::CallerDropped,
        });
        if let Some(message) = cancellation {
            state
                .deferred_drop_cancellations
                .push_back(DeferredDropCancellation {
                    request_id: self.request_id.clone(),
                    generation: self.generation,
                    message,
                });
        }
        state.release_terminal(&key);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use fastmcp_protocol::ExactJsonValue;
    use fastmcp_transport::CodecError;

    #[derive(Debug)]
    struct ScriptedTransport {
        received: VecDeque<Result<JsonRpcMessage, TransportError>>,
        received_frames: VecDeque<Result<ReceivedTransportFrame, TransportError>>,
        sent: Vec<JsonRpcMessage>,
        send_error: Option<std::io::ErrorKind>,
    }

    impl ScriptedTransport {
        fn new(received: impl IntoIterator<Item = Result<JsonRpcMessage, TransportError>>) -> Self {
            Self {
                received: received.into_iter().collect(),
                received_frames: VecDeque::new(),
                sent: Vec::new(),
                send_error: None,
            }
        }

        fn with_source_frames(
            received_frames: impl IntoIterator<Item = Result<ReceivedTransportFrame, TransportError>>,
        ) -> Self {
            Self {
                received: VecDeque::new(),
                received_frames: received_frames.into_iter().collect(),
                sent: Vec::new(),
                send_error: None,
            }
        }
    }

    impl Transport for ScriptedTransport {
        fn send(&mut self, _cx: &Cx, message: &JsonRpcMessage) -> Result<(), TransportError> {
            if let Some(kind) = self.send_error {
                return Err(TransportError::Io(std::io::Error::from(kind)));
            }
            self.sent.push(message.clone());
            Ok(())
        }

        fn recv(&mut self, _cx: &Cx) -> Result<JsonRpcMessage, TransportError> {
            self.received
                .pop_front()
                .unwrap_or(Err(TransportError::Closed))
        }

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

    fn receive_scripted_source_frame(
        transport: &mut ScriptedTransport,
        _cx: &Cx,
    ) -> Result<ReceivedTransportFrame, TransportError> {
        transport
            .received_frames
            .pop_front()
            .unwrap_or(Err(TransportError::Closed))
    }

    fn request(id: i64) -> JsonRpcRequest {
        JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({
                "id": id,
                "_meta": {"progressToken": id},
            })),
            id,
        )
    }

    fn response(id: i64, result: serde_json::Value) -> JsonRpcMessage {
        JsonRpcMessage::Response(JsonRpcResponse::success(RequestId::Number(id), result))
    }

    fn legacy_reverse_request(id: i64) -> JsonRpcMessage {
        JsonRpcMessage::Request(JsonRpcRequest::new(
            "sampling/createMessage",
            Some(serde_json::json!({"messages": [], "maxTokens": 9})),
            id,
        ))
    }

    #[cfg(feature = "tasks")]
    fn tasks_subscription_request(id: i64, task_id: &TaskId) -> JsonRpcRequest {
        let mut notifications = SubscriptionFilter::default();
        fastmcp_protocol::set_task_subscription_ids(&mut notifications, vec![task_id.clone()])
            .expect("compose a bounded Tasks subscription filter");
        JsonRpcRequest::new(
            SUBSCRIPTIONS_LISTEN,
            Some(serde_json::json!({
                "_meta": fastmcp_protocol::FinalRequestMeta::new(fastmcp_protocol::ClientCapabilities::default()),
                "notifications": notifications,
            })),
            id,
        )
    }

    #[cfg(feature = "tasks")]
    fn task_tool_call_request(id: i64) -> JsonRpcRequest {
        JsonRpcRequest::new(
            TOOLS_CALL,
            Some(serde_json::json!({
                "name": "long-running-tool",
                "arguments": {},
                "_meta": fastmcp_protocol::FinalRequestMeta::new(fastmcp_protocol::ClientCapabilities::default()),
            })),
            id,
        )
    }

    #[cfg(feature = "tasks")]
    fn tasks_subscription_acknowledgement(id: i64, task_id: &TaskId) -> JsonRpcMessage {
        JsonRpcMessage::Request(JsonRpcRequest::notification(
            "notifications/subscriptions/acknowledged",
            Some(serde_json::json!({
                "_meta": {"io.modelcontextprotocol/subscriptionId": id},
                "notifications": {"taskIds": [task_id]},
            })),
        ))
    }

    #[cfg(feature = "tasks")]
    fn tasks_status_notification(id: i64, task_id: &TaskId) -> JsonRpcMessage {
        JsonRpcMessage::Request(JsonRpcRequest::notification(
            TASK_STATUS_NOTIFICATION,
            Some(serde_json::json!({
                "_meta": {"io.modelcontextprotocol/subscriptionId": id},
                "taskId": task_id,
                "status": "working",
                "createdAt": "2026-07-28T12:00:00.000Z",
                "lastUpdatedAt": "2026-07-28T12:00:00.000Z",
                "ttlMs": null,
            })),
        ))
    }

    #[test]
    fn unit_clt_01_a_positive() {
        assert_eq!(
            clt_01_a_manifest_digest().as_bytes(),
            &[
                0x52, 0x7c, 0x4b, 0xdb, 0x5b, 0xdd, 0xff, 0x10, 0x95, 0xb3, 0x27, 0xf7, 0x92, 0x5b,
                0xcf, 0x73, 0xba, 0x6e, 0xd0, 0x05, 0x22, 0x5b, 0x8b, 0x59, 0x91, 0x6b, 0x0b, 0x7e,
                0xe3, 0x88, 0x62, 0xb7,
            ],
        );
        let executor = RequestExecutor::new(ScriptedTransport::new([
            Ok(response(999, serde_json::json!({"unknown": true}))),
            Ok(response(
                2,
                serde_json::json!({"kind": "input-required", "x": [1, 2]}),
            )),
            Ok(JsonRpcMessage::Request(JsonRpcRequest::notification(
                "notifications/message",
                Some(serde_json::json!({"level": "info"})),
            ))),
            Ok(response(
                1,
                serde_json::json!({"kind": "complete", "extra": {"n": 9007199254740993u64}}),
            )),
        ]));
        let cx = Cx::for_testing();
        let mut first = executor
            .execute(&cx, request(1))
            .expect("first request commits");
        let mut second = executor
            .execute(&cx, request(2))
            .expect("second request commits");

        let records = executor.pending_records();
        assert_eq!(records.len(), 2);
        assert!(records.iter().all(|record| {
            record.correlation_key
                == record
                    .request_id
                    .correlation_key()
                    .expect("committed request IDs remain canonicalizable")
                && record.send_committed
                && record.request_state == ExecutionTerminalState::Pending
                && record.terminal_state == ExecutionTerminalState::Pending
                && !record.cancellation_committed
                && record.tombstone_generation.is_none()
                && record.idle_deadline <= record.absolute_deadline
        }));

        let first_response = executor
            .wait(&cx, &mut first)
            .expect("reordered first response");
        assert_eq!(first_response.id, Some(RequestId::Number(1)));
        assert_eq!(
            first_response.result,
            Some(serde_json::json!({"kind": "complete", "extra": {"n": 9007199254740993u64}}))
        );
        let second_response = executor
            .wait(&cx, &mut second)
            .expect("stored second response");
        assert_eq!(second_response.id, Some(RequestId::Number(2)));
        assert_eq!(
            second_response.result,
            Some(serde_json::json!({"kind": "input-required", "x": [1, 2]}))
        );
        let notifications = executor.take_notifications();
        assert_eq!(notifications.len(), 1);
        assert!(executor.pending_records().is_empty());
        let uncorrelated = executor.take_uncorrelated_responses();
        assert_eq!(uncorrelated.len(), 1);
        assert_eq!(uncorrelated[0].id, Some(RequestId::Number(999)));

        let malformed = RequestExecutor::new(ScriptedTransport::new([Err(TransportError::Codec(
            CodecError::Json(
                serde_json::from_str::<serde_json::Value>("{").expect_err("invalid JSON"),
            ),
        ))]));
        let mut malformed_first = malformed
            .execute(&cx, request(11))
            .expect("first malformed-owner request commits");
        let mut malformed_second = malformed
            .execute(&cx, request(12))
            .expect("second malformed-owner request commits");
        let error = malformed
            .drive(&cx)
            .expect_err("malformed peer ingress fails locally without a peer response");
        assert_eq!(error.code, fastmcp_core::McpErrorCode::InternalError);
        assert_eq!(
            malformed
                .wait(&cx, &mut malformed_first)
                .expect_err("first owner receives the fanout failure")
                .code,
            fastmcp_core::McpErrorCode::InternalError,
        );
        assert_eq!(
            malformed
                .wait(&cx, &mut malformed_second)
                .expect_err("second owner receives the same fanout failure")
                .code,
            fastmcp_core::McpErrorCode::InternalError,
        );
        assert_eq!(malformed.state.borrow().transport.sent.len(), 2);

        let closed = RequestExecutor::new(ScriptedTransport::new([Err(TransportError::Closed)]));
        let mut closed_first = closed
            .execute(&cx, request(13))
            .expect("first connection-loss owner request commits");
        let mut closed_second = closed
            .execute(&cx, request(14))
            .expect("second connection-loss owner request commits");
        assert!(closed.drive(&cx).is_err());
        assert_eq!(
            closed
                .wait(&cx, &mut closed_first)
                .expect_err("first owner receives connection loss")
                .code,
            fastmcp_core::McpErrorCode::InternalError,
        );
        assert_eq!(
            closed
                .wait(&cx, &mut closed_second)
                .expect_err("second owner receives connection loss")
                .code,
            fastmcp_core::McpErrorCode::InternalError,
        );

        let abandoned = RequestExecutor::new(ScriptedTransport::new([
            Ok(response(31, serde_json::json!({"late": true}))),
            Ok(response(32, serde_json::json!({"current": true}))),
        ]));
        let dropped = abandoned
            .execute(&cx, request(31))
            .expect("abandoned request commits");
        drop(dropped);
        let mut current = abandoned
            .execute(&cx, request(32))
            .expect("next request drains the cancelled owner first");
        let current_response = abandoned
            .wait(&cx, &mut current)
            .expect("late tombstone response cannot poison the next generation");
        assert_eq!(current_response.id, Some(RequestId::Number(32)));
        assert_eq!(abandoned.state.borrow().transport.sent.len(), 3);

        let backpressured = RequestExecutor::new(ScriptedTransport {
            received: VecDeque::new(),
            received_frames: VecDeque::new(),
            sent: Vec::new(),
            send_error: Some(std::io::ErrorKind::WouldBlock),
        });
        assert!(backpressured.execute(&cx, request(21)).is_err());
        assert!(backpressured.pending_records().is_empty());
        assert!(backpressured.execute(&cx, request(22)).is_err());
    }

    #[test]
    fn modern_reverse_request_is_rejected_without_mutating_legacy_handler_state() {
        let cx = Cx::for_testing();
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new([Ok(legacy_reverse_request(700))]),
            ResultPeerEra::Modern,
        );
        let _execution = executor
            .execute(&cx, request(42))
            .expect("outer request commits before modern peer ingress");
        let pending_before = executor.pending_records();

        executor
            .drive(&cx)
            .expect("modern legacy-shaped reverse request is rejected locally");

        assert!(executor.take_reverse_requests().is_empty());
        assert_eq!(executor.pending_records(), pending_before);
        let state = executor.state.borrow();
        assert!(state.pending_reverse_requests.is_empty());
        assert_eq!(state.reverse_requests.len(), 0);
        assert_eq!(state.transport.sent.len(), 2);
        let JsonRpcMessage::Response(rejection) = &state.transport.sent[1] else {
            panic!("modern reverse request receives one JSON-RPC error response");
        };
        assert_eq!(rejection.id, Some(RequestId::Number(700)));
        let error = rejection
            .error
            .as_ref()
            .expect("rejection carries an error");
        assert_eq!(
            error.code.as_i32(),
            Some(i32::from(McpErrorCode::MethodNotFound))
        );
        assert_eq!(error.message, "Method not found");
    }

    #[test]
    fn legacy_reverse_request_remains_available_to_the_handler_boundary() {
        let cx = Cx::for_testing();
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new([Ok(legacy_reverse_request(700))]),
            ResultPeerEra::Legacy,
        );
        let _execution = executor
            .execute(&cx, request(42))
            .expect("outer request commits before legacy peer ingress");
        let pending_before = executor.pending_records();

        executor
            .drive(&cx)
            .expect("legacy reverse request reaches the handler boundary");

        let reverse_requests = executor.take_reverse_requests();
        assert_eq!(reverse_requests.len(), 1);
        assert_eq!(reverse_requests[0].request_id(), &RequestId::Number(700));
        assert_eq!(
            reverse_requests[0].request().method,
            "sampling/createMessage"
        );
        assert_eq!(executor.pending_records(), pending_before);
        executor
            .respond_to_reverse_request(&cx, &reverse_requests[0], serde_json::json!({"ok": true}))
            .expect("legacy handler result is sent for its exact request ID");

        let state = executor.state.borrow();
        assert!(state.pending_reverse_requests.is_empty());
        assert!(state.reverse_requests.is_empty());
        assert_eq!(state.transport.sent.len(), 2);
        let JsonRpcMessage::Response(response) = &state.transport.sent[1] else {
            panic!("legacy handler result is a JSON-RPC response");
        };
        assert_eq!(response.id, Some(RequestId::Number(700)));
        assert_eq!(response.result, Some(serde_json::json!({"ok": true})));
    }

    #[test]
    fn unit_clt_01_a_planted_negative() {
        let executor = RequestExecutor::new(ScriptedTransport::new(std::iter::empty()));
        let cx = Cx::for_testing();
        let _first = executor
            .execute(&cx, request(7))
            .expect("baseline request commits");
        let before = executor.pending_records();
        let error = executor
            .execute(&cx, request(7))
            .expect_err("changing only the correlation ID to a duplicate must fail");
        assert_eq!(error.code, fastmcp_core::McpErrorCode::InvalidRequest);
        assert_eq!(executor.pending_records(), before);
        assert_eq!(executor.state.borrow().transport.sent.len(), 1);
        assert!(executor.take_notifications().is_empty());
        assert!(executor.take_uncorrelated_responses().is_empty());
    }

    #[test]
    fn unit_clt_01_b_positive() {
        assert_eq!(
            clt_01_b_manifest_digest().as_bytes(),
            &[
                0x8f, 0xae, 0x58, 0xf3, 0x7a, 0xe8, 0x54, 0xb1, 0x89, 0xc7, 0x42, 0x9a, 0x75, 0xd8,
                0xf7, 0x4b, 0x4b, 0x88, 0xda, 0x1e, 0x1d, 0xd7, 0xd5, 0x9a, 0x8d, 0x88, 0x0e, 0xd1,
                0x97, 0xa5, 0x78, 0xc6,
            ],
        );
        let cx = Cx::for_testing();
        let executor = RequestExecutor::new(ScriptedTransport::new([
            Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                "sampling/createMessage",
                Some(serde_json::json!({"messages": [], "maxTokens": 9})),
                700,
            ))),
            Ok(JsonRpcMessage::Request(JsonRpcRequest::notification(
                "notifications/progress",
                Some(serde_json::json!({"progressToken": 42, "progress": 0.5})),
            ))),
            Ok(response(42, serde_json::json!({"kind": "complete"}))),
        ]));
        let mut execution = executor
            .execute(&cx, request(42))
            .expect("public executor commits the request");

        executor.drive(&cx).expect("reverse request is retained");
        let reverse = executor.take_reverse_requests();
        assert_eq!(reverse.len(), 1);
        assert_eq!(reverse[0].request_id(), &RequestId::Number(700));
        executor
            .respond_to_reverse_request(&cx, &reverse[0], serde_json::json!({"ok": true}))
            .expect("reverse request receives a JSON-RPC result");

        let idle_before_progress = executor.pending_records()[0].idle_deadline;
        executor
            .drive(&cx)
            .expect("exact valid progress enters the request-owned stream");
        let stream = execution
            .take_stream_notifications()
            .expect("live execution owns its stream");
        assert_eq!(stream.len(), 1);
        assert_eq!(stream[0].method, "notifications/progress");
        assert!(executor.pending_records()[0].idle_deadline >= idle_before_progress);
        let final_response = executor
            .wait(&cx, &mut execution)
            .expect("stream notification precedes exact final response");
        assert_eq!(final_response.id, Some(RequestId::Number(42)));

        let explicit = RequestExecutor::new(ScriptedTransport::new(std::iter::empty()));
        let mut explicitly_cancelled = explicit
            .execute(&cx, request(43))
            .expect("explicit-cancellation request commits");
        let caller_cancelled = Cx::for_testing();
        caller_cancelled.set_cancel_requested(true);
        assert_eq!(
            explicit
                .wait(&caller_cancelled, &mut explicitly_cancelled)
                .expect_err("caller cancellation selects and releases its exact waiter")
                .code,
            fastmcp_core::McpErrorCode::RequestCancelled,
        );
        assert!(explicit.terminal_records().is_empty());
        assert_eq!(
            explicit.take_cancellation_events(),
            vec![CancellationRequested {
                request_id: RequestId::Number(43),
                reason: ExecutionTerminalReason::CallerCancelled,
            }],
        );

        let timed = RequestExecutor::new(ScriptedTransport::new(std::iter::empty()));
        let short = RequestTimeoutPolicy::new(Duration::from_millis(1), Duration::from_millis(2))
            .expect("bounded timeout policy");
        let mut idle_execution = timed
            .execute_with_timeout_policy(&cx, request(44), short)
            .expect("idle timeout request commits");
        let idle_deadline = timed.pending_records()[0].idle_deadline;
        timed
            .poll_timeouts_at(&cx, idle_deadline)
            .expect("idle deadline selects cancellation");
        assert!(timed.wait(&cx, &mut idle_execution).is_err());
        assert_eq!(
            timed.take_cancellation_events()[0].reason,
            ExecutionTerminalReason::IdleTimeout,
        );

        let absolute = RequestExecutor::new(ScriptedTransport::new(std::iter::empty()));
        let flood_policy =
            RequestTimeoutPolicy::new(Duration::from_secs(1), Duration::from_millis(2))
                .expect("bounded absolute timeout policy");
        let mut absolute_execution = absolute
            .execute_with_timeout_policy(&cx, request(45), flood_policy)
            .expect("absolute timeout request commits");
        let absolute_deadline = absolute.pending_records()[0].absolute_deadline;
        absolute
            .poll_timeouts_at(&cx, absolute_deadline)
            .expect("absolute deadline cannot be reset by peer activity");
        assert!(absolute.wait(&cx, &mut absolute_execution).is_err());
        assert_eq!(
            absolute.take_cancellation_events()[0].reason,
            ExecutionTerminalReason::AbsoluteTimeout,
        );

        let subscription = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new(std::iter::empty()),
            ResultPeerEra::Modern,
        );
        let mut subscribed = subscription
            .execute(
                &cx,
                JsonRpcRequest::new(SUBSCRIPTIONS_LISTEN, Some(serde_json::json!({})), 46),
            )
            .expect("subscription-owned request commits");
        subscription
            .accept_subscription_teardown(&cx, &mut subscribed)
            .expect("accepted teardown selects local cancellation");
        assert!(subscription.wait(&cx, &mut subscribed).is_err());
        assert_eq!(
            subscription.take_cancellation_events()[0].reason,
            ExecutionTerminalReason::PeerSubscriptionTeardown,
        );

        let mut pagination = OpaquePagination::new(PaginationBounds::default(), Instant::now());
        assert!(
            pagination
                .accept_page(Some(String::new()), 0, 0, Instant::now())
                .expect("empty opaque cursor remains present")
        );
        assert_eq!(pagination.next_cursor(), Some(""));
        assert!(
            pagination
                .accept_page(Some(String::new()), 0, 0, Instant::now())
                .expect("repeated opaque cursor remains present")
        );
        assert!(
            !pagination
                .accept_page(None, 0, 0, Instant::now())
                .expect("only cursor absence completes pagination")
        );

        let shutdown = RequestExecutor::new(ScriptedTransport::new(std::iter::empty()));
        let mut closing = shutdown
            .execute(&cx, request(47))
            .expect("shutdown-owned request commits");
        shutdown
            .shutdown(&cx)
            .expect("bounded shutdown closes transport");
        assert!(shutdown.wait(&cx, &mut closing).is_err());
        assert!(shutdown.terminal_records().is_empty());
    }

    #[test]
    fn unit_clt_01_b_planted_negative() {
        let cx = Cx::for_testing();
        let executor = RequestExecutor::new(ScriptedTransport::new([Ok(JsonRpcMessage::Request(
            JsonRpcRequest::notification(
                "notifications/progress",
                Some(serde_json::json!({"progressToken": 101, "progress": 0.5})),
            ),
        ))]));
        let mut execution = executor
            .execute(&cx, request(100))
            .expect("baseline request commits");
        let before = executor.pending_records();
        executor
            .drive(&cx)
            .expect("changing only the progress token leaves the owner untouched");
        assert_eq!(executor.pending_records(), before);
        assert!(
            execution
                .take_stream_notifications()
                .expect("unrelated progress has no stream owner")
                .is_empty()
        );
        assert_eq!(executor.take_notifications().len(), 1);
        assert!(executor.terminal_records().is_empty());
        assert!(executor.take_cancellation_events().is_empty());
    }

    #[test]
    fn request_executor_clone_preserves_raw_results_and_prompt_drop_cancellation() {
        let cx = Cx::for_testing();
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new(std::iter::empty()),
            ResultPeerEra::Modern,
        );
        let clone = executor.clone();
        assert_eq!(clone.result_peer_era(), ResultPeerEra::Modern);

        let mut completed = executor
            .execute(&cx, request(80))
            .expect("primary clone commits its request");
        let dropped = clone
            .execute(&cx, request(81))
            .expect("secondary clone shares the same multiplexed core");
        let raw_result = r#"{"resultType":"complete","opaque":{"decimal":1.20e+4}}"#;
        let typed_result: Value = serde_json::from_str(raw_result).expect("raw result is JSON");
        clone
            .route_response_with_raw_result(
                &cx,
                JsonRpcResponse::success(RequestId::Number(80), typed_result),
                Some(raw_result.to_owned()),
            )
            .expect("raw routing admits the completed owner's matching source");
        let (_, preserved_raw_result) = executor
            .wait_with_raw_result(&cx, &mut completed)
            .expect("a response routed by one clone belongs to the exact owner");
        assert_eq!(preserved_raw_result.as_deref(), Some(raw_result));

        drop(dropped);
        assert!(executor.pending_records().is_empty());
        assert!(executor.terminal_records().is_empty());
        assert_eq!(
            executor.take_cancellation_events(),
            vec![CancellationRequested {
                request_id: RequestId::Number(81),
                reason: ExecutionTerminalReason::CallerDropped,
            }],
        );

        assert_eq!(executor.state.borrow().transport.sent.len(), 2);
        clone
            .route_response_with_raw_result(
                &cx,
                JsonRpcResponse::success(
                    RequestId::Number(81),
                    serde_json::json!({"resultType":"complete"}),
                ),
                Some(r#"{"resultType":"complete"}"#.to_owned()),
            )
            .expect("the raw ingress drains cancellation before discarding the tombstoned final");
        let state = executor.state.borrow();
        assert_eq!(state.transport.sent.len(), 3);
        let JsonRpcMessage::Request(cancellation) = &state.transport.sent[2] else {
            panic!("the dropped owner emits a cancellation notification");
        };
        assert_eq!(
            cancellation
                .params
                .as_ref()
                .and_then(|params| params.get("requestId")),
            Some(&Value::from(81)),
        );
    }

    #[test]
    fn request_executor_raw_result_mismatch_rejects_only_its_owner() {
        let cx = Cx::for_testing();
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new(std::iter::empty()),
            ResultPeerEra::Modern,
        );
        let mut rejected = executor
            .execute(&cx, request(82))
            .expect("first owner commits");
        let mut admitted = executor
            .execute(&cx, request(83))
            .expect("second owner commits");
        let raw_result = r#"{"resultType":"complete","opaque":{"decimal":1.20e+4}}"#;
        let admitted_result: Value = serde_json::from_str(raw_result).expect("raw result is JSON");
        executor
            .route_response_with_raw_result(
                &cx,
                JsonRpcResponse::success(
                    RequestId::Number(82),
                    serde_json::json!({"resultType":"complete","opaque":{"decimal":12001}}),
                ),
                Some(raw_result.to_owned()),
            )
            .expect("mismatched raw source is routed to its exact owner");
        executor
            .route_response_with_raw_result(
                &cx,
                JsonRpcResponse::success(RequestId::Number(83), admitted_result),
                Some(raw_result.to_owned()),
            )
            .expect("matching raw source is routed to its exact owner");

        assert_eq!(
            executor
                .wait_with_raw_result(&cx, &mut rejected)
                .expect_err("changing only the typed result rejects its owner")
                .code,
            McpErrorCode::InvalidRequest,
        );
        let (_, preserved_raw_result) = executor
            .wait_with_raw_result(&cx, &mut admitted)
            .expect("the exact sibling result remains admitted");
        assert_eq!(preserved_raw_result.as_deref(), Some(raw_result));
        assert_eq!(
            executor
                .execute(&cx, request(82))
                .expect_err("a peer-protocol terminal outcome also retires its canonical ID")
                .code,
            McpErrorCode::InvalidRequest,
        );
    }

    #[test]
    fn normal_drive_never_fabricates_a_raw_result_source() {
        let cx = Cx::for_testing();
        let raw_result = r#"{"resultType":"complete","opaque":{"decimal":1.20e+4}}"#;
        let typed_result: Value = serde_json::from_str(raw_result).expect("raw result is JSON");
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new([Ok(JsonRpcMessage::Response(JsonRpcResponse::success(
                RequestId::Number(84),
                typed_result,
            )))]),
            ResultPeerEra::Modern,
        );
        let mut execution = executor
            .execute(&cx, request(84))
            .expect("normal transport request commits");

        let (_, retained_source) = executor
            .wait_with_raw_result(&cx, &mut execution)
            .expect("normal drive preserves the typed response for the waiter");
        assert!(retained_source.is_none());
    }

    #[test]
    fn drive_frame_preserves_the_exact_result_source_for_its_request_owner() {
        let cx = Cx::for_testing();
        let raw_result = r#"{"resultType":"complete","opaque":{"decimal":1.20e+4}}"#;
        let frame = ReceivedTransportFrame::admit(
            format!(r#"{{"jsonrpc":"2.0","id":84,"result":{raw_result}}}"#)
                .into_bytes()
                .into_boxed_slice(),
        )
        .expect("one complete source frame is admitted before executor routing");
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new(std::iter::empty()),
            ResultPeerEra::Modern,
        );
        let mut execution = executor
            .execute(&cx, request(84))
            .expect("request commits before the source-preserving ingress frame");

        executor
            .drive_frame(&cx, frame)
            .expect("the admitted frame completes only its exact request owner");

        let (response, retained_source) = executor
            .wait_with_raw_result(&cx, &mut execution)
            .expect("the request owner retains its admitted source result");
        assert_eq!(response.id, Some(RequestId::Number(84)));
        assert_eq!(retained_source.as_deref(), Some(raw_result));
    }

    #[test]
    fn drive_frame_retains_a_listen_complete_source_instead_of_generic_complete_decode() {
        let cx = Cx::for_testing();
        let raw_result =
            r#"{"resultType":"complete","_meta":{"io.modelcontextprotocol/subscriptionId":2}}"#;
        let frame = ReceivedTransportFrame::admit(
            format!(r#"{{"jsonrpc":"2.0","id":2,"result":{raw_result}}}"#)
                .into_bytes()
                .into_boxed_slice(),
        )
        .expect("one listen terminal source frame is admitted before executor routing");
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new(std::iter::empty()),
            ResultPeerEra::Modern,
        );
        let mut listen = executor
            .execute(
                &cx,
                JsonRpcRequest::new(
                    SUBSCRIPTIONS_LISTEN,
                    Some(serde_json::json!({"notifications":{"toolsListChanged":true}})),
                    2,
                ),
            )
            .expect("listen request commits before its terminal frame");
        executor
            .drive_frame(&cx, frame)
            .expect("a listen terminal is not forced through generic complete-result decoding");
        let (response, retained_source) = executor
            .try_take_response_with_raw_result(&mut listen)
            .expect("typed listen surface can take the retained source")
            .expect("the listen terminal is already routed");
        assert_eq!(response.id, Some(RequestId::Number(2)));
        assert_eq!(retained_source.as_deref(), Some(raw_result));
    }

    #[test]
    fn drive_frame_rejects_a_listen_complete_payload_on_an_ordinary_tools_call() {
        let cx = Cx::for_testing();
        let raw_result =
            r#"{"resultType":"complete","_meta":{"io.modelcontextprotocol/subscriptionId":2}}"#;
        let frame = ReceivedTransportFrame::admit(
            format!(r#"{{"jsonrpc":"2.0","id":2,"result":{raw_result}}}"#)
                .into_bytes()
                .into_boxed_slice(),
        )
        .expect("one listen-shaped complete frame is admitted before executor routing");
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new(std::iter::empty()),
            ResultPeerEra::Modern,
        );
        let mut call = executor
            .execute(&cx, request(2))
            .expect("ordinary tools/call commits before the listen-shaped payload");
        executor
            .drive_frame(&cx, frame)
            .expect("the protocol failure is retained on the request owner");
        let error = executor
            .try_take_response_with_raw_result(&mut call)
            .expect_err("changing only the method must reject a listen complete payload");
        assert_eq!(error.code, McpErrorCode::InvalidRequest);
        assert_eq!(error.message, "Peer final result failed protocol decoding");
    }

    #[test]
    fn source_aware_executor_drive_retains_the_exact_result_source() {
        let cx = Cx::for_testing();
        let raw_result = r#"{"resultType":"complete","opaque":{"decimal":7.30e-2}}"#;
        let frame = ReceivedTransportFrame::admit(
            format!(r#"{{"jsonrpc":"2.0","id":84,"result":{raw_result}}}"#)
                .into_bytes()
                .into_boxed_slice(),
        )
        .expect("the selected-reader source frame is admitted");
        let executor = RequestExecutor::with_source_frame_receiver(
            ScriptedTransport::with_source_frames([Ok(frame)]),
            ResultPeerEra::Modern,
            Some(receive_scripted_source_frame),
        );
        let mut execution = executor
            .execute(&cx, request(84))
            .expect("source-aware request commits before its response is read");

        let (_, retained_source) = executor
            .wait_with_raw_result(&cx, &mut execution)
            .expect("the executor's one source-aware reader retains raw result spelling");
        assert_eq!(retained_source.as_deref(), Some(raw_result));
    }

    #[test]
    fn externally_driven_completion_makes_wait_observe_state_without_reading() {
        let cx = Cx::for_testing();
        let queued_self_reader_frame = ReceivedTransportFrame::admit(
            br#"{"jsonrpc":"2.0","id":999,"result":{"resultType":"complete"}}"#
                .to_vec()
                .into_boxed_slice(),
        )
        .expect("the unused self-reader frame is admitted");
        let raw_result = r#"{"resultType":"complete","opaque":{"decimal":1.20e+4}}"#;
        let externally_driven_frame = ReceivedTransportFrame::admit(
            format!(r#"{{"jsonrpc":"2.0","id":85,"result":{raw_result}}}"#)
                .into_bytes()
                .into_boxed_slice(),
        )
        .expect("the external completion frame is admitted");
        let executor = RequestExecutor::with_source_frame_receiver(
            ScriptedTransport::with_source_frames([Ok(queued_self_reader_frame)]),
            ResultPeerEra::Modern,
            Some(receive_scripted_source_frame),
        );
        let mut execution = executor
            .execute(&cx, request(85))
            .expect("owner commits before selected ingress dispatch");

        executor
            .drive_frame(&cx, externally_driven_frame)
            .expect("the external sole reader completes its request owner");
        let (_, retained_source) = executor
            .wait_with_raw_result(&cx, &mut execution)
            .expect("wait consumes the already-routed outcome without another transport read");

        assert_eq!(retained_source.as_deref(), Some(raw_result));
        assert_eq!(executor.state.borrow().transport.received_frames.len(), 1);
    }

    #[test]
    fn externally_driven_ingress_rejects_a_forced_second_self_reader() {
        let cx = Cx::for_testing();
        let queued_self_reader_frame = ReceivedTransportFrame::admit(
            br#"{"jsonrpc":"2.0","id":86,"result":{"resultType":"complete"}}"#
                .to_vec()
                .into_boxed_slice(),
        )
        .expect("the competing self-reader frame is admitted");
        let external_progress = ReceivedTransportFrame::admit(
            br#"{"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":86,"progress":0.5}}"#
                .to_vec()
                .into_boxed_slice(),
        )
        .expect("the external owner first claims ingress");
        let executor = RequestExecutor::with_source_frame_receiver(
            ScriptedTransport::with_source_frames([Ok(queued_self_reader_frame)]),
            ResultPeerEra::Modern,
            Some(receive_scripted_source_frame),
        );
        let mut execution = executor
            .execute(&cx, request(86))
            .expect("request commits before the forced two-reader attempt");

        executor
            .drive_frame(&cx, external_progress)
            .expect("external frame claims the sole ingress owner");
        let error = executor
            .drive(&cx)
            .expect_err("a self-reader cannot consume a frame after external ingress is selected");
        assert_eq!(error.code, McpErrorCode::InvalidRequest);
        assert_eq!(executor.state.borrow().transport.received_frames.len(), 1);
        assert_eq!(
            execution
                .take_stream_notifications()
                .expect("the external owner retains its progress")
                .len(),
            1
        );
        let error = executor
            .wait(&cx, &mut execution)
            .expect_err("a pending external execution must not make wait read transport");
        assert_eq!(error.code, McpErrorCode::InvalidRequest);
        assert_eq!(executor.state.borrow().transport.received_frames.len(), 1);
    }

    #[test]
    fn drive_frame_routes_matching_progress_to_its_request_owner() {
        let cx = Cx::for_testing();
        let frame = ReceivedTransportFrame::admit(
            br#"{"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":85,"progress":0.5}}"#
                .to_vec()
                .into_boxed_slice(),
        )
        .expect("matching progress frame is admitted before routing");
        let executor = RequestExecutor::new(ScriptedTransport::new(std::iter::empty()));
        let mut execution = executor
            .execute(&cx, request(85))
            .expect("matching-progress request commits");

        executor
            .drive_frame(&cx, frame)
            .expect("matching progress routes without a second reader");

        let stream = execution
            .take_stream_notifications()
            .expect("live owner retains its matching progress");
        assert_eq!(stream.len(), 1);
        assert_eq!(stream[0].method, "notifications/progress");
        assert!(executor.take_notifications().is_empty());
    }

    #[test]
    fn drive_frame_wrong_progress_token_is_not_owned_by_the_adjacent_request() {
        let cx = Cx::for_testing();
        let frame = ReceivedTransportFrame::admit(
            br#"{"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":86,"progress":0.5}}"#
                .to_vec()
                .into_boxed_slice(),
        )
        .expect("near-identical progress frame is admitted before routing");
        let executor = RequestExecutor::new(ScriptedTransport::new(std::iter::empty()));
        let mut execution = executor
            .execute(&cx, request(85))
            .expect("only the request ID differs from the matching positive");
        let pending_before = executor.pending_records();

        executor
            .drive_frame(&cx, frame)
            .expect("foreign progress remains connection-level activity");

        assert_eq!(executor.pending_records(), pending_before);
        assert!(
            execution
                .take_stream_notifications()
                .expect("foreign progress has no request owner")
                .is_empty()
        );
        assert_eq!(executor.take_notifications().len(), 1);
    }

    #[test]
    fn drive_frame_flushes_dropped_owner_cancellation_before_its_late_final() {
        let cx = Cx::for_testing();
        let raw_result = r#"{"resultType":"complete"}"#;
        let frame = ReceivedTransportFrame::admit(
            format!(r#"{{"jsonrpc":"2.0","id":87,"result":{raw_result}}}"#)
                .into_bytes()
                .into_boxed_slice(),
        )
        .expect("late final source is admitted before routing");
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new(std::iter::empty()),
            ResultPeerEra::Modern,
        );
        let dropped = executor
            .execute(&cx, request(87))
            .expect("owner commits before its request-owned handle drops");
        drop(dropped);

        executor
            .drive_frame(&cx, frame)
            .expect("the sole ingress frame first drains the dropped owner's cancellation");

        assert!(executor.pending_records().is_empty());
        assert!(executor.take_uncorrelated_responses().is_empty());
        assert_eq!(
            executor.take_cancellation_events(),
            vec![CancellationRequested {
                request_id: RequestId::Number(87),
                reason: ExecutionTerminalReason::CallerDropped,
            }],
        );
        let state = executor.state.borrow();
        assert_eq!(state.transport.sent.len(), 2);
        let JsonRpcMessage::Request(cancellation) = &state.transport.sent[1] else {
            panic!("dropped execution emits one modern cancellation control");
        };
        assert_eq!(cancellation.method, "notifications/cancelled");
    }

    #[test]
    fn completed_canonical_id_blocks_alias_reuse_until_tombstone_expiry() {
        let cx = Cx::for_testing();
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new(std::iter::empty()),
            ResultPeerEra::Modern,
        );
        let mut completed = executor
            .execute(&cx, request(85))
            .expect("baseline request commits");
        executor
            .route_response_with_raw_result(
                &cx,
                JsonRpcResponse::success(
                    RequestId::Integer("85e0".to_owned()),
                    serde_json::json!({"resultType":"complete"}),
                ),
                Some(r#"{"resultType":"complete"}"#.to_owned()),
            )
            .expect("a numeric response alias completes the baseline owner");

        let alias = || {
            JsonRpcRequest::new(
                "tools/call",
                Some(serde_json::json!({"id": "same-canonical-id"})),
                RequestId::Integer("85e0".to_owned()),
            )
        };
        assert_eq!(
            executor
                .execute(&cx, alias())
                .expect_err("an unconsumed terminal outcome retains its canonical ID")
                .code,
            McpErrorCode::InvalidRequest,
        );
        assert_eq!(
            executor
                .wait(&cx, &mut completed)
                .expect("baseline owner consumes its exact final response")
                .id,
            Some(RequestId::Integer("85e0".to_owned())),
        );
        assert_eq!(
            executor
                .execute(&cx, alias())
                .expect_err("consuming the terminal outcome cannot reopen its canonical ID")
                .code,
            McpErrorCode::InvalidRequest,
        );

        let key = RequestId::Number(85)
            .correlation_key()
            .expect("numeric test ID is canonical");
        executor
            .state
            .borrow_mut()
            .tombstones
            .get_mut(&key)
            .expect("normal terminal outcome retains a canonical tombstone")
            .expires_at = Instant::now();
        let mut replacement = executor
            .execute(&cx, alias())
            .expect("only tombstone expiry permits the canonical replacement");
        executor
            .route_response_with_raw_result(
                &cx,
                JsonRpcResponse::success(
                    RequestId::Number(85),
                    serde_json::json!({"resultType":"complete"}),
                ),
                Some(r#"{"resultType":"complete"}"#.to_owned()),
            )
            .expect("the post-expiry final belongs to the replacement owner");
        assert_eq!(
            executor
                .wait(&cx, &mut replacement)
                .expect("the canonical replacement receives its own final")
                .id,
            Some(RequestId::Number(85)),
        );
    }

    #[test]
    fn normal_terminal_late_duplicate_negative_cannot_complete_an_adjacent_owner() {
        let cx = Cx::for_testing();
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new(std::iter::empty()),
            ResultPeerEra::Modern,
        );
        let mut completed = executor
            .execute(&cx, request(86))
            .expect("baseline request commits");
        let raw_result = r#"{"resultType":"complete"}"#;
        executor
            .route_response_with_raw_result(
                &cx,
                JsonRpcResponse::success(
                    RequestId::Number(86),
                    serde_json::json!({"resultType":"complete"}),
                ),
                Some(raw_result.to_owned()),
            )
            .expect("baseline owner receives its terminal response");
        executor
            .wait(&cx, &mut completed)
            .expect("baseline owner consumes its terminal response");
        let mut adjacent = executor
            .execute(&cx, request(87))
            .expect("an unrelated owner remains admissible");
        let pending_before_late_duplicate = executor.pending_records();

        executor
            .route_response_with_raw_result(
                &cx,
                JsonRpcResponse::success(
                    RequestId::Number(86),
                    serde_json::json!({"resultType":"complete"}),
                ),
                Some(raw_result.to_owned()),
            )
            .expect("changing only the late final ID targets the retired owner");
        assert_eq!(executor.pending_records(), pending_before_late_duplicate);
        executor
            .route_response_with_raw_result(
                &cx,
                JsonRpcResponse::success(
                    RequestId::Number(87),
                    serde_json::json!({"resultType":"complete"}),
                ),
                Some(raw_result.to_owned()),
            )
            .expect("only the adjacent owner's final may complete it");
        assert_eq!(
            executor
                .wait(&cx, &mut adjacent)
                .expect("the late duplicate cannot poison the adjacent owner")
                .id,
            Some(RequestId::Number(87)),
        );
        let late_duplicates = executor.take_uncorrelated_responses();
        assert_eq!(late_duplicates.len(), 1);
        assert_eq!(late_duplicates[0].id, Some(RequestId::Number(86)));
    }

    #[test]
    fn numeric_aliases_share_admission_response_and_tombstone_ownership() {
        let cx = Cx::for_testing();
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new(std::iter::empty()),
            ResultPeerEra::Modern,
        );
        let mut owner = executor
            .execute(&cx, request(86))
            .expect("baseline numeric owner commits");

        let alias = JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({"id": "alias"})),
            RequestId::Integer("86e0".to_owned()),
        );
        let error = executor
            .execute(&cx, alias)
            .expect_err("a numeric alias cannot create a second pending owner");
        assert_eq!(error.code, McpErrorCode::InvalidRequest);
        assert_eq!(executor.pending_records().len(), 1);
        assert_eq!(executor.state.borrow().transport.sent.len(), 1);

        executor
            .route_response_with_raw_result(
                &cx,
                JsonRpcResponse::success(
                    RequestId::Integer("86e0".to_owned()),
                    serde_json::json!({"resultType":"complete"}),
                ),
                Some(r#"{"resultType":"complete"}"#.to_owned()),
            )
            .expect("a numeric response alias completes the original owner");
        let response = executor
            .wait(&cx, &mut owner)
            .expect("the original owner receives its aliased final response");
        assert_eq!(response.id, Some(RequestId::Integer("86e0".to_owned())));

        let tombstoned = executor
            .execute(&cx, request(87))
            .expect("second owner commits before caller drop");
        drop(tombstoned);
        let alias = JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({"id": "tombstone-alias"})),
            RequestId::Integer("87e0".to_owned()),
        );
        let error = executor
            .execute(&cx, alias)
            .expect_err("a numeric alias cannot reuse a tombstoned owner");
        assert_eq!(error.code, McpErrorCode::InvalidRequest);
        executor
            .route_response_with_raw_result(
                &cx,
                JsonRpcResponse::success(
                    RequestId::Integer("87e0".to_owned()),
                    serde_json::json!({"resultType":"complete"}),
                ),
                Some(r#"{"resultType":"complete"}"#.to_owned()),
            )
            .expect("a numeric alias is discarded by its matching tombstone");
        executor
            .route_response_with_raw_result(
                &cx,
                JsonRpcResponse::success(
                    RequestId::Number(87),
                    serde_json::json!({"resultType":"complete"}),
                ),
                Some(r#"{"resultType":"complete"}"#.to_owned()),
            )
            .expect("a second late numeric alias remains owned by the tombstone");
        let alias = JsonRpcRequest::new(
            "tools/call",
            Some(serde_json::json!({"id": "tombstone-second-late-alias"})),
            RequestId::Number(87),
        );
        let error = executor
            .execute(&cx, alias)
            .expect_err("a late response never consumes the tombstone before its expiry");
        assert_eq!(error.code, McpErrorCode::InvalidRequest);
        assert!(executor.pending_records().is_empty());
        assert!(executor.take_uncorrelated_responses().is_empty());
    }

    #[test]
    fn numeric_alias_tombstone_expiry_allows_a_new_owner() {
        let cx = Cx::for_testing();
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new(std::iter::empty()),
            ResultPeerEra::Modern,
        );
        let dropped = executor
            .execute(&cx, request(89))
            .expect("baseline numeric owner commits before drop");
        drop(dropped);
        let key = RequestId::Number(89)
            .correlation_key()
            .expect("numeric test ID is canonical");
        executor
            .state
            .borrow_mut()
            .tombstones
            .get_mut(&key)
            .expect("dropped owner installs its tombstone")
            .expires_at = Instant::now();

        let mut replacement = executor
            .execute(
                &cx,
                JsonRpcRequest::new(
                    "tools/call",
                    Some(serde_json::json!({"id": "replacement-alias"})),
                    RequestId::Integer("89e0".to_owned()),
                ),
            )
            .expect("changing only tombstone expiry permits the canonical replacement");
        executor
            .route_response_with_raw_result(
                &cx,
                JsonRpcResponse::success(
                    RequestId::Number(89),
                    serde_json::json!({"resultType":"complete"}),
                ),
                Some(r#"{"resultType":"complete"}"#.to_owned()),
            )
            .expect("the expired canonical tombstone no longer suppresses its replacement");
        assert_eq!(
            executor
                .wait(&cx, &mut replacement)
                .expect("the replacement owns the post-expiry final")
                .id,
            Some(RequestId::Number(89)),
        );
    }

    #[test]
    fn shutdown_propagates_deferred_drop_cancellation_send_failure() {
        let cx = Cx::for_testing();
        let executor = RequestExecutor::new(ScriptedTransport::new(std::iter::empty()));
        let dropped = executor
            .execute(&cx, request(88))
            .expect("owner commits before its prompt drop");
        drop(dropped);
        executor.state.borrow_mut().transport.send_error = Some(std::io::ErrorKind::BrokenPipe);

        let error = executor
            .shutdown(&cx)
            .expect_err("shutdown must expose deferred cancellation cleanup failure");
        assert_ne!(error.code, McpErrorCode::RequestCancelled);
        let state = executor.state.borrow();
        assert!(state.shutdown);
        assert!(state.terminal_error.is_some());
        assert!(state.deferred_drop_cancellations.is_empty());
        assert!(state.pending.is_empty());
    }

    #[test]
    fn shutdown_propagates_active_owner_cancellation_send_failure() {
        let cx = Cx::for_testing();
        let executor = RequestExecutor::new(ScriptedTransport::new(std::iter::empty()));
        let active = executor
            .execute(&cx, request(90))
            .expect("owner commits before shutdown cancellation");
        executor.state.borrow_mut().transport.send_error = Some(std::io::ErrorKind::BrokenPipe);

        let error = executor
            .shutdown(&cx)
            .expect_err("shutdown must expose active-owner cancellation send failure");
        assert_ne!(error.code, McpErrorCode::RequestCancelled);
        let state = executor.state.borrow();
        assert!(state.shutdown);
        assert!(state.terminal_error.is_some());
        assert!(state.pending.is_empty());
        assert_eq!(state.terminal_records.len(), 1);
        drop(state);
        drop(active);
        assert!(executor.terminal_records().is_empty());
    }

    #[test]
    fn completed_terminal_state_is_released_on_consumption_but_correlation_retires_until_expiry() {
        let cx = Cx::for_testing();
        let mut executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new(std::iter::empty()),
            ResultPeerEra::Modern,
        );
        executor.max_correlations = 1;
        let mut first = executor
            .execute(&cx, request(91))
            .expect("first owner fits the bounded retained-correlation budget");
        executor
            .route_response_with_raw_result(
                &cx,
                JsonRpcResponse::success(
                    RequestId::Number(91),
                    serde_json::json!({"resultType":"complete"}),
                ),
                Some(r#"{"resultType":"complete"}"#.to_owned()),
            )
            .expect("first owner receives its terminal result");
        assert_eq!(executor.state.borrow().completed.len(), 1);
        assert_eq!(executor.terminal_records().len(), 1);
        assert_eq!(
            executor
                .execute(&cx, request(92))
                .expect_err("an unconsumed completed result occupies the bounded budget")
                .code,
            McpErrorCode::InternalError,
        );

        executor
            .wait(&cx, &mut first)
            .expect("consuming the terminal result releases its retained state");
        assert!(executor.state.borrow().completed.is_empty());
        assert!(executor.terminal_records().is_empty());
        assert_eq!(
            executor
                .execute(&cx, request(92))
                .expect_err("the retained tombstone occupies correlation capacity before expiry")
                .code,
            McpErrorCode::InternalError,
        );
        let first_key = RequestId::Number(91)
            .correlation_key()
            .expect("numeric test ID is canonical");
        executor
            .state
            .borrow_mut()
            .tombstones
            .get_mut(&first_key)
            .expect("normal terminal result retires its canonical correlation")
            .expires_at = Instant::now();
        let replacement = executor
            .execute(&cx, request(92))
            .expect("tombstone expiry releases capacity for the near-identical owner");
        drop(replacement);
    }

    #[test]
    fn completed_terminal_retention_is_released_on_handle_drop_and_expiry() {
        let cx = Cx::for_testing();
        let mut executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new(std::iter::empty()),
            ResultPeerEra::Modern,
        );
        executor.max_correlations = 1;
        let completed = executor
            .execute(&cx, request(93))
            .expect("first owner fits the bounded retained-correlation budget");
        executor
            .route_response_with_raw_result(
                &cx,
                JsonRpcResponse::success(
                    RequestId::Number(93),
                    serde_json::json!({"resultType":"complete"}),
                ),
                Some(r#"{"resultType":"complete"}"#.to_owned()),
            )
            .expect("first owner receives its terminal result");
        drop(completed);
        assert!(executor.state.borrow().completed.is_empty());
        assert!(executor.terminal_records().is_empty());
        let completed_key = RequestId::Number(93)
            .correlation_key()
            .expect("numeric test ID is canonical");
        executor
            .state
            .borrow_mut()
            .tombstones
            .get_mut(&completed_key)
            .expect("dropping the completed handle preserves its response tombstone")
            .expires_at = Instant::now();

        let mut expired = executor
            .execute(&cx, request(94))
            .expect("the completed correlation releases capacity only after tombstone expiry");
        executor
            .route_response_with_raw_result(
                &cx,
                JsonRpcResponse::success(
                    RequestId::Number(94),
                    serde_json::json!({"resultType":"complete"}),
                ),
                Some(r#"{"resultType":"complete"}"#.to_owned()),
            )
            .expect("sibling owner receives its terminal result");
        let key = (RequestId::Number(94), expired.generation());
        executor
            .state
            .borrow_mut()
            .terminal_expirations
            .insert(key, Instant::now());
        assert!(executor.terminal_records().is_empty());
        assert_eq!(
            executor
                .wait(&cx, &mut expired)
                .expect_err("changing only terminal retention to expired releases the outcome")
                .code,
            McpErrorCode::InternalError,
        );
        assert!(executor.state.borrow().completed.is_empty());
    }

    #[test]
    fn raw_routing_expired_owner_negative_discards_final_after_lifecycle_gates() {
        let cx = Cx::for_testing();
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new(std::iter::empty()),
            ResultPeerEra::Modern,
        );
        let mut expired = executor
            .execute(&cx, request(85))
            .expect("request commits before raw ingress");
        {
            let mut state = executor.state.borrow_mut();
            let pending = state
                .pending
                .get_mut(
                    &RequestId::Number(85)
                        .correlation_key()
                        .expect("numeric test ID is a valid correlation key"),
                )
                .expect("request remains pending before the planted deadline");
            pending.record.absolute_deadline = Instant::now();
        }

        executor
            .route_response_with_raw_result(
                &cx,
                JsonRpcResponse::success(
                    RequestId::Number(85),
                    serde_json::json!({"resultType":"complete"}),
                ),
                Some(r#"{"resultType":"complete"}"#.to_owned()),
            )
            .expect("raw ingress gates expiry before it considers the final response");

        assert_eq!(
            executor
                .wait(&cx, &mut expired)
                .expect_err("changing only the lifetime to expired rejects the final")
                .code,
            McpErrorCode::RequestCancelled,
        );
        assert!(executor.terminal_records().is_empty());
        assert!(executor.take_uncorrelated_responses().is_empty());
        assert_eq!(executor.state.borrow().transport.sent.len(), 2);
    }

    #[test]
    fn raw_routing_late_dropped_response_negative_cannot_complete_adjacent_owner() {
        let cx = Cx::for_testing();
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new(std::iter::empty()),
            ResultPeerEra::Modern,
        );
        let dropped = executor
            .execute(&cx, request(86))
            .expect("first owner commits");
        drop(dropped);
        let mut adjacent = executor
            .execute(&cx, request(87))
            .expect("the next owner flushes the dropped owner's cancellation");
        let raw_result = r#"{"resultType":"complete"}"#;

        executor
            .route_response_with_raw_result(
                &cx,
                JsonRpcResponse::success(
                    RequestId::Number(86),
                    serde_json::json!({"resultType":"complete"}),
                ),
                Some(raw_result.to_owned()),
            )
            .expect("the tombstone consumes only its late raw final");
        assert_eq!(executor.pending_records().len(), 1);
        assert_eq!(
            executor.pending_records()[0].request_id,
            RequestId::Number(87)
        );

        executor
            .route_response_with_raw_result(
                &cx,
                JsonRpcResponse::success(
                    RequestId::Number(87),
                    serde_json::json!({"resultType":"complete"}),
                ),
                Some(raw_result.to_owned()),
            )
            .expect("only the adjacent owner's exact raw final completes it");
        let response = executor
            .wait(&cx, &mut adjacent)
            .expect("late dropped response must not poison the adjacent owner");
        assert_eq!(response.id, Some(RequestId::Number(87)));
        assert!(executor.take_uncorrelated_responses().is_empty());
    }

    #[test]
    fn modern_executor_cancellation_omits_optional_final_metadata() {
        let cx = Cx::for_testing();
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new(std::iter::empty()),
            ResultPeerEra::Modern,
        );
        let mut execution = executor
            .execute(&cx, request(47))
            .expect("modern request commits before cancellation");

        executor
            .cancel(&cx, &mut execution)
            .expect("final cancellation needs no synthesized metadata");

        let state = executor.state.borrow();
        assert_eq!(state.transport.sent.len(), 2);
        let JsonRpcMessage::Request(cancellation) = &state.transport.sent[1] else {
            panic!("cancellation is a JSON-RPC notification");
        };
        assert!(cancellation.is_notification());
        assert_eq!(cancellation.method, "notifications/cancelled");
        let params = cancellation
            .params
            .as_ref()
            .expect("final cancellation carries parameters");
        assert_eq!(params.get("requestId"), Some(&serde_json::json!(47)));
        assert!(params.get("_meta").is_none());
        assert!(params.get("awaitCleanup").is_none());
    }

    #[test]
    fn malformed_modern_peer_cancellation_leaves_owner_state_unchanged() {
        let cx = Cx::for_testing();
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new([Ok(JsonRpcMessage::Request(JsonRpcRequest::notification(
                "notifications/cancelled",
                Some(serde_json::json!({"reason": "missing request ID"})),
            )))]),
            ResultPeerEra::Modern,
        );
        let mut execution = executor
            .execute(&cx, request(48))
            .expect("baseline modern request commits");
        let pending_before = executor.pending_records();

        executor
            .drive(&cx)
            .expect("invalid peer cancellation is ignored without terminating the client");
        assert_eq!(executor.pending_records(), pending_before);
        assert!(executor.terminal_records().is_empty());
        assert!(executor.take_cancellation_events().is_empty());
        assert_eq!(executor.state.borrow().transport.sent.len(), 1);
        executor
            .cancel(&cx, &mut execution)
            .expect("the still-live owner remains locally cancellable");
    }

    #[test]
    fn unit_clt_01_final_result_stream_reverse_and_peer_cancellation_positive() {
        let cx = Cx::for_testing();
        let complete =
            serde_json::from_str(r#"{"resultType":"complete","opaque":{"decimal":1.20e+4}}"#)
                .expect("exact-number result is valid JSON");
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new([
                Ok(JsonRpcMessage::Request(JsonRpcRequest::new(
                    "sampling/createMessage",
                    Some(serde_json::json!({"messages": [], "maxTokens": 9})),
                    700,
                ))),
                Ok(JsonRpcMessage::Request(JsonRpcRequest::notification(
                    "notifications/progress",
                    Some(serde_json::json!({"progressToken": 42, "progress": 0.5})),
                ))),
                Ok(response(42, complete)),
            ]),
            ResultPeerEra::Modern,
        );
        let mut execution = executor
            .execute(&cx, request(42))
            .expect("request commits before peer traffic arrives");

        executor
            .drive(&cx)
            .expect("modern legacy-shaped reverse request is rejected");
        assert!(executor.take_reverse_requests().is_empty());
        {
            let state = executor.state.borrow();
            let sent = &state.transport.sent;
            assert_eq!(sent.len(), 2);
            let JsonRpcMessage::Response(rejection) = &sent[1] else {
                panic!("modern reverse request receives an error response");
            };
            assert_eq!(rejection.id, Some(RequestId::Number(700)));
            assert_eq!(
                rejection.error.as_ref().map(|error| error.code.clone()),
                Some(i32::from(McpErrorCode::MethodNotFound).into())
            );
        }

        let (decoded, diagnostic, stream) = executor
            .wait_decoded_with_stream(&cx, &mut execution)
            .expect("progress precedes a complete final result");
        assert!(diagnostic.is_none());
        assert_eq!(stream.len(), 1);
        assert_eq!(stream[0].method, "notifications/progress");
        assert!(matches!(decoded, DecodedResult::Complete(_)));
        let complete = match decoded {
            DecodedResult::Complete(complete) => complete,
            DecodedResult::InputRequired(_) | DecodedResult::Deferred(_) => return,
        };
        let opaque = complete
            .extras
            .members()
            .iter()
            .find(|member| member.name == "opaque")
            .expect("unknown result member is retained inertly");
        assert!(matches!(opaque.value, ExactJsonValue::Object(_)));
        let opaque = match &opaque.value {
            ExactJsonValue::Object(opaque) => opaque,
            ExactJsonValue::Null
            | ExactJsonValue::Bool(_)
            | ExactJsonValue::String(_)
            | ExactJsonValue::Number(_)
            | ExactJsonValue::Array(_) => return,
        };
        assert_eq!(
            opaque.get("decimal"),
            Some(&ExactJsonValue::Number("1.20e+4".to_owned()))
        );
        assert_eq!(executor.state.borrow().transport.sent.len(), 2);

        let cancelled = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new([
                Ok(JsonRpcMessage::Request(JsonRpcRequest::notification(
                    "notifications/cancelled",
                    Some(serde_json::json!({"requestId": 43, "reason": "peer text"})),
                ))),
                Ok(response(43, serde_json::json!({}))),
            ]),
            ResultPeerEra::Modern,
        );
        let mut cancelled_execution = cancelled
            .execute(&cx, request(43))
            .expect("request commits before peer cancellation");
        let pending_before = cancelled.pending_records();
        cancelled
            .drive(&cx)
            .expect("server cancellation for a non-subscription is ignored");
        assert_eq!(cancelled.pending_records(), pending_before);
        cancelled
            .wait(&cx, &mut cancelled_execution)
            .expect("the ordinary request remains owned by its terminal response");
        assert_eq!(cancelled.state.borrow().transport.sent.len(), 1);
        assert!(cancelled.take_cancellation_events().is_empty());
        assert!(cancelled.take_notifications().is_empty());
    }

    #[test]
    fn unit_clt_01_final_result_planted_negative_is_owner_scoped() {
        let cx = Cx::for_testing();
        let rejected = serde_json::from_str(r#"{"resultType":null,"opaque":{"decimal":1.20e+4}}"#)
            .expect("planted negative remains structurally valid JSON");
        let accepted =
            serde_json::from_str(r#"{"resultType":"complete","opaque":{"decimal":1.20e+4}}"#)
                .expect("near-identical positive remains valid JSON");
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new([Ok(response(60, rejected)), Ok(response(61, accepted))]),
            ResultPeerEra::Modern,
        );
        let mut rejected_execution = executor
            .execute(&cx, request(60))
            .expect("first request commits");
        let mut accepted_execution = executor
            .execute(&cx, request(61))
            .expect("second request commits");

        assert_eq!(
            executor
                .wait_decoded(&cx, &mut rejected_execution)
                .expect_err("only explicit null instead of complete is rejected")
                .code,
            McpErrorCode::InvalidRequest,
        );
        let (accepted, diagnostic) = executor
            .wait_decoded(&cx, &mut accepted_execution)
            .expect("the other owner remains eligible for its final result");
        assert!(diagnostic.is_none());
        assert!(matches!(accepted, DecodedResult::Complete(_)));
        assert!(executor.terminal_records().is_empty());
        assert_eq!(executor.state.borrow().transport.sent.len(), 2);
        assert!(executor.take_uncorrelated_responses().is_empty());
    }

    #[test]
    #[cfg(feature = "tasks")]
    fn unit_task_01_executor_tool_call_preserves_completed_task_result_source() {
        let cx = Cx::for_testing();
        let raw_result = r#"{"resultType":"task","taskId":"task-escaped","status":"completed","createdAt":"2026-07-28T12:00:00.000Z","lastUpdatedAt":"2026-07-28T12:00:00.000Z","ttlMs":null,"result":{"structuredContent":{"z":1.20e+4,"message":"line\nquoted\" value"},"content":[]}}"#;
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new(std::iter::empty()),
            ResultPeerEra::Modern,
        );
        let mut execution = executor
            .execute_task_tool_call(&cx, task_tool_call_request(72))
            .expect("final tools/call commits before source-aware Task ingress");

        let frame = ReceivedTransportFrame::admit(
            format!(r#"{{"jsonrpc":"2.0","id":72,"result":{raw_result}}}"#)
                .into_bytes()
                .into_boxed_slice(),
        )
        .expect("the complete Tasks JSON-RPC frame is admitted with exact result bytes");
        executor
            .drive_frame(&cx, frame)
            .expect("the executor routes the Tasks result from admitted raw frame source");
        let created = executor
            .wait_task_tool_call(&cx, &mut execution)
            .expect("the public Tasks path decodes from the admitted source");
        let Task::Completed { result, .. } = created.task else {
            panic!("the completed Task branch must reach the public result");
        };
        let expected_nested_result =
            r#"{"structuredContent":{"z":1.20e+4,"message":"line\nquoted\" value"},"content":[]}"#;
        assert_eq!(
            serde_json::to_string(&result).expect("completed Task result re-emits"),
            expected_nested_result,
            "escaped strings, member order, and numeric spelling survive the public Tasks path"
        );
    }

    #[cfg(not(feature = "tasks"))]
    #[test]
    fn feature_off_executor_retains_final_raw_result_source_without_tasks_symbols() {
        let cx = Cx::for_testing();
        let raw_result =
            r#"{"resultType":"complete","content":[],"isError":false,"opaque":{"z":1.20e+4}}"#;
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new(std::iter::empty()),
            ResultPeerEra::Modern,
        );
        let mut execution = executor
            .execute(&cx, request(73))
            .expect("feature-off core request commits before frame ingress");
        let frame = ReceivedTransportFrame::admit(
            format!(r#"{{"jsonrpc":"2.0","id":73,"result":{raw_result}}}"#)
                .into_bytes()
                .into_boxed_slice(),
        )
        .expect("feature-off final JSON-RPC frame is admitted");

        executor
            .drive_frame(&cx, frame)
            .expect("feature-off executor routes an ordinary final result");
        let (_response, result_source) = executor
            .wait_with_raw_result(&cx, &mut execution)
            .expect("feature-off raw result source remains available");
        assert_eq!(result_source.as_deref(), Some(raw_result));
    }

    #[test]
    #[cfg(feature = "tasks")]
    fn unit_task_01_executor_subscription_lifecycle_positive() {
        let cx = Cx::for_testing();
        let task_id = TaskId::parse("task-73").expect("bounded task id");
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new([
                Ok(response(
                    72,
                    serde_json::json!({
                        "resultType": "task",
                        "taskId": task_id,
                        "status": "working",
                        "createdAt": "2026-07-28T12:00:00.000Z",
                        "lastUpdatedAt": "2026-07-28T12:00:00.000Z",
                        "ttlMs": null,
                    }),
                )),
                Ok(tasks_subscription_acknowledgement(73, &task_id)),
                Ok(tasks_status_notification(73, &task_id)),
                Ok(response(
                    73,
                    serde_json::json!({
                        "resultType": "complete",
                        "_meta": {"io.modelcontextprotocol/subscriptionId": 73},
                    }),
                )),
            ]),
            ResultPeerEra::Modern,
        );
        let mut task_execution = executor
            .execute_task_tool_call(&cx, task_tool_call_request(72))
            .expect("final tools/call commits before the peer creates its Task");
        let created = executor
            .wait_task_tool_call(&cx, &mut task_execution)
            .expect("final tools/call returns the typed durable Task handle");
        assert_eq!(created.task.base().task_id, task_id);
        let mut subscription = executor
            .execute_tasks_subscription(&cx, tasks_subscription_request(73, &task_id))
            .expect("final Tasks subscription commits after exact local admission");

        let (accepted_filter, notifications) = executor
            .wait_tasks_subscription(&cx, &mut subscription)
            .expect("acknowledged exact Tasks stream terminates through its owner");
        assert_eq!(
            task_subscription_ids(&accepted_filter).expect("accepted filter remains typed"),
            Some(vec![task_id.clone()]),
        );
        assert_eq!(notifications.len(), 1);
        assert_eq!(notifications[0].params.task.base().task_id, task_id);
        assert!(executor.state.borrow().task_subscriptions.is_empty());
        assert!(executor.pending_records().is_empty());
        assert_eq!(executor.state.borrow().transport.sent.len(), 2);
        assert!(executor.terminal_records().is_empty());
        assert!(executor.take_cancellation_events().is_empty());
    }

    #[test]
    #[cfg(feature = "tasks")]
    fn unit_task_01_executor_subscription_wrong_task_negative_unchanged_state() {
        let cx = Cx::for_testing();
        let requested_task = TaskId::parse("task-73").expect("bounded requested task id");
        let foreign_task = TaskId::parse("task-74").expect("bounded foreign task id");
        let executor = RequestExecutor::with_result_peer_era(
            ScriptedTransport::new([
                Ok(tasks_subscription_acknowledgement(73, &requested_task)),
                Ok(tasks_status_notification(73, &foreign_task)),
            ]),
            ResultPeerEra::Modern,
        );
        let subscription = executor
            .execute_tasks_subscription(&cx, tasks_subscription_request(73, &requested_task))
            .expect("baseline exact Tasks subscription commits");
        executor
            .drive(&cx)
            .expect("baseline acknowledgement is admitted");
        let before_pending = executor.pending_records();
        let before_accepted = executor
            .state
            .borrow()
            .task_subscriptions
            .get(&(RequestId::Number(73), subscription.generation()))
            .and_then(|subscription| subscription.accepted_filter.clone());
        let before_accepted_snapshot =
            serde_json::to_value(&before_accepted).expect("accepted filter snapshot serializes");

        let error = executor
            .drive(&cx)
            .expect_err("changing only taskId to an unacknowledged task must reject the event");
        assert_eq!(error.code, McpErrorCode::InvalidRequest);
        assert_eq!(executor.pending_records(), before_pending);
        let after_accepted = executor
            .state
            .borrow()
            .task_subscriptions
            .get(&(RequestId::Number(73), subscription.generation()))
            .and_then(|subscription| subscription.accepted_filter.clone());
        assert_eq!(
            serde_json::to_value(after_accepted).expect("accepted filter snapshot serializes"),
            before_accepted_snapshot,
        );
        assert!(
            executor
                .take_tasks_subscription_notifications(&subscription)
                .expect("rejected event leaves the listener queue unchanged")
                .is_empty()
        );
        assert_eq!(executor.state.borrow().transport.sent.len(), 1);
        assert!(executor.terminal_records().is_empty());
        assert!(executor.take_cancellation_events().is_empty());
        assert!(executor.take_notifications().is_empty());
    }

    #[test]
    fn cache_03_tolerates_missing_and_negative_cache_ttl_as_immediately_stale() {
        let request = CoreRequest::Final(fastmcp_protocol::FinalCoreRequest::ToolsList(
            fastmcp_protocol::FinalListParams {
                meta: fastmcp_protocol::common_types::OpenMetadata::default(),
                cursor: None,
                include_tags: None,
                exclude_tags: None,
            },
        ));

        let (missing, missing_diagnostic) = decode_core_result_with_cache_ttl(
            &request,
            &serde_json::json!({
                "resultType": "complete",
                "tools": [],
                "cacheScope": "private",
            }),
        )
        .expect("a missing peer TTL is normalized to zero freshness");
        assert_eq!(missing_diagnostic, Some(FinalCacheTtlDiagnostic::Missing));
        assert!(matches!(
            missing,
            CoreResult::Final(FinalCoreResult::ToolsList { result, .. })
                if result.payload.ttl_ms.try_as_millis() == Ok(0)
                    && result.payload.ttl_ms.as_str() == "0"
        ));

        let (negative, negative_diagnostic) = decode_core_result_with_cache_ttl(
            &request,
            &serde_json::json!({
                "resultType": "complete",
                "tools": [],
                "ttlMs": -1.5,
                "cacheScope": "private",
            }),
        )
        .expect("a negative peer TTL is normalized to zero freshness");
        assert_eq!(negative_diagnostic, Some(FinalCacheTtlDiagnostic::Negative));
        assert!(matches!(
            negative,
            CoreResult::Final(FinalCoreResult::ToolsList { result, .. })
                if result.payload.ttl_ms.try_as_millis() == Ok(0)
                    && result.payload.ttl_ms.as_str() == "0"
        ));

        let exact_source = r#"{"resultType":"complete","tools":[],"zeta":{"second":2,"first":1},"ttlMs":-1,"cacheScope":"private","alpha":1.20e+4}"#;
        let exact_value = serde_json::from_str(exact_source).expect("exact TTL source is JSON");
        let (exact, diagnostic) = decode_core_result_with_cache_ttl_from_source(
            &request,
            &exact_value,
            Some(exact_source),
        )
        .expect("negative TTL compatibility retains every other source lexeme");
        assert_eq!(diagnostic, Some(FinalCacheTtlDiagnostic::Negative));
        let CoreResult::Final(FinalCoreResult::ToolsList { result, .. }) = exact else {
            panic!("exact TTL source selects tools/list");
        };
        assert_eq!(result.payload.ttl_ms.as_str(), "0");
        assert_eq!(
            result
                .payload
                .ttl_ms
                .try_as_millis()
                .expect("normalized TTL fits the local duration domain"),
            0
        );
        assert_eq!(
            result
                .extras
                .members()
                .iter()
                .map(|member| member.name.as_str())
                .collect::<Vec<_>>(),
            vec!["zeta", "alpha"],
        );
        assert_eq!(
            result.extras.members()[1].value,
            fastmcp_protocol::ExactJsonValue::Number("1.20e+4".to_owned()),
        );

        assert!(
            decode_core_result_with_cache_ttl(
                &request,
                &serde_json::json!({
                    "resultType": "complete",
                    "tools": [],
                    "ttlMs": 1.5,
                    "cacheScope": "private",
                }),
            )
            .is_err()
        );
    }
}