klieo-mcp-server 2.2.0

Expose any klieo ToolInvoker or Agent as an MCP server over stdio or HTTP. The inverse of klieo-tools-mcp.
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
//! HTTP transport for `McpServer`. Streamable HTTP per the MCP
//! 2025-03-26 spec. Single-shot JSON responses for all methods except
//! `tools/call` with `_meta.progressToken`, which upgrades to an SSE
//! stream per MCP spec §6.4.
//!
//! Gated behind the `http` cargo feature. See the crate-level
//! docs for out-of-scope items (sessions, auth).
//!
//! ## Lock acquisition order
//!
//! Across the multi-session paths:
//!   1. [`McpServer::sessions`](crate::McpServer) (write or read)
//!   2. [`McpServer::principal_counts`](crate::McpServer) (write)
//!
//! Either lock is taken alone where the other is not needed. When
//! both are needed (the `initialize` admission check), `sessions` is
//! taken FIRST and `principal_counts` SECOND. Eviction paths
//! decrement `principal_counts` AFTER releasing the `sessions`
//! guard, preserving the order.

use crate::{
    rpc_error, tool_error_to_envelope, McpServer, McpServerError, JSONRPC_INVALID_PARAMS,
    JSONRPC_LEADER_DIED, JSONRPC_PARSE_ERROR, JSONRPC_SERVER_ERROR, JSONRPC_UNAUTHENTICATED,
    MCP_LEADER_KEY_PREFIX,
};
use axum::{
    body::Bytes,
    extract::{DefaultBodyLimit, State},
    http::{header, HeaderMap, StatusCode},
    response::{IntoResponse, Response},
    routing::post,
    Json, Router,
};
use futures::{Stream, StreamExt as _};
use klieo_auth_common::Identity;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::atomic::AtomicU64;
use std::sync::Arc;
use tracing::{error, instrument, warn};
use tracing_opentelemetry::OpenTelemetrySpanExt as _;

const MAX_BODY_BYTES: usize = 1 << 20; // 1 MiB
const CANCEL_SUBJECT_PREFIX: &str = "klieo.mcp.cancel.";
/// Key-prefix in the `klieo-tenants` KV bucket for MCP streams.
/// Mirrors `A2A_OWNERSHIP_KEY_PREFIX` on the A2A side so a single
/// bucket can host both transports without collisions.
const MCP_OWNERSHIP_KEY_PREFIX: &str = "mcp.";
/// Wire header carrying the streamable-HTTP session identifier.
/// Set on the `initialize` response, echoed by the client on every
/// subsequent POST + GET. ADR-028.
const MCP_SESSION_ID_HEADER: &str = "Mcp-Session-Id";

/// Standard SSE-resumption header. Clients echo the last `id:` they
/// observed; the GET /mcp handler parses it as a `u64` and snapshots
/// the session's resume buffer for any frames strictly newer than the
/// supplied id.
const LAST_EVENT_ID_HEADER: &str = "Last-Event-Id";

/// Initial capacity hint for the per-frame SSE body buffer.
///
/// Sized to cover the `id: <N>\ndata: <payload>\n\n` framing
/// plus a typical small JSON payload without forcing a realloc.
/// Larger payloads grow the `BytesMut` once.
pub(crate) const SSE_FRAME_HINT_BYTES: usize = 512;

/// Per-batch JSON-RPC element cap. Combined with the 1 MiB body cap
/// this bounds worst-case batch work.
const MAX_BATCH_ITEMS: usize = 100;

/// Construct the structured-logged 500 returned when a session-mint
/// `OnceCell::set` lost a race. Distinguishes a real server invariant
/// violation from the legitimate `.get().is_some()` 409 path: the
/// `.get()` branch fires whenever a second `initialize` races past the
/// guard with a session already minted; hitting THIS branch means two
/// requests both raced past the `.get()` check, which is an internal
/// invariant violation worth surfacing to operators rather than
/// presenting as a benign client-side conflict.
fn mint_session_race_500(
    raw_id: Option<&serde_json::Value>,
    field: &'static str,
    attempted_session_id: Option<uuid::Uuid>,
) -> Response {
    error!(
        target: "klieo::mcp::session",
        field,
        attempted_session_id = ?attempted_session_id,
        "session-mint race (concurrent initialize past guard)"
    );
    (
        StatusCode::INTERNAL_SERVER_ERROR,
        Json(rpc_error(
            raw_id.cloned(),
            JSONRPC_SERVER_ERROR,
            "internal: session mint race",
        )),
    )
        .into_response()
}

impl McpServer {
    /// Build the axum [`Router`] that serves `POST /mcp`. The
    /// caller may mount this under their own application or hand
    /// it to [`Self::serve_http`].
    ///
    /// No middleware is applied beyond a 1 MiB body limit and a
    /// `Content-Type: application/json` guard. CORS, tracing,
    /// auth, and rate-limiting are caller-owned — wrap the
    /// returned `Router` with whatever `tower` layers you need.
    pub fn router(self: &Arc<Self>) -> Router {
        router_impl(self.clone())
    }

    /// Bind to `addr` and serve until `parent_cancel` fires or
    /// the listener errors out.
    ///
    /// # Security
    /// No authentication is performed. Bind to `127.0.0.1`
    /// unless the listener is fronted by a reverse proxy that
    /// enforces auth. Plain HTTP only — terminate TLS at the
    /// proxy.
    pub async fn serve_http(self: Arc<Self>, addr: SocketAddr) -> Result<(), McpServerError> {
        let cancel = self.parent_cancel.clone();
        let listener = tokio::net::TcpListener::bind(addr).await?;
        let router = self.router();
        axum::serve(listener, router)
            .with_graceful_shutdown(async move { cancel.cancelled().await })
            .await?;
        Ok(())
    }
}

fn router_impl(server: Arc<McpServer>) -> Router {
    Router::new()
        .route("/mcp", post(post_mcp).get(get_mcp).delete(delete_mcp))
        .layer(DefaultBodyLimit::max(MAX_BODY_BYTES))
        .with_state(server)
}

#[instrument(
    skip_all,
    fields(
        rpc.system = "klieo-mcp",
        rpc.method = tracing::field::Empty,
        http.request.method = "POST",
    ),
)]
async fn post_mcp(
    State(server): State<Arc<McpServer>>,
    headers: HeaderMap,
    body: Bytes,
) -> Response {
    // Cluster 0.23: stitch the current span under any upstream W3C
    // tracecontext carried in `traceparent` / `tracestate` headers so
    // load-balancer / sibling-service traces fold into klieo's tree.
    // Empty / malformed headers yield an empty Context; behaviour
    // pre-0.23 (no parent) is preserved when callers send neither.
    let parent_cx = klieo_core::extract_traceparent(&klieo_headers_from_axum(&headers));
    tracing::Span::current().set_parent(parent_cx);

    if server.parent_cancel.is_cancelled() {
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(rpc_error(
                None,
                JSONRPC_SERVER_ERROR,
                "server shutting down",
            )),
        )
            .into_response();
    }

    if !content_type_is_json(&headers) {
        return StatusCode::UNSUPPORTED_MEDIA_TYPE.into_response();
    }

    let raw: serde_json::Value = match serde_json::from_slice(&body) {
        Ok(v) => v,
        Err(e) => {
            warn!(error = %e, "rejected malformed JSON-RPC body");
            return (
                StatusCode::BAD_REQUEST,
                Json(rpc_error(
                    None,
                    JSONRPC_PARSE_ERROR,
                    "malformed JSON-RPC body",
                )),
            )
                .into_response();
        }
    };

    if let Some(method) = raw.get("method").and_then(|m| m.as_str()) {
        tracing::Span::current().record("rpc.method", method);
    }

    // OAuth / bearer / arbitrary-Authenticator gate. Runs BEFORE
    // `try_sse_upgrade` so an unauthenticated tools/call with a
    // progressToken returns a JSON -32001 envelope rather than an
    // SSE stream (the stream would otherwise leak the start of an
    // invocation an unauthorised principal must not see). Skipped
    // entirely when no authenticator is wired, preserving the
    // pre-0.21 caller-owned-middleware contract.
    let identity = match enforce_authenticator(&server, &headers, &body, &raw).await {
        Ok(identity) => identity,
        Err(rejection) => return rejection,
    };

    // Streamable-HTTP session lifecycle. `initialize` mints the session
    // id + echoes it in the response header. Every subsequent non-
    // `initialize` request must echo the same id back — mismatched ids
    // are rejected with 409, missing ids with 400. ADR-028.
    let method = raw.get("method").and_then(|m| m.as_str()).unwrap_or("");
    if method == "initialize" {
        return handle_initialize_post(&server, raw, identity).await;
    }

    // Non-initialize POSTs require a session header once any session
    // has been minted on this server. The registry-emptiness guard
    // lets a non-initialize POST on a fresh server (no sessions yet)
    // fall through to `dispatch` without a session, so HTTP servers
    // that never `initialize` still serve in-process unit-test
    // traffic. Once the registry holds at least one entry, the
    // header is mandatory. `identity` (when present) is threaded into
    // `require_session` so the per-session principal binding is
    // enforced on every subsequent request — CWE-639 cross-tenant
    // session reuse returns 404.
    let session = if server.sessions.read().await.is_empty() {
        None
    } else {
        match require_session(&headers, &server, identity.as_ref()).await {
            Ok(s) => Some(s),
            Err(rejection) => return rejection,
        }
    };

    // HTTP outbound responses arrive as POST bodies with shape
    // {id, result|error, ...} and no `method`. Route them to the
    // session's outbound correlation table rather than handle_jsonrpc.
    // Only single-object bodies qualify — batch arrays fall through
    // to `dispatch` so their per-element method semantics survive.
    // ADR-028.
    if raw.is_object() && raw.get("method").is_none() {
        let Some(session) = session.as_ref() else {
            warn!(
                target: "mcp.http",
                "POST /mcp body has no method and no session header; rejecting",
            );
            return (
                StatusCode::BAD_REQUEST,
                Json(rpc_error(None, JSONRPC_PARSE_ERROR, "missing method")),
            )
                .into_response();
        };
        return route_outbound_response(&server, session, raw).await;
    }

    if let Some(session) = session.as_ref() {
        touch_last_activity(&server, session);
    }

    // SSE upgrade: `tools/call` with `_meta.progressToken` switches to
    // an SSE stream carrying progress frames + a terminal result frame.
    // `klieo/tools/resume` replays buffered events for a progressToken.
    // The verified `Identity` (when present) is threaded into the
    // upgrade path so the cluster-0.22 tenant-binding gate can claim
    // ownership on `tools/call` and check it on `klieo/tools/resume`.
    if let Some(sse) = try_sse_upgrade(server.clone(), raw.clone(), identity).await {
        return sse;
    }

    let resp = dispatch(&server, raw, session.as_ref()).await;
    (StatusCode::OK, Json(resp)).into_response()
}

/// Bump the per-session activity timestamp on the supplied session.
/// Called on every successful POST and on every outbound frame send.
/// The idle reaper compares this against `session_idle_timeout` to
/// detect idle sessions. ADR-028.
///
/// Lock-free relaxed atomic store; synchronous. `server` supplies the
/// reference instant used to encode the timestamp.
fn touch_last_activity(server: &Arc<McpServer>, session: &Arc<crate::session::Session>) {
    session.mark_active(server.server_start);
}

/// Route a POST body that has no `method` (a JSON-RPC response shape:
/// `{id, result|error, ...}`) to the supplied session's outbound
/// correlation table. Returns `202 Accepted` once `complete_pending`
/// has fired, or `400 Bad Request` when the body is missing a
/// numeric `id` OR no outbound primitive is wired on this session
/// (the SSE-stream open path wires it on `GET /mcp`). ADR-028.
async fn route_outbound_response(
    server: &Arc<McpServer>,
    session: &Arc<crate::session::Session>,
    raw: serde_json::Value,
) -> Response {
    let id = raw.get("id").and_then(|v| v.as_i64());
    let outbound = session.outbound.get();
    if let (Some(id), Some(outbound)) = (id, outbound) {
        outbound.complete_pending(id, raw).await;
        touch_last_activity(server, session);
        return StatusCode::ACCEPTED.into_response();
    }
    warn!(
        target: "mcp.http",
        "POST /mcp body has no method and no routable outbound; rejecting",
    );
    (
        StatusCode::BAD_REQUEST,
        Json(rpc_error(None, JSONRPC_PARSE_ERROR, "missing method")),
    )
        .into_response()
}

/// Streamable-HTTP outbound stream entry. Validates the session,
/// authenticates the caller, mints a per-session mpsc whose receiver
/// becomes the response body, and returns an SSE response carrying
/// newline-delimited JSON-RPC frames. ADR-028.
///
/// Single-shot per session: a second concurrent `GET /mcp` for the
/// same active session returns `409 Conflict`. The receiver's
/// lifetime equals the response body's lifetime.
#[instrument(
    skip_all,
    fields(
        rpc.system = "klieo-mcp",
        http.request.method = "GET",
    ),
)]
async fn get_mcp(State(server): State<Arc<McpServer>>, headers: HeaderMap) -> Response {
    let parent_cx = klieo_core::extract_traceparent(&klieo_headers_from_axum(&headers));
    tracing::Span::current().set_parent(parent_cx);

    if server.parent_cancel.is_cancelled() {
        return StatusCode::SERVICE_UNAVAILABLE.into_response();
    }

    // Authenticator runs BEFORE the SSE stream is minted so a 401
    // never leaks a stream byte to an unauthenticated peer. GET
    // carries no JSON-RPC body and no `method` slot, so only the
    // `authenticate` half runs; `authorize_method` is deliberately
    // skipped — scope on the GET observer is granted transitively
    // through the session-id check from the (already-authorized)
    // `initialize`. The verified `Identity` is threaded into
    // `require_session` so the per-session principal binding is
    // enforced before the SSE upgrade starts. ADR-028.
    let identity = match enforce_authenticator_for_get(&server, &headers).await {
        Ok(identity) => identity,
        Err(rejection) => return rejection,
    };

    let session = match require_session(&headers, &server, identity.as_ref()).await {
        Ok(s) => s,
        Err(rejection) => return rejection,
    };
    let session_id = session.id.expect("HTTP session always carries Some(uuid)");

    let replay = match compute_replay_window(&headers, &session, &server) {
        Ok(slice) => slice,
        Err(rejection) => return rejection,
    };

    let (tx, rx) = crate::outbound_ring::bounded_ring::<(u64, std::sync::Arc<serde_json::Value>)>(
        crate::outbound_sink::OUTBOUND_QUEUE_CAPACITY,
    );

    // The outbound primitive's `OnceCell` is a single-writer slot per
    // session: only the first `GET /mcp` for a session may set it.
    // Hitting `Err` here means a concurrent GET raced past
    // `require_session` for the same session id — a server invariant
    // violation, surfaced via `mint_session_race_500` rather than
    // collapsed to a generic 4xx.
    if session.outbound_tx.set(tx.clone()).is_err() {
        return mint_session_race_500(None, "session.outbound_tx", session.id);
    }

    if let Err(rejection) = wire_session_outbound(&server, &session, tx) {
        return rejection;
    }

    let (cleanup_tx, cleanup_rx) = tokio::sync::oneshot::channel::<()>();
    spawn_session_cleanup(server.clone(), session_id, cleanup_rx);
    build_outbound_sse_response(session_id, replay, rx, cleanup_tx)
}

/// Snapshots the per-session resume buffer for the slice with event id
/// strictly greater than the client's `Last-Event-Id`. Returns
/// `Ok(Vec::new())` when the header is absent. Returns
/// `Err(Response)` for the 400 / 410 / 501 wire-status edges:
///
/// - `400 Bad Request` — header is non-ASCII, not parseable as `u64`,
///   or ahead of the server's monotonic event sequence.
/// - `410 Gone` (rpc_error envelope, message `"resume gap; reconnect
///   with fresh initialize"`) — id older than the oldest retained
///   buffer entry, so the replay window cannot be honoured without
///   forging a gap.
/// - `501 Not Implemented` — server built with
///   `with_sse_replay_capacity(0)`.
///
/// The buffer Mutex is dropped before the returned `Vec` leaves; the
/// caller never holds the lock across the SSE body's lifetime. The
/// function is synchronous because every step — header parse, atomic
/// load, `parking_lot::Mutex` guard acquisition, slice collection —
/// completes without yielding.
#[allow(clippy::result_large_err)]
fn compute_replay_window(
    headers: &HeaderMap,
    session: &crate::session::Session,
    server: &McpServer,
) -> Result<Vec<(u64, std::sync::Arc<serde_json::Value>)>, Response> {
    let Some(raw) = headers.get(LAST_EVENT_ID_HEADER) else {
        return Ok(Vec::new());
    };
    let Ok(header_str) = raw.to_str() else {
        return Err((StatusCode::BAD_REQUEST, "Last-Event-Id must be ASCII u64").into_response());
    };
    let Ok(last_id) = header_str.parse::<u64>() else {
        return Err((StatusCode::BAD_REQUEST, "Last-Event-Id is not a valid u64").into_response());
    };
    if !server.sse_replay_enabled() {
        return Err((
            StatusCode::NOT_IMPLEMENTED,
            "resume buffer disabled (with_sse_replay_capacity(0))",
        )
            .into_response());
    }
    let current_head = session
        .next_event_id
        .load(std::sync::atomic::Ordering::Relaxed);
    if last_id >= current_head {
        return Err((
            StatusCode::BAD_REQUEST,
            "Last-Event-Id is ahead of the server's event sequence",
        )
            .into_response());
    }
    let buffer = session.sse_replay_buffer.lock();
    let oldest_retained = buffer.front().map(|(id, _)| *id).unwrap_or(current_head);
    if last_id < oldest_retained.saturating_sub(1) {
        return Err((
            StatusCode::GONE,
            Json(rpc_error(
                None,
                JSONRPC_SERVER_ERROR,
                "resume gap; reconnect with fresh initialize",
            )),
        )
            .into_response());
    }
    Ok(buffer
        .iter()
        .filter(|(id, _)| *id > last_id)
        .cloned()
        .collect())
}

/// Handle `DELETE /mcp`: client-initiated session shutdown.
///
/// Authenticates the caller, parses the `Mcp-Session-Id` header,
/// removes the matching session from the registry under a single
/// write-lock acquisition, marks it closed, drains any pending
/// outbound oneshots so awaiting callers wake with
/// `TransportClosed`, emits
/// `klieo_mcp_session_deleted_total{reason="client_delete"}` for
/// operator visibility, and returns 204 No Content.
///
/// Status codes:
/// - `204 No Content` — session removed.
/// - `400 Bad Request` — missing or malformed `Mcp-Session-Id`.
/// - `401 Unauthorized` — authenticator rejected the caller.
/// - `404 Not Found` — id absent from the registry (never minted,
///   already deleted, or evicted by the idle reaper).
///
/// Idempotency: the registry remove + close marker are both
/// one-shot, so a repeated DELETE for the same id yields 404 rather
/// than re-running drain logic.
async fn delete_mcp(State(server): State<Arc<McpServer>>, headers: HeaderMap) -> Response {
    let identity = match enforce_authenticator_for_delete(&server, &headers).await {
        Ok(identity) => identity,
        Err(rejection) => return rejection,
    };
    let id = match extract_session_id(&headers) {
        Some(id) => id,
        None => {
            return (StatusCode::BAD_REQUEST, "missing or invalid Mcp-Session-Id").into_response();
        }
    };
    // Two-step lookup-then-remove: peek first under the read-lock so a
    // principal mismatch returns 404 without taking the registry
    // write-lock OR mutating state. Only proceed to the remove when
    // the caller's principal matches the binding established at
    // `initialize`. Mismatch yields 404 (same status as unknown id)
    // so a peer cannot probe the registry for existence — CWE-639.
    {
        let sessions = server.sessions.read().await;
        let Some(session) = sessions.get(&id) else {
            return StatusCode::NOT_FOUND.into_response();
        };
        if !principal_matches(identity.as_ref(), session.principal.as_deref()) {
            return StatusCode::NOT_FOUND.into_response();
        }
    }
    let session = {
        let mut sessions = server.sessions.write().await;
        sessions.remove(&id)
    };
    let Some(session) = session else {
        return StatusCode::NOT_FOUND.into_response();
    };
    let principal = session.principal.clone();
    session.close_and_drain().await;
    server.decrement_principal_count(principal.as_deref()).await;
    metrics::counter!(
        "klieo_mcp_session_deleted_total",
        "reason" => "client_delete"
    )
    .increment(1);
    tracing::info!(
        target: "klieo::mcp::session",
        session_id = %id,
        "session deleted by client"
    );
    StatusCode::NO_CONTENT.into_response()
}

/// Spawn the disconnect-cleanup task tied to the SSE body.
///
/// The task waits on a `oneshot::Receiver` that fires when
/// [`GuardedSseStream`] is dropped (TCP close, axum shutdown, client
/// disconnect). On wake it looks the session up in the
/// [`McpServer::sessions`] registry by `session_id` — the entry may
/// already be gone (DELETE /mcp, idle reaper) and the task tolerates
/// that as a no-op. When present, the session is marked closed, any
/// pending outbound oneshots drain as
/// [`klieo_core::ServerOutboundError::TransportClosed`] so awaiting
/// callers wake immediately, and the entry is removed from the
/// registry so the slot is reclaimed for a fresh `initialize`. The
/// `Sender` side travels with the guard wrapping the response body,
/// so the task can only fire after the body is gone. ADR-028.
fn spawn_session_cleanup(
    server: Arc<McpServer>,
    session_id: uuid::Uuid,
    cleanup_rx: tokio::sync::oneshot::Receiver<()>,
) {
    tokio::spawn(async move {
        let _ = cleanup_rx.await;
        let session = {
            let mut sessions = server.sessions.write().await;
            sessions.remove(&session_id)
        };
        let Some(session) = session else {
            return;
        };
        let principal = session.principal.clone();
        session.close_and_drain().await;
        server.decrement_principal_count(principal.as_deref()).await;
    });
}

/// Wire the per-session outbound primitive (and the roots cache, when
/// the server declared `sampling`) on top of the freshly-minted GET
/// mpsc tx. Mirrors stdio's `ensure_outbound_and_roots`. The caller
/// (`get_mcp`) passes the [`crate::session::Session`] resolved by
/// `require_session`, so the outbound + roots primitives land on the
/// exact session this GET is wiring. Returns `Err(500)` via
/// [`mint_session_race_500`] only if the outbound `OnceCell` was
/// already populated — a server invariant violation (concurrent GET
/// past `require_session` for the same id), not a benign client
/// conflict. The `roots_cache` set is best-effort; a stale cache on
/// the same `Session` survives by design.
#[allow(clippy::result_large_err)]
fn wire_session_outbound(
    server: &Arc<McpServer>,
    session: &Arc<crate::session::Session>,
    tx: crate::outbound_ring::RingSender<(u64, std::sync::Arc<serde_json::Value>)>,
) -> Result<(), Response> {
    use crate::outbound::OutboundRequests;
    use crate::outbound_sink::HttpFrameSink;
    use klieo_core::ServerOutbound;

    let sink: Arc<dyn crate::OutboundFrameSink> = Arc::new(HttpFrameSink::new(
        Arc::downgrade(session),
        tx,
        server.sse_replay_capacity,
    ));
    let outbound = Arc::new(OutboundRequests::new(sink));

    if session.outbound.set(outbound.clone()).is_err() {
        return Err(mint_session_race_500(None, "session.outbound", session.id));
    }
    if server.declare_sampling {
        let as_trait: Arc<dyn ServerOutbound> = outbound.clone();
        let _ = session
            .roots_cache
            .set(Arc::new(crate::roots::RootsCache::new(as_trait)));
    }
    Ok(())
}

/// Encodes one SSE frame into a `Bytes` buffer: `id: <N>\ndata: <json>\n\n`.
///
/// Writes the framing prefix, then streams the JSON payload directly
/// into the same [`bytes::BytesMut`] via [`serde_json::to_writer`],
/// then appends the SSE record terminator. The initial capacity is
/// `SSE_FRAME_HINT_BYTES`; oversized payloads grow the buffer once.
///
/// Returns `None` and logs at `target = "klieo::mcp::sse"` with
/// `event_id` + `session_id` when the JSON payload fails to serialise,
/// so the caller can skip the frame without aborting the stream.
pub fn encode_sse_frame(
    event_id: u64,
    frame: &serde_json::Value,
    session_id: uuid::Uuid,
) -> Option<Bytes> {
    use bytes::BufMut as _;
    use std::fmt::Write as _;
    let mut buf = bytes::BytesMut::with_capacity(SSE_FRAME_HINT_BYTES);
    write!(&mut buf, "id: {event_id}\ndata: ").expect("BytesMut write is infallible");
    match serde_json::to_writer((&mut buf).writer(), frame) {
        Ok(()) => {
            buf.extend_from_slice(b"\n\n");
            Some(buf.freeze())
        }
        Err(err) => {
            tracing::error!(
                target: "klieo::mcp::sse",
                event_id,
                session_id = %session_id,
                error = %err,
                "outbound frame serialisation failed; skipping id",
            );
            None
        }
    }
}

/// Wrap the per-session outbound receiver in an SSE-framed body and
/// build the `text/event-stream` response. `replay` carries the
/// snapshot of buffered `(event_id, frame)` pairs taken by
/// [`compute_replay_window`] before the live ring is attached;
/// fresh streams (no `Last-Event-Id` header) pass `Vec::new()`. The
/// body emits every replay frame in order, then attaches to the
/// live ring receiver.
///
/// Each yielded frame carries the monotonic per-session `event_id`
/// allocated by [`crate::outbound_sink::HttpFrameSink`] as the SSE
/// `id:` field, followed by the JSON-RPC payload as a single-line
/// `data:` field and the SSE record terminator (blank line).
/// Compliant clients track `id:` automatically and replay it via
/// `Last-Event-Id` on reconnect; non-tracking clients see the
/// `data:` payload unchanged. JSON serialisation failures log the
/// offending `event_id` + `session_id` at error severity (target
/// `klieo::mcp::sse`) and skip the frame rather than terminate the
/// stream — the next frame still gets through.
///
/// The stream is wrapped in a [`GuardedSseStream`] so dropping the
/// body (TCP close, axum shutdown, client disconnect) fires
/// `cleanup_tx`, waking the session-cleanup task that drains pending
/// outbound oneshots. Constructing the response cannot fail in
/// practice (status, headers, and body type are all well-formed); the
/// fallback path exists only to keep the handler total.
fn build_outbound_sse_response(
    session_id: uuid::Uuid,
    replay: Vec<(u64, std::sync::Arc<serde_json::Value>)>,
    mut rx: crate::outbound_ring::RingReceiver<(u64, std::sync::Arc<serde_json::Value>)>,
    cleanup_tx: tokio::sync::oneshot::Sender<()>,
) -> Response {
    let stream = async_stream::stream! {
        for (event_id, value) in replay {
            if let Some(frame) = encode_sse_frame(event_id, &value, session_id) {
                yield Ok::<Bytes, std::io::Error>(frame);
            }
        }
        while let Some((event_id, value)) = rx.recv().await {
            if let Some(frame) = encode_sse_frame(event_id, &value, session_id) {
                yield Ok::<Bytes, std::io::Error>(frame);
            }
        }
    };
    let guarded = GuardedSseStream::new(Box::pin(stream), cleanup_tx);
    Response::builder()
        .status(StatusCode::OK)
        .header(header::CONTENT_TYPE, "text/event-stream")
        .header(header::CACHE_CONTROL, "no-cache")
        .header(MCP_SESSION_ID_HEADER, session_id.to_string())
        .body(axum::body::Body::from_stream(guarded))
        .unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response())
}

/// Wraps the outbound SSE body stream so that when the stream is
/// dropped (TCP close, axum shutdown, client disconnect) the server
/// clears the per-session state for the session this stream serves.
/// On drop the contained [`tokio::sync::oneshot::Sender`] fires,
/// waking the cleanup task spawned by [`spawn_session_cleanup`],
/// which removes the session from the registry, marks it closed,
/// and drains pending outbound oneshots. ADR-028.
struct GuardedSseStream<S> {
    inner: S,
    cleanup: Option<tokio::sync::oneshot::Sender<()>>,
}

impl<S> GuardedSseStream<S> {
    fn new(inner: S, cleanup: tokio::sync::oneshot::Sender<()>) -> Self {
        Self {
            inner,
            cleanup: Some(cleanup),
        }
    }
}

impl<S: Stream + Unpin> Stream for GuardedSseStream<S> {
    type Item = S::Item;

    fn poll_next(
        mut self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        Pin::new(&mut self.inner).poll_next(cx)
    }
}

impl<S> Drop for GuardedSseStream<S> {
    fn drop(&mut self) {
        if let Some(sender) = self.cleanup.take() {
            // Receiver may already be gone if the cleanup task was
            // cancelled (server shutdown); the send-error is the
            // intended no-op signal in that case.
            let _ = sender.send(());
        }
    }
}

/// Apply the configured [`klieo_auth_common::Authenticator`] to the
/// inbound request. Returns the verified [`Identity`] on success
/// (or `None` when no authenticator is wired), or a JSON-RPC
/// `-32001` envelope on failure. Authentication failure and
/// authorisation failure both yield the same `-32001` envelope
/// shape; the differing branches are logged so operators can
/// distinguish them in `tracing` output without leaking the
/// distinction onto the wire.
///
/// The `Identity` is returned (rather than consumed inline) so
/// the SSE upgrade path (`stream_tools_call` / `stream_resume`)
/// can thread it into the cluster-0.22 tenant-binding gate.
async fn enforce_authenticator(
    server: &Arc<McpServer>,
    headers: &HeaderMap,
    body: &Bytes,
    raw: &serde_json::Value,
) -> Result<Option<Identity>, Response> {
    let Some(auth) = server.authenticator() else {
        return Ok(None);
    };
    let adapter = AxumHeaders(headers);
    let identity = match auth.authenticate(&adapter, body).await {
        Ok(identity) => identity,
        Err(e) => {
            warn!(target: "mcp.auth", error = ?e, "authenticate failed");
            return Err(unauthenticated_response(raw, "authentication required"));
        }
    };
    let method = raw.get("method").and_then(|m| m.as_str()).unwrap_or("");
    if let Err(e) = auth.authorize_method(&identity, method).await {
        warn!(target: "mcp.auth", method = %method, error = ?e, "authorize_method failed");
        return Err(unauthenticated_response(
            raw,
            "method not authorized for principal",
        ));
    }
    Ok(Some(identity))
}

fn unauthenticated_response(raw: &serde_json::Value, message: &str) -> Response {
    (
        StatusCode::OK,
        Json(rpc_error(
            raw.get("id").cloned(),
            JSONRPC_UNAUTHENTICATED,
            message,
        )),
    )
        .into_response()
}

/// Apply the configured authenticator to a `GET /mcp` request. Only
/// the credential check (`authenticate`) runs; the POST path's
/// per-method scope check (`authorize_method`) is skipped because
/// GET carries no JSON-RPC `method` slot and the observer's scope
/// is granted transitively from the `initialize` POST that minted
/// the session id (the session-id requirement on subsequent calls
/// binds the GET observer to that same principal). Returns `None`
/// when no authenticator is wired, the verified [`Identity`] when
/// it succeeds, or a 401 response with no JSON-RPC envelope on
/// failure. ADR-028.
#[allow(clippy::result_large_err)]
async fn enforce_authenticator_for_get(
    server: &Arc<McpServer>,
    headers: &HeaderMap,
) -> Result<Option<Identity>, Response> {
    let Some(auth) = server.authenticator() else {
        return Ok(None);
    };
    let adapter = AxumHeaders(headers);
    match auth.authenticate(&adapter, &Bytes::new()).await {
        Ok(identity) => Ok(Some(identity)),
        Err(e) => {
            warn!(target: "mcp.auth", error = ?e, "authenticate failed on GET /mcp");
            Err(unauthenticated_response_for_get())
        }
    }
}

/// Build the 401 response returned from `enforce_authenticator_for_get`.
/// Plain status + short reason — GET /mcp has no JSON-RPC envelope to
/// embed an error in, unlike POST. The body is fixed text to avoid
/// echoing any caller-supplied data.
fn unauthenticated_response_for_get() -> Response {
    (StatusCode::UNAUTHORIZED, "authentication required").into_response()
}

/// Authentication gate for `DELETE /mcp`. Mirrors the GET dispatch:
/// runs only the `authenticate` half (no JSON-RPC body, no `method`
/// slot to `authorize_method` against), and yields `Err(rejection)`
/// when the configured authenticator rejects the request — otherwise
/// `Ok(_)`. Kept as a thin wrapper around
/// [`enforce_authenticator_for_get`] so a future divergence (e.g. a
/// distinct DELETE scope policy) has a single edit point.
#[allow(clippy::result_large_err)]
async fn enforce_authenticator_for_delete(
    server: &Arc<McpServer>,
    headers: &HeaderMap,
) -> Result<Option<Identity>, Response> {
    enforce_authenticator_for_get(server, headers).await
}

/// Adapter that exposes axum's [`HeaderMap`] as a
/// [`klieo_auth_common::Headers`] bag so the shared `Authenticator`
/// trait can read the same case-insensitive header surface on both
/// transports. `HeaderName`'s internal representation is already
/// lowercase per RFC 7230 §3.2, so we lowercase the lookup name and
/// pass it through `HeaderMap::get` (which does its own case-
/// insensitive match).
struct AxumHeaders<'a>(&'a HeaderMap);

impl<'a> klieo_auth_common::Headers for AxumHeaders<'a> {
    fn get(&self, name: &str) -> Option<&str> {
        self.0.get(name).and_then(|v| v.to_str().ok())
    }
}

/// Parse the `Mcp-Session-Id` header into a UUID. Returns `None` when
/// the header is absent, non-UTF-8, or not a valid UUID — callers map
/// each to the appropriate HTTP status (400 Bad Request).
fn extract_session_id(headers: &HeaderMap) -> Option<uuid::Uuid> {
    let raw = headers.get(MCP_SESSION_ID_HEADER)?.to_str().ok()?;
    uuid::Uuid::parse_str(raw).ok()
}

/// Parse the `Mcp-Session-Id` header, look up the corresponding
/// session in the registry, and verify the caller's principal matches
/// the binding established at `initialize`.
///
/// `caller` is the [`Identity`] returned by the configured
/// authenticator on this request (`None` when no authenticator is
/// wired — in that mode every session's stored principal is also
/// `None` and the equality check passes trivially).
///
/// A principal mismatch returns the same 404 envelope as an unknown
/// session id: a peer with a stolen session UUID must not be able to
/// distinguish "id never minted" from "id minted by someone else"
/// (CWE-639 IDOR existence-leakage).
///
/// Returns:
/// - `Err((400, "missing or invalid Mcp-Session-Id"))` on missing
///   or malformed header.
/// - `Err((404, JSONRPC_SERVER_ERROR + "unknown session id"))` when
///   the id is not in the registry OR the caller's principal does
///   not match the session's recorded principal.
/// - `Ok(Arc<Session>)` on a successful lookup with matching
///   principal.
async fn require_session(
    headers: &HeaderMap,
    server: &McpServer,
    caller: Option<&Identity>,
) -> Result<std::sync::Arc<crate::session::Session>, Response> {
    let id = extract_session_id(headers).ok_or_else(|| {
        (StatusCode::BAD_REQUEST, "missing or invalid Mcp-Session-Id").into_response()
    })?;
    let unknown_session = || -> Response {
        (
            StatusCode::NOT_FOUND,
            Json(rpc_error(None, JSONRPC_SERVER_ERROR, "unknown session id")),
        )
            .into_response()
    };
    let sessions = server.sessions.read().await;
    let session = sessions.get(&id).cloned().ok_or_else(unknown_session)?;
    if !principal_matches(caller, session.principal.as_deref()) {
        return Err(unknown_session());
    }
    Ok(session)
}

/// Compare a caller's verified principal against the principal
/// recorded on a session at `initialize` time.
///
/// `caller` is `None` when no authenticator is wired on this request;
/// `session_principal` is `None` when the session was minted on a
/// server with no authenticator. Both-None passes (auth-disabled
/// deployment, backwards compatible). Any other combination requires
/// string equality on the principal value (typically the OAuth `sub`
/// claim returned by `Identity::as_str`).
fn principal_matches(caller: Option<&Identity>, session_principal: Option<&str>) -> bool {
    match (caller, session_principal) {
        (None, None) => true,
        (Some(identity), Some(stored)) => identity.as_str() == stored,
        _ => false,
    }
}

/// Handle the `initialize`-shaped POST: mint a fresh UUID v4, build
/// a [`crate::session::Session`] bound to the verified caller
/// principal, insert it atomically into the server's `sessions`
/// registry under a single write-lock acquisition (cap check + insert
/// co-located so two concurrent inserts cannot both pass the cap),
/// and return the dispatch result with the session id echoed in the
/// `Mcp-Session-Id` response header. Called from [`post_mcp`].
///
/// `caller` is the [`Identity`] verified by `enforce_authenticator`
/// for this request (`None` when no authenticator is wired). It is
/// recorded on the [`crate::session::Session`] and enforced by
/// `require_session` on every subsequent POST / GET / DELETE for the
/// session — a different principal presenting the same session UUID
/// is rejected as 404 (CWE-639).
///
/// Cap enforcement: when `sessions.len() >= server.max_sessions` the
/// request is rejected with `503 Service Unavailable` and a
/// `klieo_mcp_session_cap_rejected_total` counter increment for
/// operator visibility. Successful inserts lazy-start the idle reaper
/// task via [`ensure_idle_reaper`].
async fn handle_initialize_post(
    server: &Arc<McpServer>,
    raw: serde_json::Value,
    caller: Option<Identity>,
) -> Response {
    let session_id = uuid::Uuid::new_v4();
    let principal = caller.as_ref().map(|id| id.as_str().to_string());
    let session = std::sync::Arc::new(crate::session::Session::new_http(
        session_id,
        principal,
        server.server_start,
    ));

    {
        let mut sessions = server.sessions.write().await;
        let mut principal_counts = server.principal_counts.write().await;

        if sessions.len() >= server.max_sessions {
            drop(principal_counts);
            drop(sessions);
            tracing::warn!(
                target: "klieo::mcp::session",
                scope = "global",
                cap = server.max_sessions,
                "session cap reached; rejecting initialize"
            );
            metrics::counter!(
                "klieo_mcp_session_cap_rejected_total",
                "scope" => "global"
            )
            .increment(1);
            return (
                StatusCode::SERVICE_UNAVAILABLE,
                Json(rpc_error(
                    raw.get("id").cloned(),
                    JSONRPC_SERVER_ERROR,
                    "session cap reached",
                )),
            )
                .into_response();
        }

        if let Some(p) = session.principal.as_deref() {
            let current = principal_counts.get(p).copied().unwrap_or(0);
            if current >= server.max_sessions_per_principal {
                drop(principal_counts);
                drop(sessions);
                tracing::warn!(
                    target: "klieo::mcp::session",
                    scope = "per_principal",
                    principal = p,
                    cap = server.max_sessions_per_principal,
                    "per-principal session cap reached; rejecting initialize"
                );
                metrics::counter!(
                    "klieo_mcp_session_cap_rejected_total",
                    "scope" => "per_principal"
                )
                .increment(1);
                return (
                    StatusCode::SERVICE_UNAVAILABLE,
                    Json(rpc_error(
                        raw.get("id").cloned(),
                        JSONRPC_SERVER_ERROR,
                        "per-principal session cap reached",
                    )),
                )
                    .into_response();
            }
            *principal_counts.entry(p.to_string()).or_insert(0) += 1;
        }

        sessions.insert(session_id, session.clone());
    }

    ensure_idle_reaper(server).await;

    // Successful initialize counts as the session's first activity:
    // touch the per-session clock before the OK envelope leaves so
    // the idle reaper does not race the response and evict an
    // otherwise-live session.
    let resp = dispatch(server, raw, Some(&session)).await;
    touch_last_activity(server, &session);
    (
        StatusCode::OK,
        [(MCP_SESSION_ID_HEADER, session_id.to_string())],
        Json(resp),
    )
        .into_response()
}

/// Idempotently spawn the idle-session reaper task for this server.
/// The first call populates [`McpServer::idle_reaper_started`] and
/// spawns [`idle_reaper_loop`]; subsequent calls are no-ops, so
/// duplicate `initialize` POSTs do not spawn duplicate reapers. The
/// spawned task holds an `Arc<McpServer>` and exits cleanly when the
/// runtime drops it (typically server shutdown).
async fn ensure_idle_reaper(server: &Arc<McpServer>) {
    let server_for_task = server.clone();
    let _ = server
        .idle_reaper_started
        .get_or_init(|| async move {
            tokio::spawn(idle_reaper_loop(server_for_task));
        })
        .await;
}

/// Drive periodic idle-session reaping for the HTTP session
/// registry. Holds an `Arc<McpServer>` for the task's lifetime and
/// runs until the runtime drops the spawned task (typically server
/// shutdown).
///
/// Wakes on the cadence stored in [`McpServer::idle_reaper_tick`]
/// (defaults to 10 seconds; configurable via
/// [`McpServerBuilder::with_idle_reaper_tick`] in test builds). On
/// each tick, when `session_idle_timeout` is non-zero, snapshots
/// `(id, Arc<Session>)` pairs under a read-lock then drops the
/// lock; per-session probes of `last_activity_millis` run lock-free
/// outside the registry lock so writers (initialize POST, DELETE,
/// SSE disconnect) never queue behind a scan. Entries that probe
/// idle are then removed under a write-lock.
/// After the registry lock is released, each evicted session is
/// marked closed, its pending outbound oneshots are drained as
/// `TransportClosed`, a
/// `klieo_mcp_session_deleted_total{reason="idle_timeout"}` counter
/// is incremented, and an info-level eviction record is emitted.
///
/// `MissedTickBehavior::Skip` prevents tick accumulation if the
/// runtime stalls under load; missed ticks coalesce into a single
/// scan. A `session_idle_timeout` of `Duration::ZERO` disables the
/// scan entirely while leaving the task alive.
async fn idle_reaper_loop(server: Arc<McpServer>) {
    let tick = server.idle_reaper_tick;
    let mut interval = tokio::time::interval(tick);
    interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
    loop {
        interval.tick().await;
        let timeout = server.session_idle_timeout;
        if timeout.is_zero() {
            continue;
        }
        // Snapshot Arcs under the read-lock; probe `last_activity_millis`
        // lock-free outside it so registry writers never queue behind a
        // scan.
        let snapshot: Vec<(uuid::Uuid, Arc<crate::session::Session>)> = {
            let sessions = server.sessions.read().await;
            sessions.iter().map(|(id, s)| (*id, s.clone())).collect()
        };

        let now_millis = server.server_start.elapsed().as_millis() as u64;
        let timeout_millis = timeout.as_millis() as u64;
        let to_evict: Vec<(uuid::Uuid, Arc<crate::session::Session>)> = snapshot
            .into_iter()
            .filter(|(_, session)| {
                let last = session
                    .last_activity_millis
                    .load(std::sync::atomic::Ordering::Relaxed);
                now_millis.saturating_sub(last) > timeout_millis
            })
            .collect();

        if to_evict.is_empty() {
            continue;
        }

        {
            let mut sessions = server.sessions.write().await;
            for (id, _) in &to_evict {
                sessions.remove(id);
            }
        }

        for (id, session) in to_evict {
            let principal = session.principal.clone();
            session.close_and_drain().await;
            server.decrement_principal_count(principal.as_deref()).await;
            metrics::counter!(
                "klieo_mcp_session_deleted_total",
                "reason" => "idle_timeout"
            )
            .increment(1);
            tracing::info!(
                target: "klieo::mcp::session",
                session_id = %id,
                "session evicted by idle reaper"
            );
        }
    }
}

/// Route `tools/call` (SSE upgrade) and `klieo/tools/resume` (replay-only
/// SSE) out of the normal JSON dispatch path. Returns `Some(Response)` when
/// either branch fires, `None` when the request should continue to
/// `dispatch`.
///
/// `identity` is the [`Identity`] verified by `enforce_authenticator` —
/// `None` when no authenticator is wired. Threaded through to the
/// tenant-binding gate in both SSE paths (ADR-022).
#[instrument(skip_all, level = "debug")]
async fn try_sse_upgrade(
    server: Arc<McpServer>,
    raw: serde_json::Value,
    identity: Option<Identity>,
) -> Option<Response> {
    let method = raw.get("method").and_then(|m| m.as_str())?;
    match method {
        "tools/call" => {
            let token_val = raw.pointer("/params/_meta/progressToken")?;
            match token_val {
                serde_json::Value::String(_) | serde_json::Value::Number(_) => {
                    Some(stream_tools_call(server, raw.clone(), token_val.clone(), identity).await)
                }
                _ => {
                    let id = raw.get("id").cloned();
                    Some(
                        (
                            StatusCode::BAD_REQUEST,
                            Json(rpc_error(
                                id,
                                JSONRPC_INVALID_PARAMS,
                                "_meta.progressToken must be a string or number",
                            )),
                        )
                            .into_response(),
                    )
                }
            }
        }
        "klieo/run/resume" => Some(handle_run_resume(server, raw, identity).await),
        "klieo/tools/resume" => {
            let params = match raw.get("params").cloned() {
                Some(p) => p,
                None => {
                    let id = raw.get("id").cloned();
                    return Some(
                        (
                            StatusCode::BAD_REQUEST,
                            Json(rpc_error(
                                id,
                                JSONRPC_INVALID_PARAMS,
                                "klieo/tools/resume: missing params",
                            )),
                        )
                            .into_response(),
                    );
                }
            };
            let parsed: ResumeParams = match serde_json::from_value(params) {
                Ok(p) => p,
                Err(e) => {
                    let id = raw.get("id").cloned();
                    return Some(
                        (
                            StatusCode::BAD_REQUEST,
                            Json(rpc_error(
                                id,
                                JSONRPC_INVALID_PARAMS,
                                &format!("klieo/tools/resume: invalid params: {e}"),
                            )),
                        )
                            .into_response(),
                    );
                }
            };
            Some(stream_resume(server, raw, parsed, identity).await)
        }
        _ => None,
    }
}

#[derive(serde::Deserialize)]
struct ResumeParams {
    #[serde(rename = "progressToken")]
    progress_token: serde_json::Value,
    #[serde(rename = "lastEventId")]
    last_event_id: u64,
}

/// Wire shape of `klieo/run/resume` params. The ticket is the only
/// opaque handle the peer holds; the decision carries the operator's
/// approve/reject verdict plus an optional rejection reason that
/// gets fed back to the model on resume (ADR-045).
#[derive(serde::Deserialize)]
struct RunResumeParams {
    ticket: String,
    decision: RunResumeDecision,
}

#[derive(serde::Deserialize)]
struct RunResumeDecision {
    approved: bool,
    #[serde(default)]
    reason: Option<String>,
}

/// Stable wire message used by `klieo/run/resume` for every
/// fail-closed branch: unknown ticket, foreign-principal ticket, race-
/// loser ticket. Identical bytes in all three cases so the peer cannot
/// distinguish them (IDOR mitigation, CWE-639). The reason a request
/// failed lives in the server log only.
const RUN_RESUME_DENY_MESSAGE: &str = "resume ticket invalid";

/// Stable wire message used when the server has no checkpoint KV
/// wired or no workflow registered under the ticket's workflow name —
/// caller-side config, not a tenant secret. Distinct from the deny
/// shape because the peer cannot derive ticket presence from it.
const RUN_RESUME_UNAVAILABLE_MESSAGE: &str = "resume unavailable";

/// JSON-RPC handler for `klieo/run/resume`. Every error branch
/// surfaces the sanitised stable string only (CWE-209); the internal
/// cause lives in the server log.
async fn handle_run_resume(
    server: Arc<McpServer>,
    raw: serde_json::Value,
    identity: Option<Identity>,
) -> Response {
    let req_id = raw.get("id").cloned();
    let parsed = match parse_run_resume_params(&raw, req_id.clone()) {
        Ok(p) => p,
        Err(resp) => return resp,
    };
    let claimed = match claim_resume_record(&server, &parsed.ticket, identity, req_id.clone()).await
    {
        Ok(rec) => rec,
        Err(resp) => return resp,
    };
    drive_resume(&server, parsed.decision, claimed, req_id).await
}

#[allow(clippy::result_large_err)]
fn parse_run_resume_params(
    raw: &serde_json::Value,
    req_id: Option<serde_json::Value>,
) -> Result<RunResumeParams, Response> {
    let Some(params_value) = raw.get("params").cloned() else {
        return Err(run_resume_invalid_params(req_id, "missing params"));
    };
    serde_json::from_value::<RunResumeParams>(params_value)
        .map_err(|_| run_resume_invalid_params(req_id, "invalid params"))
}

/// Run the lookup-then-authz-then-claim sequence. Authz runs BEFORE
/// the atomic claim so a foreign principal cannot ever consume
/// another caller's ticket; the same opaque deny string surfaces for
/// every failure branch so the peer cannot tell unknown from
/// foreign-owned.
#[allow(clippy::result_large_err)]
async fn claim_resume_record(
    server: &McpServer,
    ticket: &str,
    identity: Option<Identity>,
    req_id: Option<serde_json::Value>,
) -> Result<crate::resume_ticket::ResumeTicketRecord, Response> {
    let Some(store) = server.resume_ticket_store.as_ref() else {
        return Err(run_resume_unavailable(req_id));
    };
    let caller = identity
        .as_ref()
        .filter(|id| !id.is_anonymous())
        .ok_or_else(|| run_resume_denied(req_id.clone(), "anonymous caller"))?;

    let peeked = store
        .peek(ticket)
        .await
        .map_err(|err| log_and_deny(err, req_id.clone(), "peek failure"))?;
    let record = peeked.ok_or_else(|| run_resume_denied(req_id.clone(), "unknown ticket"))?;
    if caller.as_str() != record.principal {
        return Err(run_resume_denied(req_id, "principal mismatch"));
    }
    let claimed = store
        .claim(ticket)
        .await
        .map_err(|err| log_and_deny(err, req_id.clone(), "claim failure"))?;
    claimed.ok_or_else(|| run_resume_denied(req_id, "claim lost race"))
}

async fn drive_resume(
    server: &McpServer,
    decision: RunResumeDecision,
    record: crate::resume_ticket::ResumeTicketRecord,
    req_id: Option<serde_json::Value>,
) -> Response {
    let Some(handle) = server.workflow_resume_handles.get(&record.workflow_name) else {
        tracing::warn!(
            target: "klieo.mcp.resume",
            workflow = %record.workflow_name,
            "claimed ticket references an unregistered workflow",
        );
        return run_resume_unavailable(req_id);
    };
    let approval = if decision.approved {
        klieo_core::checkpoint::ApprovalDecision::Approved
    } else {
        klieo_core::checkpoint::ApprovalDecision::Rejected {
            reason: decision.reason.unwrap_or_default(),
        }
    };
    // Bind the resumed run to the ticket's principal (hashed, non-PII) so
    // the continuation is attributed + governed like the original call —
    // resume must not bypass the inbound per-tenant LLM budget.
    let tenant_label = klieo_core::principal_hash(&record.principal);
    match handle
        .resume(record.checkpoint, approval, tenant_label)
        .await
    {
        Ok(result) => (StatusCode::OK, Json(crate::rpc_ok(req_id, result))).into_response(),
        Err(err) => {
            tracing::warn!(
                target: "klieo.mcp.resume",
                workflow = %record.workflow_name,
                error = %err,
                "workflow resume failed",
            );
            run_resume_server_error(req_id)
        }
    }
}

fn log_and_deny(
    err: crate::resume_ticket::TicketStoreError,
    req_id: Option<serde_json::Value>,
    log_reason: &str,
) -> Response {
    tracing::warn!(
        target: "klieo.mcp.resume",
        rpc_id = ?req_id,
        error = %err,
        reason = log_reason,
        "resume ticket-store op failed; denying fail-closed",
    );
    run_resume_denied(req_id, log_reason)
}

fn run_resume_denied(id: Option<serde_json::Value>, log_reason: &str) -> Response {
    tracing::info!(
        target: "klieo.mcp.resume",
        rpc_id = ?id,
        reason = log_reason,
        "klieo/run/resume denied",
    );
    (
        StatusCode::OK,
        Json(rpc_error(id, JSONRPC_INVALID_PARAMS, RUN_RESUME_DENY_MESSAGE)),
    )
        .into_response()
}

fn run_resume_unavailable(id: Option<serde_json::Value>) -> Response {
    (
        StatusCode::OK,
        Json(rpc_error(
            id,
            JSONRPC_SERVER_ERROR,
            RUN_RESUME_UNAVAILABLE_MESSAGE,
        )),
    )
        .into_response()
}

fn run_resume_invalid_params(id: Option<serde_json::Value>, log_reason: &str) -> Response {
    tracing::warn!(
        target: "klieo.mcp.resume",
        rpc_id = ?id,
        reason = log_reason,
        "klieo/run/resume params invalid",
    );
    (
        StatusCode::BAD_REQUEST,
        Json(rpc_error(id, JSONRPC_INVALID_PARAMS, RUN_RESUME_DENY_MESSAGE)),
    )
        .into_response()
}

fn run_resume_server_error(id: Option<serde_json::Value>) -> Response {
    (
        StatusCode::OK,
        Json(rpc_error(id, JSONRPC_SERVER_ERROR, "resume execution failed")),
    )
        .into_response()
}

/// Cluster-0.23 helper: copy the W3C tracecontext headers from an
/// axum [`HeaderMap`] into a [`klieo_core::Headers`] bag so
/// [`klieo_core::extract_traceparent`] can lift the upstream
/// `opentelemetry::Context` and parent the entry span under it.
/// Only `traceparent` + `tracestate` are forwarded — everything else
/// stays on the inbound `HeaderMap` for the dispatch path.
fn klieo_headers_from_axum(headers: &HeaderMap) -> klieo_core::Headers {
    let mut out = klieo_core::Headers::default();
    if let Some(value) = headers.get("traceparent").and_then(|v| v.to_str().ok()) {
        out.insert("traceparent".into(), value.to_string());
    }
    if let Some(value) = headers.get("tracestate").and_then(|v| v.to_str().ok()) {
        out.insert("tracestate".into(), value.to_string());
    }
    out
}

fn content_type_is_json(headers: &HeaderMap) -> bool {
    headers
        .get(header::CONTENT_TYPE)
        .and_then(|v| v.to_str().ok())
        .map(|s| {
            s.split(';')
                .next()
                .unwrap_or("")
                .trim()
                .eq_ignore_ascii_case("application/json")
        })
        .unwrap_or(false)
}

/// Broadcast channel capacity: enough headroom for a burst of events
/// before the SSE loop drains them. Lagged receivers emit a single
/// synthetic `lagged` notification rather than hard-failing.
const PROGRESS_CHANNEL_CAP: usize = 64;

/// Stringify a `progressToken` JSON value for use as a `ResumeBuffer` stream id.
fn progress_token_to_string(token: &serde_json::Value) -> String {
    match token {
        serde_json::Value::String(s) => s.clone(),
        serde_json::Value::Number(n) => n.to_string(),
        other => other.to_string(),
    }
}

/// Prepend `id: {id}\n` to an existing SSE frame so reconnecting clients
/// can supply `Last-Event-ID`.
fn id_prefixed_frame(id: u64, frame_bytes: Bytes) -> Bytes {
    let mut prefixed = format!("id: {id}\n").into_bytes();
    prefixed.extend_from_slice(&frame_bytes);
    Bytes::from(prefixed)
}

/// Extract the `id: N` line from a raw SSE frame payload (as written by
/// `id_prefixed_frame`). Returns `None` if the prefix is missing or
/// the value is not a u64.
fn parse_id_prefix(bytes: &Bytes) -> Option<u64> {
    let text = std::str::from_utf8(bytes).ok()?;
    let id_line = text.lines().next()?;
    id_line.strip_prefix("id: ")?.parse::<u64>().ok()
}

/// Spawn a best-effort write-through to the resume buffer. A record
/// failure is logged but never propagates to the SSE caller. When
/// `close_after` is `true`, `buffer.close()` is called after the record
/// succeeds (or fails) so the stream is marked terminal.
fn spawn_record(
    buffer: Arc<dyn klieo_core::resume::ResumeBuffer>,
    stream_id: String,
    id: u64,
    payload: Bytes,
    close_after: bool,
) {
    tokio::spawn(async move {
        if let Err(e) = buffer.record(&stream_id, id, payload.clone()).await {
            tracing::warn!(
                target: "mcp.resume",
                stream_id,
                id,
                error = %e,
                "resume buffer record failed"
            );
        }
        if close_after {
            if let Err(e) = buffer.close(&stream_id).await {
                tracing::warn!(
                    target: "mcp.resume",
                    stream_id,
                    error = %e,
                    "resume buffer close failed"
                );
            }
        }
    });
}

/// Spawn a best-effort cross-replica publish of one SSE frame to the
/// per-progressToken bus subject, bounded by the server's shared
/// publish-concurrency semaphore. Saturation drops the publish + emits
/// a `warn`; cross-replica subscribers fall back to the resume buffer
/// for gap-fill on the next `klieo/tools/resume` request. Failures
/// inside the spawned task log + continue. Thin wrapper over
/// [`klieo_core::cancel::spawn_publish_bounded`] so the same
/// concurrency cap covers both this hot path and the drop-time cancel
/// publish in [`CancelOnDrop`].
fn spawn_publish(
    pubsub: Arc<dyn klieo_core::Pubsub>,
    subject: String,
    payload: Bytes,
    permits: Arc<tokio::sync::Semaphore>,
) {
    // Capture the publisher's OTEL context via the tracing →
    // opentelemetry bridge so the bus headers carry a W3C `traceparent`.
    // Subscribers on other replicas extract it and stitch their decode
    // span under this span (cluster 0.23, ADR-023).
    let mut trace_headers = klieo_core::Headers::default();
    klieo_core::inject_traceparent(&mut trace_headers, &tracing::Span::current().context());
    klieo_core::cancel::spawn_publish_bounded(
        pubsub,
        subject,
        payload,
        "mcp.fanout",
        permits,
        trace_headers,
    );
}

/// Wrap an SSE body stream with the cancel-fanout sandwich both
/// streaming paths require: `RegistryDeregisterOnDrop` to remove the
/// per-invoke cancel-registry entry when the stream ends, plus
/// `CancelOnDrop` to fire the request-scoped token and publish a
/// best-effort cross-replica cancel on body drop.
///
/// `leader_handle` is held inside `CancelOnDrop` for the lifetime of
/// the SSE body; on drop the held `klieo_core::LeaderHandle` releases
/// its KV claim so a follower's orphan probe observes a TTL-expired
/// entry (ADR-020). `None` when leader election is disabled.
///
/// `ownership_handle` is held inside `CancelOnDrop` for the lifetime
/// of the SSE body; on drop the held `klieo_core::OwnershipHandle`
/// fires a best-effort `kv.delete` so a follower's `lookup` no longer
/// returns the stale principal (ADR-022). `None` when tenant binding
/// is disabled, when the request is anonymous, or when the claim
/// itself failed.
///
/// Callers MUST have already registered `request_cancel` under
/// `stream_id` in `server.cancel_registry()`. The wrapper handles
/// deregistration on drop.
fn wrap_with_cancel_fanout<S>(
    server: &Arc<McpServer>,
    inner: S,
    stream_id: String,
    request_cancel: tokio_util::sync::CancellationToken,
    leader_handle: Option<klieo_core::LeaderHandle>,
    ownership_handle: Option<klieo_core::OwnershipHandle>,
) -> CancelOnDrop<klieo_core::cancel::RegistryDeregisterOnDrop<S>>
where
    S: Stream<Item = Result<Bytes, std::convert::Infallible>> + Send + Unpin + 'static,
{
    let cancel_subject = CANCEL_SUBJECT_PREFIX.to_string() + &stream_id;
    let deregistered = klieo_core::cancel::RegistryDeregisterOnDrop::new(
        inner,
        server.cancel_registry().clone(),
        stream_id,
    );
    CancelOnDrop {
        inner: deregistered,
        _guard: request_cancel.drop_guard(),
        pubsub: server.pubsub.clone(),
        cancel_subject,
        permits: server.publish_permits.clone(),
        _leader: leader_handle,
        _ownership: ownership_handle,
    }
}

/// Best-effort leader claim for a streaming invoke. Returns `None`
/// when no registry is wired (single-replica deployment) OR when the
/// KV `put` fails (fail-open per ADR-020). The returned
/// `LeaderHandle` MUST be held for the lifetime of the SSE response;
/// `CancelOnDrop::_leader` carries it to drop-time so the KV entry
/// is released and a follower's orphan probe observes TTL expiry on
/// replica failure.
///
/// `payload` carries the original JSON-RPC request body serialised
/// to bytes so a follower that detects an orphan can re-invoke an
/// idempotent tool from the cached payload (cluster 0.24).
/// `principal` records the authenticated subject (cluster 0.22) so
/// the re-invoke runs under the same tenant binding as the original.
async fn try_claim_leader(
    server: &Arc<McpServer>,
    stream_id: &str,
    payload: Option<Bytes>,
    principal: Option<String>,
) -> Option<klieo_core::LeaderHandle> {
    let registry = server.leader_registry()?;
    let key = format!("{MCP_LEADER_KEY_PREFIX}{stream_id}");
    match registry
        .claim_with_heartbeat(
            key,
            server.leader_ttl(),
            server.leader_heartbeat_interval(),
            payload,
            principal,
        )
        .await
    {
        Ok(handle) => Some(handle),
        Err(e) => {
            tracing::warn!(
                target: "mcp.leader",
                stream_id = %stream_id,
                error = %e,
                "leader claim failed; degrading to no-claim (orphan detection \
                 disabled for this stream)",
            );
            None
        }
    }
}

/// Tenant-binding claim for a streaming invoke. Returns `Ok(None)` (proceed,
/// no claim) when no `OwnershipRegistry` is wired or the caller is
/// unauthenticated/anonymous. On KV `put` failure a lenient registry returns
/// `Ok(None)` (fail-open per ADR-022), while a **strict** registry returns
/// `Err(Response)` so the invoke is denied rather than started unprotected. The
/// returned `OwnershipHandle` MUST be held for the lifetime of the SSE response;
/// `CancelOnDrop::_ownership` carries it to drop-time so the entry is removed on
/// stream end.
async fn try_claim_ownership(
    server: &Arc<McpServer>,
    stream_id: &str,
    identity: &Option<Identity>,
) -> Result<Option<klieo_core::OwnershipHandle>, Response> {
    let Some(registry) = server.ownership_registry() else {
        return Ok(None);
    };
    let Some(identity) = identity.as_ref() else {
        return Ok(None);
    };
    if identity.is_anonymous() {
        return Ok(None);
    }
    let key = format!("{MCP_OWNERSHIP_KEY_PREFIX}{stream_id}");
    let principal = identity.as_str().to_string();
    match registry.claim_guarded(key, principal).await {
        klieo_core::OwnershipClaim::Claimed(handle) => Ok(Some(handle)),
        klieo_core::OwnershipClaim::Proceed => Ok(None),
        klieo_core::OwnershipClaim::Unavailable => {
            Err(stream_unavailable_response(serde_json::Value::Null))
        }
        // Non_exhaustive: an unrecognised future outcome denies (fail-closed).
        _ => Err(stream_unavailable_response(serde_json::Value::Null)),
    }
}

/// `klieo/tools/resume` tenant-binding gate. Looks up the owner of
/// `stream_id` in the `klieo-tenants` bucket and matches against the
/// caller's principal.
///
/// - Owner match → `Ok(())` (proceed).
/// - Owner mismatch → `Err(stream_not_found_response)` — deny-as-
///   NotFound per OWASP IDOR best practice; same wire shape as a
///   nonexistent progressToken so the response leaks no existence
///   info.
/// - No registry / no caller / anonymous caller → `Ok(())`
///   (partial-deployment skip, ADR-022).
/// - Missing entry (`Ok(None)`) → `Ok(())` (legacy pre-0.22 stream
///   or no auth wired at invoke).
/// - KV lookup error → `Ok(())` (fail-open; same posture as the
///   leader is_alive probe in ADR-020).
async fn enforce_owner(
    server: &Arc<McpServer>,
    stream_id: &str,
    identity: &Option<Identity>,
    req_id: &serde_json::Value,
) -> Result<(), Response> {
    let Some(registry) = server.ownership_registry() else {
        return Ok(());
    };
    let Some(identity) = identity.as_ref() else {
        return Ok(());
    };
    if identity.is_anonymous() {
        return Ok(());
    }
    let key = format!("{MCP_OWNERSHIP_KEY_PREFIX}{stream_id}");
    match registry.check_owner(&key, identity.as_str()).await {
        klieo_core::OwnershipCheck::Allowed => Ok(()),
        klieo_core::OwnershipCheck::Denied => {
            tracing::warn!(
                target: "mcp.tenants",
                stream_id = %stream_id,
                principal = %identity.as_str(),
                "ownership mismatch on klieo/tools/resume; denying as stream-not-found",
            );
            Err(stream_not_found_response(req_id.clone()))
        }
        // Strict mode, store unreachable: `check_owner` already logged the
        // cause; deny rather than risk a cross-tenant resume.
        klieo_core::OwnershipCheck::Unavailable => Err(stream_unavailable_response(req_id.clone())),
        // Non_exhaustive: an unrecognised future verdict denies (fail-closed).
        _ => Err(stream_unavailable_response(req_id.clone())),
    }
}

/// Build the JSON-RPC envelope the resume gate returns on owner
/// mismatch. Wire-shape MUST match the `ResumeError::NotFound` arm
/// in [`stream_resume`] byte-for-byte (modulo request id) so the
/// response is indistinguishable from a request for a nonexistent
/// progressToken — IDOR mitigation per OWASP.
fn stream_not_found_response(req_id: serde_json::Value) -> Response {
    (
        StatusCode::OK,
        Json(rpc_error(
            Some(req_id),
            crate::JSONRPC_RESUME_BUFFER_NOT_FOUND,
            "no buffered stream for progressToken",
        )),
    )
        .into_response()
}

/// Build the envelope returned when **strict** tenant binding cannot reach the
/// ownership store. 503 + `JSONRPC_SERVER_ERROR` — a retryable infrastructure
/// failure, deliberately distinct from the leak-safe not-found used on an owner
/// mismatch: the gate fails closed rather than risk a cross-tenant resume.
fn stream_unavailable_response(req_id: serde_json::Value) -> Response {
    (
        StatusCode::SERVICE_UNAVAILABLE,
        Json(rpc_error(
            Some(req_id),
            crate::JSONRPC_SERVER_ERROR,
            "ownership store unavailable; denied (strict tenant binding)",
        )),
    )
        .into_response()
}

/// Outcome of a leader-alive probe at `stream_resume` entry.
enum LeaderProbe {
    /// No registry wired — single-replica deployment, orphan detection skipped.
    NoRegistry,
    /// Probe returned `Ok(true)` OR the KV errored (fail-open per ADR-020).
    Alive,
    /// Probe returned `Ok(false)` — the leader's claim has lapsed or never existed.
    Dead,
}

/// Best-effort leader-alive probe for a `stream_resume` entry.
///
/// Returns `LeaderProbe::NoRegistry` when leader election is not
/// wired; otherwise probes the KV. `Err(_)` from the registry
/// fails open (treat as alive) per ADR-020: a transient KV blip
/// must NOT trip an orphan write that would terminate a live
/// stream prematurely.
async fn probe_leader(server: &Arc<McpServer>, stream_id: &str) -> LeaderProbe {
    let Some(registry) = server.leader_registry() else {
        return LeaderProbe::NoRegistry;
    };
    let key = format!("{MCP_LEADER_KEY_PREFIX}{stream_id}");
    match registry.is_alive(&key).await {
        Ok(true) => LeaderProbe::Alive,
        Ok(false) => LeaderProbe::Dead,
        Err(e) => {
            tracing::warn!(
                target: "mcp.leader",
                stream_id = %stream_id,
                error = %e,
                "is_alive probe failed; treating as alive (fail-open per ADR-020)",
            );
            LeaderProbe::Alive
        }
    }
}

/// Probe a [`klieo_core::resume::ResumeBuffer`] for the highest
/// retained event id. Returns `None` when the buffer has no
/// retained events for `stream_id` (`NotFound`) OR when the
/// backend errors (best-effort: log warn + skip orphan write).
async fn max_event_id(
    buffer: &Arc<dyn klieo_core::resume::ResumeBuffer>,
    stream_id: &str,
) -> Option<u64> {
    let mut replay = match buffer.replay(stream_id, 0).await {
        Ok(stream) => stream,
        Err(klieo_core::resume::ResumeError::NotFound(_)) => return None,
        Err(e) => {
            tracing::warn!(
                target: "mcp.leader",
                stream_id = %stream_id,
                error = %e,
                "max_event_id replay failed; skipping orphan terminal write",
            );
            return None;
        }
    };
    let mut highest: Option<u64> = None;
    while let Some((id, _)) = tokio_stream::StreamExt::next(&mut replay).await {
        highest = Some(match highest {
            Some(current) => current.max(id),
            None => id,
        });
    }
    highest
}

/// JSON-RPC error envelope for the LEADER_DIED single-shot
/// response returned from `stream_resume` on orphan detection.
/// Carries `data.stream_id` so the client can correlate the orphan
/// signal with operator-side bus telemetry. Mirrors A2A's
/// `leader_died_envelope`. ADR-020.
fn leader_died_envelope(id: serde_json::Value, stream_id: &str) -> serde_json::Value {
    serde_json::json!({
        "jsonrpc": "2.0",
        "id": id,
        "error": {
            "code": JSONRPC_LEADER_DIED,
            "message": "stream leader died",
            "data": { "stream_id": stream_id },
        }
    })
}

/// Build the terminal SSE-frame bytes recorded in the resume buffer
/// at `max_id + 1` when an orphan is detected on `stream_resume`.
/// Replay restamps with `id_prefixed_frame` on read, so the stored
/// payload is the bare `event: error\ndata: {...}\n\n` SSE block.
fn leader_died_sse_frame_bytes(stream_id: &str) -> Bytes {
    let envelope = serde_json::json!({
        "jsonrpc": "2.0",
        "id": serde_json::Value::Null,
        "error": {
            "code": JSONRPC_LEADER_DIED,
            "message": "stream leader died",
            "data": { "stream_id": stream_id },
        }
    });
    Bytes::from(format!("event: error\ndata: {}\n\n", envelope))
}

/// Orphan recovery: on a dead leader probe, write a terminal
/// "leader died" SSE frame at `max_id + 1` to the resume buffer and
/// mark the buffer terminal. Future resume clients replaying past
/// `max_id` see the synthetic frame and close.
///
/// Returns `true` when the orphan write landed (caller raises the
/// single-shot JSON-RPC `LEADER_DIED` envelope); `false` when:
/// - The buffer has no retained events (leader never claimed +
///   never wrote → not an orphan, just a non-streaming client).
///   Caller falls through to the regular replay path.
/// - The terminal-frame `record` failed (best-effort: log warn +
///   fall through to the regular subscribe path so a transient
///   KV blip does not surface as a hard-fail to the client).
async fn write_orphan_terminal_frame(
    buffer: &Arc<dyn klieo_core::resume::ResumeBuffer>,
    stream_id: &str,
) -> bool {
    let Some(max_id) = max_event_id(buffer, stream_id).await else {
        return false;
    };
    let next_id = max_id + 1;
    let frame = leader_died_sse_frame_bytes(stream_id);
    if let Err(e) = buffer.record(stream_id, next_id, frame).await {
        tracing::warn!(
            target: "mcp.leader",
            stream_id = %stream_id,
            next_id,
            error = %e,
            "orphan terminal record failed; skipping orphan write",
        );
        return false;
    }
    if let Err(e) = buffer.close(stream_id).await {
        tracing::warn!(
            target: "mcp.leader",
            stream_id = %stream_id,
            error = %e,
            "orphan terminal close failed; resume buffer may retain stale stream",
        );
    }
    tracing::error!(
        target: "mcp.leader",
        stream_id = %stream_id,
        next_id,
        "stream leader died; emitted LEADER_DIED terminal frame at max+1",
    );
    true
}

/// Terminate-only orphan response (cluster-0.20 path). Writes the
/// "leader died" SSE frame to the resume buffer at `max + 1` + marks
/// the buffer terminal, then returns the single-shot JSON-RPC
/// `LEADER_DIED` (-32099) envelope. When the resume buffer has no
/// retained events the orphan write is skipped (not an orphan, just
/// a no-stream resume client) and the caller falls through to the
/// regular replay path; the [`OrphanOutcome::Passthrough`] variant
/// signals that fall-through.
async fn terminate_orphan_mcp(
    buffer: &Arc<dyn klieo_core::resume::ResumeBuffer>,
    req_id: &serde_json::Value,
    stream_id: &str,
) -> OrphanOutcome {
    if write_orphan_terminal_frame(buffer, stream_id).await {
        let resp = (
            StatusCode::OK,
            Json(leader_died_envelope(req_id.clone(), stream_id)),
        )
            .into_response();
        return OrphanOutcome::Terminated(resp);
    }
    OrphanOutcome::Passthrough
}

/// Outcome of the cluster-0.24 follower-side orphan gate.
///
/// - [`OrphanOutcome::Reinvoked`] — the gate CAS-claimed a new leader
///   entry with `attempt + 1` and is driving a fresh `tools/call`
///   stream from the cached payload. The carried [`Response`] is the
///   SSE stream the resume client should consume.
/// - [`OrphanOutcome::Terminated`] — cluster-0.20 fall-back fired
///   (handler not idempotent, attempt cap reached, no cached payload,
///   CAS conflict, or no resume-buffer events to anchor on). The
///   carried [`Response`] is the single-shot LEADER_DIED envelope.
/// - [`OrphanOutcome::Passthrough`] — no leader registry wired OR
///   the orphan write found no buffer entries. Caller falls through
///   to the regular replay path.
#[non_exhaustive]
pub enum OrphanOutcome {
    /// Follower CAS-claimed a fresh leader entry and is driving a new
    /// `tools/call` stream; the carried response is the SSE stream
    /// the resume client should consume.
    Reinvoked(Response),
    /// Cluster-0.20 fall-back fired (handler not idempotent, attempt
    /// cap reached, no cached payload, CAS conflict, or no
    /// resume-buffer events). The carried response is the single-shot
    /// LEADER_DIED envelope.
    Terminated(Response),
    /// No leader registry wired or the orphan write found no buffer
    /// entries; caller falls through to the regular replay path.
    Passthrough,
}

/// Cluster-0.24 follower-side response to a dead-leader probe on
/// `klieo/tools/resume`.
///
/// Branches on the cached [`klieo_core::LeaderEntry`]:
/// 1. No registry wired → [`OrphanOutcome::Passthrough`].
/// 2. Lookup yields no entry / KV error → terminate-only.
/// 3. Cached payload missing / unparseable → terminate-only.
/// 4. `tool_invoker.is_tool_idempotent(name) == false` → terminate-
///    only.
/// 5. `entry.attempt >= FAILOVER_ATTEMPT_CAP` → terminate-only.
/// 6. CAS-claim with `attempt + 1` succeeds → record a
///    `failover-reinvoke` marker frame at `max + 1`, fabricate an
///    [`Identity`] from the cached principal, and drive a fresh
///    `tools/call` invocation via `run_tools_call` (private helper) with the new
///    handle adopted as `existing_leader`. The re-invoke's events
///    append to the existing resume buffer at `max + 2` onwards.
/// 7. CAS conflict (another follower won) / CAS error → terminate-
///    only.
///
/// `pub` under `test-fixtures` so integration tests can drive the
/// gate directly with a pre-seeded `LeaderEntry` in the KV bucket —
/// the production path's `is_alive` probe and
/// `lookup_entry_with_revision` both go through `kv.get`, so any HTTP-
/// driven test that mocks "dead leader" via `kv.delete` collapses the
/// entry visibility for the lookup too. Same shape as A2A's
/// `handle_dead_leader_orphan`.
#[cfg(feature = "test-fixtures")]
pub async fn handle_dead_leader_orphan_mcp(
    server: &Arc<McpServer>,
    buffer: &Arc<dyn klieo_core::resume::ResumeBuffer>,
    req_id: &serde_json::Value,
    stream_id: &str,
) -> OrphanOutcome {
    handle_dead_leader_orphan_mcp_impl(server, buffer, req_id, stream_id).await
}

#[cfg(not(feature = "test-fixtures"))]
async fn handle_dead_leader_orphan_mcp(
    server: &Arc<McpServer>,
    buffer: &Arc<dyn klieo_core::resume::ResumeBuffer>,
    req_id: &serde_json::Value,
    stream_id: &str,
) -> OrphanOutcome {
    handle_dead_leader_orphan_mcp_impl(server, buffer, req_id, stream_id).await
}

async fn handle_dead_leader_orphan_mcp_impl(
    server: &Arc<McpServer>,
    buffer: &Arc<dyn klieo_core::resume::ResumeBuffer>,
    req_id: &serde_json::Value,
    stream_id: &str,
) -> OrphanOutcome {
    let Some(registry) = server.leader_registry() else {
        return OrphanOutcome::Passthrough;
    };
    let key = format!("{MCP_LEADER_KEY_PREFIX}{stream_id}");
    let lookup = registry.lookup_entry_with_revision(&key).await;
    let Some((entry, prior_rev)) = lookup_ok_or_log_mcp(&key, lookup) else {
        return terminate_orphan_mcp(buffer, req_id, stream_id).await;
    };
    let Some(payload_bytes) = entry.payload.clone() else {
        tracing::debug!(
            target: "mcp.failover",
            stream_id = %stream_id,
            "no cached payload on leader entry; emitting terminate frame",
        );
        return terminate_orphan_mcp(buffer, req_id, stream_id).await;
    };
    let parsed_body: serde_json::Value = match serde_json::from_slice(&payload_bytes) {
        Ok(v) => v,
        Err(e) => {
            tracing::error!(
                target: "mcp.failover",
                stream_id = %stream_id,
                error = %e,
                "cached payload parse failed; emitting terminate frame",
            );
            return terminate_orphan_mcp(buffer, req_id, stream_id).await;
        }
    };
    let tool_name = parsed_body
        .pointer("/params/name")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    if !server.invoker.is_tool_idempotent(tool_name) {
        tracing::debug!(
            target: "mcp.failover",
            stream_id = %stream_id,
            tool = %tool_name,
            "tool not idempotent; emitting terminate frame",
        );
        return terminate_orphan_mcp(buffer, req_id, stream_id).await;
    }
    if entry.attempt >= server.max_failover_attempts() {
        tracing::warn!(
            target: "mcp.failover",
            stream_id = %stream_id,
            attempt = entry.attempt,
            cap = server.max_failover_attempts(),
            "failover attempt cap reached; emitting terminate frame",
        );
        return terminate_orphan_mcp(buffer, req_id, stream_id).await;
    }
    let new_handle = match registry
        .claim_with_attempt_cas_and_heartbeat(
            key.clone(),
            server.leader_ttl(),
            server.leader_heartbeat_interval(),
            prior_rev,
            &entry,
        )
        .await
    {
        Ok(h) => h,
        Err(klieo_core::BusError::CasConflict { .. }) => {
            tracing::info!(
                target: "mcp.failover",
                stream_id = %stream_id,
                "another follower won the CAS race; emitting terminate frame",
            );
            return terminate_orphan_mcp(buffer, req_id, stream_id).await;
        }
        Err(e) => {
            tracing::warn!(
                target: "mcp.failover",
                stream_id = %stream_id,
                error = %e,
                "CAS claim failed; emitting terminate frame",
            );
            return terminate_orphan_mcp(buffer, req_id, stream_id).await;
        }
    };
    record_failover_marker_mcp(buffer, stream_id, &entry, &new_handle).await;
    let progress_token = parsed_body
        .pointer("/params/_meta/progressToken")
        .cloned()
        .unwrap_or(serde_json::Value::Null);
    let reinvoke_identity = entry.principal.as_ref().map(|p| Identity::new(p.clone()));
    let resp = run_tools_call(
        server.clone(),
        parsed_body,
        progress_token,
        reinvoke_identity,
        Some(new_handle),
    )
    .await;
    OrphanOutcome::Reinvoked(resp)
}

/// Unwrap a `lookup_entry_with_revision` result, logging KV-layer
/// errors at `warn` before falling back to terminate. Returns
/// `Some((entry, rev))` only on `Ok(Some(_))`. Mirrors A2A's
/// `lookup_ok_or_log`.
fn lookup_ok_or_log_mcp(
    key: &str,
    lookup: Result<Option<(klieo_core::LeaderEntry, klieo_core::Revision)>, klieo_core::BusError>,
) -> Option<(klieo_core::LeaderEntry, klieo_core::Revision)> {
    match lookup {
        Ok(Some(pair)) => Some(pair),
        Ok(None) => None,
        Err(e) => {
            tracing::warn!(
                target: "mcp.failover",
                key,
                error = %e,
                "leader entry lookup_with_revision failed; falling back to terminate",
            );
            None
        }
    }
}

/// Write the cluster-0.24 `failover-reinvoke` marker frame to the
/// resume buffer at `max + 1` so resume clients see a clear boundary
/// between the dead leader's last event and the re-invoke's fresh
/// sequence (which appends at `max + 2` onwards). Best-effort: a
/// record failure logs a `warn` + continues so the re-invoke still
/// drives the production stream.
async fn record_failover_marker_mcp(
    buffer: &Arc<dyn klieo_core::resume::ResumeBuffer>,
    stream_id: &str,
    prior: &klieo_core::LeaderEntry,
    new_handle: &klieo_core::LeaderHandle,
) {
    let Some(max) = max_event_id(buffer, stream_id).await else {
        return;
    };
    let marker_id = max + 1;
    let frame = failover_reinvoke_sse_frame_bytes_mcp(
        stream_id,
        marker_id,
        prior.attempt + 1,
        new_handle.replica_id(),
    );
    if let Err(e) = buffer.record(stream_id, marker_id, frame).await {
        tracing::warn!(
            target: "mcp.failover",
            stream_id = %stream_id,
            marker_id,
            error = %e,
            "failover-reinvoke marker record failed; continuing without marker",
        );
    }
}

/// Build the cluster-0.24 `failover-reinvoke` SSE marker frame
/// recorded in the resume buffer at `max + 1` when a follower
/// re-invokes an idempotent tool from the cached payload. The
/// re-invoke's own events append at `max + 2` onwards via
/// [`emit_progress_frame`], so resume clients see the marker between
/// the original leader's last event and the re-invoke's fresh
/// sequence. Mirrors A2A's `failover_reinvoke_sse_frame_bytes`.
fn failover_reinvoke_sse_frame_bytes_mcp(
    stream_id: &str,
    event_id: u64,
    attempt: u32,
    new_replica_id: &str,
) -> Bytes {
    let payload = serde_json::json!({
        "jsonrpc": "2.0",
        "id": serde_json::Value::Null,
        "event": "failover-reinvoke",
        "data": {
            "stream_id": format!("{MCP_LEADER_KEY_PREFIX}{stream_id}"),
            "attempt": attempt,
            "by_replica": new_replica_id,
        },
        "event_id": event_id,
    });
    Bytes::from(serde_json::to_vec(&payload).unwrap_or_default())
}

/// Combine the resume buffer's `replay` stream with an optional live
/// bus tail into one `Result<Bytes, Infallible>` stream of SSE frames.
///
/// `max_replayed` tracks the highest id observed during replay so the
/// tail-side `filter_map` can drop frames already delivered by replay
/// (preserves monotonic ordering across the boundary). Tail frames
/// missing a parseable `id:` prefix are warn-logged and dropped.
fn combine_replay_and_tail(
    replay: Pin<Box<dyn Stream<Item = (u64, Bytes)> + Send>>,
    live_tail: Option<klieo_core::MsgStream>,
    max_replayed: Arc<AtomicU64>,
    stream_id: String,
) -> Pin<Box<dyn Stream<Item = Result<Bytes, std::convert::Infallible>> + Send>> {
    let max_for_replay = max_replayed.clone();
    let replay = replay.map(move |(id, payload)| {
        max_for_replay.fetch_max(id, std::sync::atomic::Ordering::SeqCst);
        Ok::<_, std::convert::Infallible>(id_prefixed_frame(id, payload))
    });
    let Some(tail_msgs) = live_tail else {
        return replay.boxed();
    };
    let max_for_tail = max_replayed;
    let stream_id_for_log = stream_id;
    let tail = tail_msgs.filter_map(move |msg_result| {
        let stream_id = stream_id_for_log.clone();
        let max_for_tail = max_for_tail.clone();
        async move {
            let msg = match msg_result {
                Ok(m) => m,
                Err(e) => {
                    tracing::warn!(
                        target: "mcp.fanout",
                        stream_id = %stream_id,
                        error = %e,
                        "live tail subscription stream error; skipping"
                    );
                    return None;
                }
            };
            // Extract W3C tracecontext from bus headers and parent the
            // decode span under the publisher's span so cross-replica
            // traces stitch into one tree (cluster 0.23, ADR-023).
            let parent_cx = klieo_core::extract_traceparent(&msg.headers);
            let decode_span = tracing::info_span!(
                "tail_frame_decode",
                messaging.system = "klieo-bus",
                messaging.destination = %format!("klieo.mcp.progress.{stream_id}"),
                messaging.operation = "receive",
                klieo.stream_id = %stream_id,
            );
            decode_span.set_parent(parent_cx);
            let _enter = decode_span.enter();
            let payload = msg.payload.clone();
            if let Err(e) = msg.ack.ack().await {
                tracing::warn!(
                    target: "mcp.fanout",
                    error = %e,
                    "ack failed; ephemeral consumer continues"
                );
            }
            match parse_id_prefix(&payload) {
                Some(id) if id > max_for_tail.load(std::sync::atomic::Ordering::SeqCst) => {
                    Some(Ok::<_, std::convert::Infallible>(payload))
                }
                Some(_) => None,
                None => {
                    tracing::warn!(
                        target: "mcp.fanout",
                        payload_len = payload.len(),
                        "tail frame missing or unparseable id prefix; dropping",
                    );
                    None
                }
            }
        }
    });
    replay.chain(tail).boxed()
}

/// Stamp one progress/lagged/result frame with the next monotonic
/// `id:` prefix, spawn the best-effort resume-buffer record + bus
/// publish, and return the stamped frame for the SSE yield. Collapses
/// the inline 6-line block repeated 9 times in `stream_tools_call`.
///
/// Frame routing preserves the pre-refactor split: the resume buffer
/// stores the UNSTAMPED frame (replay restamps via
/// `id_prefixed_frame` on read), while the cross-replica publish + the
/// SSE yield carry the STAMPED bytes.
#[allow(clippy::too_many_arguments)]
fn emit_progress_frame(
    buffer: &Arc<dyn klieo_core::resume::ResumeBuffer>,
    pubsub: &Arc<dyn klieo_core::Pubsub>,
    permits: &Arc<tokio::sync::Semaphore>,
    publish_subject: &str,
    stream_id: &str,
    next_id: &AtomicU64,
    frame: Bytes,
    terminal: bool,
) -> Bytes {
    let id = next_id.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
    spawn_record(
        buffer.clone(),
        stream_id.to_string(),
        id,
        frame.clone(),
        terminal,
    );
    let stamped = id_prefixed_frame(id, frame);
    spawn_publish(
        pubsub.clone(),
        publish_subject.to_string(),
        stamped.clone(),
        permits.clone(),
    );
    stamped
}

/// Lower bound on a cross-hop provenance anchor — short enough to admit a
/// truncated hash, long enough to reject stray single characters.
const MIN_PARENT_ANCHOR_BYTES: usize = 8;
/// Upper bound — a hash token, not a payload. Caps the audit-trail string
/// a caller can write per run.
const MAX_PARENT_ANCHOR_BYTES: usize = 256;

/// `true` for the hash-token charset accepted in a parent-chain anchor:
/// base64url (`-`/`_`), hex, `=` padding, and `:` algorithm namespacing
/// (`sha256:…`). Excludes whitespace, control chars, and `@`/`.` so most
/// freeform/PII strings are rejected at the boundary.
fn is_parent_anchor_byte(byte: u8) -> bool {
    byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'=' | b':' | b'-')
}

/// Validate the optional cross-hop provenance anchor at `params._meta.
/// parentAnchor`. Absent → `Ok(None)`. Present but malformed →
/// `Err(stable message)`: a caller that supplied the field asked for a
/// cross-hop link, so silently dropping it would leave an invisible gap
/// in the audit chain — reject loud instead. Validation is generous; a
/// conformant hash token never trips it.
fn parse_parent_anchor(raw: &serde_json::Value) -> Result<Option<String>, &'static str> {
    let Some(value) = raw.pointer("/params/_meta/parentAnchor") else {
        return Ok(None);
    };
    let anchor = value
        .as_str()
        .ok_or("_meta.parentAnchor must be a string")?;
    if anchor.len() < MIN_PARENT_ANCHOR_BYTES || anchor.len() > MAX_PARENT_ANCHOR_BYTES {
        return Err("_meta.parentAnchor length out of bounds");
    }
    if !anchor.bytes().all(is_parent_anchor_byte) {
        return Err("_meta.parentAnchor must be a hash token");
    }
    Ok(Some(anchor.to_string()))
}

#[cfg(test)]
mod parent_anchor_tests {
    use super::parse_parent_anchor;
    use serde_json::json;

    fn req_with_anchor(anchor: serde_json::Value) -> serde_json::Value {
        json!({ "params": { "name": "t", "_meta": { "parentAnchor": anchor } } })
    }

    #[test]
    fn absent_anchor_is_ok_none() {
        let req = json!({ "params": { "name": "t" } });
        assert_eq!(parse_parent_anchor(&req), Ok(None));
        // Even an empty `_meta` object yields None.
        let req = json!({ "params": { "name": "t", "_meta": {} } });
        assert_eq!(parse_parent_anchor(&req), Ok(None));
    }

    #[test]
    fn valid_hash_token_is_accepted_verbatim() {
        let req = req_with_anchor(json!("sha256:0123abcd_ef-ABCD="));
        assert_eq!(
            parse_parent_anchor(&req),
            Ok(Some("sha256:0123abcd_ef-ABCD=".to_string()))
        );
    }

    #[test]
    fn non_string_anchor_is_rejected() {
        assert!(parse_parent_anchor(&req_with_anchor(json!(42))).is_err());
        assert!(parse_parent_anchor(&req_with_anchor(json!(["a"]))).is_err());
    }

    #[test]
    fn empty_or_short_anchor_is_rejected() {
        assert!(parse_parent_anchor(&req_with_anchor(json!(""))).is_err());
        assert!(parse_parent_anchor(&req_with_anchor(json!("abc"))).is_err());
    }

    #[test]
    fn oversize_anchor_is_rejected() {
        let huge = "a".repeat(257);
        assert!(parse_parent_anchor(&req_with_anchor(json!(huge))).is_err());
    }

    #[test]
    fn freeform_or_pii_shaped_anchor_is_rejected() {
        // An email (`@`, `.`) and whitespace are outside the hash-token
        // charset, so most freeform/PII strings fail at the boundary.
        assert!(parse_parent_anchor(&req_with_anchor(json!("alice@example.com"))).is_err());
        assert!(parse_parent_anchor(&req_with_anchor(json!("hello world"))).is_err());
    }
}

/// Extract params and spawn the invoke task for SSE-upgrade `tools/call`.
/// Returns the request ID, broadcast channel, and task handle.
///
/// `parent_anchor` is the validated cross-hop provenance anchor; it is
/// honored only for an authenticated (non-anonymous) caller so every
/// recorded `Episode::RunOrigin` is co-attributable to a principal.
fn spawn_progress_stream_task(
    server: &Arc<McpServer>,
    raw: &serde_json::Value,
    cancel: tokio_util::sync::CancellationToken,
    identity: Option<&Identity>,
    parent_anchor: Option<String>,
) -> (
    serde_json::Value,
    tokio::sync::broadcast::Receiver<klieo_core::AgentEvent>,
    tokio::task::JoinHandle<Result<serde_json::Value, klieo_core::error::ToolError>>,
) {
    let req_id = raw.get("id").cloned().unwrap_or(serde_json::Value::Null);
    let params = raw
        .get("params")
        .cloned()
        .unwrap_or(serde_json::Value::Null);

    let name = params
        .get("name")
        .and_then(|n| n.as_str())
        .unwrap_or("")
        .to_string();
    let args = params
        .get("arguments")
        .cloned()
        .unwrap_or(serde_json::Value::Null);

    let (tx, rx) = tokio::sync::broadcast::channel::<klieo_core::AgentEvent>(PROGRESS_CHANNEL_CAP);
    // Anonymous identities are excluded so the workflow's authz path
    // never binds a ticket to the "anonymous" principal — a deny-by-
    // default the slice-1 no-ticket envelope already covers.
    let principal = identity
        .filter(|id| !id.is_anonymous())
        .map(|id| id.as_str().to_string());
    // Cross-hop anchor honored only for authenticated callers: an
    // anonymous caller has no principal to attribute the (unverified)
    // parent claim to, so its anchor is dropped rather than recorded
    // as an orphan `RunOrigin`.
    let parent_anchor = if principal.is_some() {
        parent_anchor
    } else {
        None
    };
    let tool_ctx = server.tool_ctx_with_progress(tx, cancel, principal, parent_anchor);

    let invoker = server.invoker.clone();
    let invoke_handle = tokio::spawn(async move { invoker.invoke(&name, args, tool_ctx).await });

    (req_id, rx, invoke_handle)
}

/// Replay buffered events for `params.progress_token` since
/// `params.last_event_id`, then tail live events published to
/// `klieo.mcp.progress.{token}` so cross-replica clients see events
/// emitted on other replicas.
///
/// Ordering guarantee: subscribe-before-replay — the bus subscription
/// is established before the replay stream is consumed, so events
/// published during the replay drain are not lost.
///
/// Error mapping:
/// - `ResumeError::Expired`  → JSON-RPC -32011.
/// - `ResumeError::NotFound` → JSON-RPC -32012.
/// - `ResumeError::Backend`  → JSON-RPC -32603 (logged server-side only).
/// - Subscribe failure       → replay-only (logged warning).
#[instrument(
    skip_all,
    fields(
        rpc.system = "klieo-mcp",
        rpc.method = "klieo/tools/resume",
        klieo.stream_id = tracing::field::Empty,
    ),
)]
async fn stream_resume(
    server: Arc<McpServer>,
    raw: serde_json::Value,
    params: ResumeParams,
    identity: Option<Identity>,
) -> Response {
    let req_id = raw.get("id").cloned().unwrap_or(serde_json::Value::Null);
    let stream_id = progress_token_to_string(&params.progress_token);
    if let Err(e) = klieo_core::validate_subject_token(&stream_id) {
        tracing::warn!(
            target: "mcp.resume",
            error = %e,
            "rejected progressToken: invalid subject segment",
        );
        return (
            StatusCode::OK,
            Json(rpc_error(
                Some(req_id),
                JSONRPC_INVALID_PARAMS,
                "progressToken contains reserved bus-subject metacharacters",
            )),
        )
            .into_response();
    }
    tracing::Span::current().record("klieo.stream_id", stream_id.as_str());
    let request_cancel = server.parent_cancel.child_token();
    let buffer = server.resume_buffer.clone();
    let pubsub = server.pubsub.clone();
    let since = params.last_event_id;

    // Orphan detection: leader probe at the resume entry. When the
    // leader is dead AND the resume buffer has retained events (the
    // leader must have written some before dying), the follower
    // either re-invokes from the cached payload (cluster 0.24,
    // idempotent tool + attempt cap + payload available) OR writes
    // the terminal "leader died" SSE frame and returns a single-shot
    // JSON-RPC error envelope (code -32099) so the client sees clean
    // termination + can retry. ADR-020 / ADR-024.
    if let LeaderProbe::Dead = probe_leader(&server, &stream_id).await {
        match handle_dead_leader_orphan_mcp(&server, &buffer, &req_id, &stream_id).await {
            OrphanOutcome::Reinvoked(resp) | OrphanOutcome::Terminated(resp) => return resp,
            OrphanOutcome::Passthrough => {}
        }
    }

    // Tenant-binding gate (ADR-022). Runs BEFORE the resume buffer
    // `replay` so a cross-tenant probe cannot infer existence via
    // backend side effects (NotFound vs Expired surfaces differ on
    // some backends). Owner mismatch returns the same envelope as
    // the buffer's `ResumeError::NotFound` arm below — wire-shape
    // identical (modulo request id) per OWASP IDOR mitigation.
    if let Err(resp) = enforce_owner(&server, &stream_id, &identity, &req_id).await {
        return resp;
    }

    let replay_stream = match buffer.replay(&stream_id, since).await {
        Ok(s) => s,
        Err(klieo_core::resume::ResumeError::Expired { since_id }) => {
            return (
                StatusCode::OK,
                Json(rpc_error(
                    Some(req_id),
                    crate::JSONRPC_RESUME_BUFFER_EXPIRED,
                    &format!("resume window expired (since_id={since_id})"),
                )),
            )
                .into_response();
        }
        Err(klieo_core::resume::ResumeError::NotFound(_)) => {
            return (
                StatusCode::OK,
                Json(rpc_error(
                    Some(req_id),
                    crate::JSONRPC_RESUME_BUFFER_NOT_FOUND,
                    "no buffered stream for progressToken",
                )),
            )
                .into_response();
        }
        Err(klieo_core::resume::ResumeError::Backend(e)) => {
            tracing::warn!(
                target: "mcp.resume",
                stream_id = %stream_id,
                error = %e,
                "resume backend error"
            );
            return (
                StatusCode::OK,
                Json(rpc_error(
                    Some(req_id),
                    JSONRPC_SERVER_ERROR,
                    "resume backend unavailable",
                )),
            )
                .into_response();
        }
        // ResumeError is #[non_exhaustive]; future variants fall back to a
        // generic server-error envelope.
        Err(_) => {
            return (
                StatusCode::OK,
                Json(rpc_error(
                    Some(req_id),
                    JSONRPC_SERVER_ERROR,
                    "resume backend error",
                )),
            )
                .into_response();
        }
    };

    // Subscribe BEFORE consuming replay so events published during the
    // replay drain are not lost (subscribe-before-replay race fix).
    // Skip the tail when the buffer is already terminal — no further
    // events will be published, so an infinite subscription would
    // prevent the SSE response from closing after replay drains.
    let already_closed = match buffer.is_terminal(&stream_id).await {
        Ok(v) => v,
        Err(e) => {
            tracing::warn!(
                target: "mcp.resume",
                stream_id = %stream_id,
                error = %e,
                "is_terminal check failed; assuming live"
            );
            false
        }
    };
    let subject = format!("klieo.mcp.progress.{}", stream_id);
    let live_tail = if already_closed {
        None
    } else {
        let durable = klieo_core::DurableName::new(format!("klieo-eph-{}", uuid::Uuid::new_v4()));
        match pubsub.subscribe(&subject, durable).await {
            Ok(s) => Some(s),
            Err(e) => {
                tracing::warn!(
                    target: "mcp.resume",
                    subject = %subject,
                    error = %e,
                    "live tail subscribe failed; returning replay-only response"
                );
                None
            }
        }
    };

    let max_replayed = Arc::new(AtomicU64::new(since));
    let combined =
        combine_replay_and_tail(replay_stream, live_tail, max_replayed, stream_id.clone());

    // Register the per-invoke cancel token under stream_id so the
    // wildcard cancel-subject subscription can fire it on inbound
    // klieo.mcp.cancel.{progressToken} messages. The DeregisterOnDrop
    // wrapper inside `wrap_with_cancel_fanout` removes the entry on
    // stream end or client disconnect.
    server
        .cancel_registry()
        .register(stream_id.clone(), request_cancel.clone());
    // stream_resume holds no leader claim — claims belong to the
    // originating invoke (`stream_tools_call`). Resume is read-side.
    // Ownership handle is `None` for the same reason: resume must
    // never `kv.delete` on drop, only the invoke owner does.
    let guarded = wrap_with_cancel_fanout(&server, combined, stream_id, request_cancel, None, None);
    axum::response::Response::builder()
        .status(StatusCode::OK)
        .header(header::CONTENT_TYPE, "text/event-stream")
        .header("Cache-Control", "no-cache")
        .body(axum::body::Body::from_stream(guarded))
        .unwrap()
}

/// Serve a `tools/call` request as an SSE stream.
///
/// Flow:
/// 1. Extract tool name and arguments, spawn the invoke task.
/// 2. Build the SSE stream pump: interleaves progress events with
///    the terminal result frame. The pump is one cohesive select-loop
///    that cannot be split further without fragmenting the state machine.
/// 3. Each yielded frame receives a monotonically-increasing `id:` line
///    (per-progressToken counter) and is recorded to the resume buffer.
/// 4. Wrap the body stream in `CancelOnDrop` so dropping the response
///    body (client TCP close) fires the request-scoped cancel token,
///    which the spawned invoke task observes via `ToolCtx.cancel`.
/// 5. Return the SSE response with correct headers.
#[allow(clippy::too_many_lines)]
#[instrument(
    skip_all,
    fields(
        rpc.system = "klieo-mcp",
        rpc.method = "tools/call",
        klieo.stream_id = tracing::field::Empty,
    ),
)]
async fn stream_tools_call(
    server: Arc<McpServer>,
    raw: serde_json::Value,
    progress_token: serde_json::Value,
    identity: Option<Identity>,
) -> Response {
    run_tools_call(server, raw, progress_token, identity, None).await
}

/// Shared body of the `tools/call` SSE-upgrade path.
///
/// Driven from two sites:
/// - [`stream_tools_call`] passes `existing_leader = None` and the
///   path performs the cluster-0.20 [`try_claim_leader`] claim,
///   capturing the original JSON-RPC body + authenticated principal
///   inside the [`klieo_core::LeaderEntry`] for cluster-0.24
///   follower re-invoke.
/// - [`handle_dead_leader_orphan_mcp`] passes `existing_leader =
///   Some(handle)` (already CAS-claimed against the dead leader's
///   revision with `attempt + 1`); this path SKIPS the on-invoke
///   claim and adopts the supplied handle. The cached payload-+-
///   principal pair came from the dead leader's entry, so the
///   re-invoke runs under the same tenant binding as the original.
#[allow(clippy::too_many_lines)]
async fn run_tools_call(
    server: Arc<McpServer>,
    raw: serde_json::Value,
    progress_token: serde_json::Value,
    identity: Option<Identity>,
    existing_leader: Option<klieo_core::LeaderHandle>,
) -> Response {
    let stream_id = progress_token_to_string(&progress_token);
    if let Err(e) = klieo_core::validate_subject_token(&stream_id) {
        tracing::warn!(
            target: "mcp.tools_call",
            error = %e,
            "rejected progressToken: invalid subject segment",
        );
        let req_id = raw.get("id").cloned().unwrap_or(serde_json::Value::Null);
        return (
            StatusCode::OK,
            Json(rpc_error(
                Some(req_id),
                JSONRPC_INVALID_PARAMS,
                "progressToken contains reserved bus-subject metacharacters",
            )),
        )
            .into_response();
    }
    // Validate the optional cross-hop provenance anchor before claiming
    // leadership/ownership — a malformed anchor fails the call loud
    // rather than silently dropping a requested audit link.
    let parent_anchor = match parse_parent_anchor(&raw) {
        Ok(anchor) => anchor,
        Err(message) => {
            tracing::warn!(
                target: "mcp.tools_call",
                reason = message,
                "rejected tools/call: malformed _meta.parentAnchor",
            );
            let req_id = raw.get("id").cloned().unwrap_or(serde_json::Value::Null);
            return (
                StatusCode::OK,
                Json(rpc_error(Some(req_id), JSONRPC_INVALID_PARAMS, message)),
            )
                .into_response();
        }
    };
    tracing::Span::current().record("klieo.stream_id", stream_id.as_str());
    let request_cancel = server.parent_cancel.child_token();
    // Register the per-invoke cancel token under stream_id so the
    // wildcard cancel-subject subscription can fire it on inbound
    // klieo.mcp.cancel.{progressToken} messages. The matching
    // deregister fires from `wrap_with_cancel_fanout` on stream drop.
    server
        .cancel_registry()
        .register(stream_id.clone(), request_cancel.clone());
    // Adopt the follower-supplied handle on cluster-0.24 re-invoke;
    // otherwise claim fresh leadership for the lifetime of the SSE
    // response (multi-replica orphan detection, ADR-020). KV-layer
    // failures on a fresh claim degrade silently: log warn + proceed
    // without a claim (a follower stream_resume will treat the
    // buffer as orphaned only if it ALSO has buffered events;
    // otherwise the regular replay path runs unchanged).
    //
    // Cluster 0.24: capture the original JSON-RPC body + the
    // authenticated principal so a follower can re-invoke an
    // idempotent tool from the cached payload under the same
    // tenant binding. A serialisation failure here is non-fatal:
    // the invoke proceeds with `payload = None` and any follower
    // that detects an orphan will terminate (no payload to
    // re-invoke from).
    let leader_handle = match existing_leader {
        Some(handle) => Some(handle),
        None => {
            let payload_bytes_for_failover = match serde_json::to_vec(&raw) {
                Ok(v) => Some(Bytes::from(v)),
                Err(e) => {
                    tracing::warn!(
                        target: "mcp.failover",
                        stream_id = %stream_id,
                        error = %e,
                        "tools/call body serialise for failover failed; \
                         proceeding without cached payload",
                    );
                    None
                }
            };
            let principal_for_failover = identity
                .as_ref()
                .filter(|id| !id.is_anonymous())
                .map(|id| id.as_str().to_string());
            try_claim_leader(
                &server,
                &stream_id,
                payload_bytes_for_failover,
                principal_for_failover,
            )
            .await
        }
    };
    // Tenant-binding claim (ADR-022). Held alongside the leader
    // handle inside `CancelOnDrop` so both KV entries fire their
    // best-effort delete on body drop in a single drop pass.
    let ownership_handle = match try_claim_ownership(&server, &stream_id, &identity).await {
        Ok(handle) => handle,
        Err(resp) => return resp,
    };
    let (req_id, rx, invoke_handle) = spawn_progress_stream_task(
        &server,
        &raw,
        request_cancel.clone(),
        identity.as_ref(),
        parent_anchor,
    );

    let next_id = Arc::new(AtomicU64::new(0));
    let buffer = server.resume_buffer.clone();
    let pubsub = server.pubsub.clone();
    let publish_subject = format!("klieo.mcp.progress.{stream_id}");
    let publish_permits = server.publish_permits.clone();

    // `async_stream::stream!` expands to `async move { ... }` and captures
    // referenced locals by move. Clone the locals the stream needs so the
    // originals remain available for the `wrap_with_cancel_fanout` wiring below.
    let request_cancel_for_stream = request_cancel.clone();
    let stream_id_for_stream = stream_id.clone();

    let body_stream = async_stream::stream! {
        let mut rx = rx;
        let invoke_handle = invoke_handle;
        tokio::pin!(invoke_handle);
        tokio::task::yield_now().await;

        loop {
            tokio::select! {
                biased;
                _ = request_cancel_for_stream.cancelled() => {
                    // Body about to drop; stop yielding to avoid writing into a
                    // closed body. Spawned task observes the same token via ToolCtx.
                    break;
                }
                recv_result = rx.recv() => {
                    match recv_result {
                        Ok(event) => {
                            let frame = match progress_event(&progress_token, &event) {
                                Ok(f) => f,
                                Err(e) => match e {},
                            };
                            yield Ok::<_, std::convert::Infallible>(emit_progress_frame(
                                &buffer, &pubsub, &publish_permits,
                                &publish_subject, &stream_id_for_stream,
                                &next_id, frame, false,
                            ));
                        }
                        Err(tokio::sync::broadcast::error::RecvError::Lagged(n)) => {
                            let frame = match lagged_event(&progress_token, n) {
                                Ok(f) => f,
                                Err(e) => match e {},
                            };
                            yield Ok::<_, std::convert::Infallible>(emit_progress_frame(
                                &buffer, &pubsub, &publish_permits,
                                &publish_subject, &stream_id_for_stream,
                                &next_id, frame, false,
                            ));
                        }
                        Err(tokio::sync::broadcast::error::RecvError::Closed) => {
                            break;
                        }
                    }
                }
                result = &mut invoke_handle => {
                    loop {
                        match rx.try_recv() {
                            Ok(event) => {
                                let frame = match progress_event(&progress_token, &event) {
                                    Ok(f) => f,
                                    Err(e) => match e {},
                                };
                                yield Ok::<_, std::convert::Infallible>(emit_progress_frame(
                                    &buffer, &pubsub, &publish_permits,
                                    &publish_subject, &stream_id_for_stream,
                                    &next_id, frame, false,
                                ));
                            }
                            Err(tokio::sync::broadcast::error::TryRecvError::Lagged(n)) => {
                                let frame = match lagged_event(&progress_token, n) {
                                    Ok(f) => f,
                                    Err(e) => match e {},
                                };
                                yield Ok::<_, std::convert::Infallible>(emit_progress_frame(
                                    &buffer, &pubsub, &publish_permits,
                                    &publish_subject, &stream_id_for_stream,
                                    &next_id, frame, false,
                                ));
                            }
                            Err(_) => break,
                        }
                    }
                    let outcome = result
                        .unwrap_or_else(|_| Err(klieo_core::error::ToolError::Permanent(
                            "invoke task panicked".into()
                        )));
                    let req_id_opt = if req_id == serde_json::Value::Null {
                        None
                    } else {
                        Some(req_id.clone())
                    };
                    let frame = match result_event(req_id_opt, outcome) {
                        Ok(f) => f,
                        Err(e) => match e {},
                    };
                    yield Ok::<_, std::convert::Infallible>(emit_progress_frame(
                        &buffer, &pubsub, &publish_permits,
                        &publish_subject, &stream_id_for_stream,
                        &next_id, frame, true,
                    ));
                    return;
                }
            }
        }

        let result = invoke_handle.await
            .unwrap_or_else(|_| Err(klieo_core::error::ToolError::Permanent(
                "invoke task panicked".into()
            )));
        loop {
            match rx.try_recv() {
                Ok(event) => {
                    let frame = match progress_event(&progress_token, &event) {
                        Ok(f) => f,
                        Err(e) => match e {},
                    };
                    yield Ok::<_, std::convert::Infallible>(emit_progress_frame(
                        &buffer, &pubsub, &publish_permits,
                        &publish_subject, &stream_id_for_stream,
                        &next_id, frame, false,
                    ));
                }
                Err(tokio::sync::broadcast::error::TryRecvError::Lagged(n)) => {
                    let frame = match lagged_event(&progress_token, n) {
                        Ok(f) => f,
                        Err(e) => match e {},
                    };
                    yield Ok::<_, std::convert::Infallible>(emit_progress_frame(
                        &buffer, &pubsub, &publish_permits,
                        &publish_subject, &stream_id_for_stream,
                        &next_id, frame, false,
                    ));
                }
                Err(_) => break,
            }
        }
        let req_id_opt = if req_id == serde_json::Value::Null {
            None
        } else {
            Some(req_id)
        };
        let frame = match result_event(req_id_opt, result) {
            Ok(f) => f,
            Err(e) => match e {},
        };
        yield Ok::<_, std::convert::Infallible>(emit_progress_frame(
            &buffer, &pubsub, &publish_permits,
            &publish_subject, &stream_id_for_stream,
            &next_id, frame, true,
        ));
    };

    let guarded = wrap_with_cancel_fanout(
        &server,
        body_stream.boxed(),
        stream_id,
        request_cancel,
        leader_handle,
        ownership_handle,
    );

    axum::response::Response::builder()
        .status(StatusCode::OK)
        .header(header::CONTENT_TYPE, "text/event-stream")
        .header("Cache-Control", "no-cache")
        .body(axum::body::Body::from_stream(guarded))
        .unwrap()
}

/// Format one `AgentEvent` as an SSE `event: progress` frame carrying a
/// `notifications/progress` JSON-RPC notification envelope.
fn progress_event(
    token: &serde_json::Value,
    event: &klieo_core::AgentEvent,
) -> Result<axum::body::Bytes, std::convert::Infallible> {
    let payload = serde_json::json!({
        "jsonrpc": "2.0",
        "method": "notifications/progress",
        "params": {
            "progressToken": token,
            "data": event,
        }
    });
    Ok(axum::body::Bytes::from(format!(
        "event: progress\ndata: {}\n\n",
        payload
    )))
}

/// Synthetic progress frame emitted when the broadcast channel lags.
fn lagged_event(
    token: &serde_json::Value,
    skipped: u64,
) -> Result<axum::body::Bytes, std::convert::Infallible> {
    let payload = serde_json::json!({
        "jsonrpc": "2.0",
        "method": "notifications/progress",
        "params": {
            "progressToken": token,
            "data": { "kind": "lagged", "message": format!("lagged: skipped {} events", skipped) }
        }
    });
    Ok(axum::body::Bytes::from(format!(
        "event: progress\ndata: {}\n\n",
        payload
    )))
}

/// Terminal SSE frame: carries the JSON-RPC `tools/call` result or a
/// redacted error envelope.
fn result_event(
    id: Option<serde_json::Value>,
    outcome: Result<serde_json::Value, klieo_core::error::ToolError>,
) -> Result<axum::body::Bytes, std::convert::Infallible> {
    let envelope = match outcome {
        Ok(v) => {
            let result = serde_json::json!({
                "content": [{ "type": "text", "text": v.to_string() }]
            });
            serde_json::json!({ "jsonrpc": "2.0", "id": id, "result": result })
        }
        Err(e) => tool_error_to_envelope(id, e),
    };
    Ok(axum::body::Bytes::from(format!(
        "event: result\ndata: {}\n\n",
        envelope
    )))
}

/// Stream wrapper that fires a `DropGuard` on `Drop`. When axum/hyper
/// drops the response body after a client TCP close, the held guard
/// cancels the request-scoped token, propagating to `ToolCtx.cancel`
/// inside the spawned invoke task.
///
/// Drop ordering: the explicit `Drop::drop` body runs FIRST and only
/// spawns a best-effort cross-replica publish (no `.await`). The
/// `_guard` field then drops as part of normal field-drop, firing
/// the local request CancellationToken. Because the body merely
/// spawns, awaiting tasks see the local cancel before the bus
/// publish completes.
///
/// # Security
/// The cross-replica cancel signal published from this `Drop` body
/// embeds the caller-supplied progressToken in its subject. Cancel
/// signals share the progressToken-as-credential threat model
/// documented for resume in ADR-018 / ADR-019: any caller who knows
/// the progressToken can cause a cancel on the owning replica.
/// Operators MUST mint unguessable progressTokens and gate
/// per-tenant authorisation BEFORE the request reaches the server;
/// otherwise cross-tenant cancel becomes possible (CWE-639 IDOR).
struct CancelOnDrop<S> {
    inner: S,
    _guard: tokio_util::sync::DropGuard,
    pubsub: Arc<dyn klieo_core::Pubsub>,
    cancel_subject: String,
    /// Shared with [`McpServer::publish_permits`] so the drop-time
    /// cross-replica cancel publish bounds under the same cap as the
    /// per-stream SSE-frame publishes. Passed through to
    /// [`klieo_core::cancel::spawn_drop_publish`] which `try_acquire`s
    /// before spawning; saturation drops the cancel publish with a
    /// `warn` (cross-replica subscribers still see the same task's
    /// local cancel fire in the conventional drop-of-`_guard` path).
    permits: Arc<tokio::sync::Semaphore>,
    /// Held for the lifetime of the SSE response body. `Drop` releases
    /// the leader claim (heartbeat abort + best-effort KV delete inside
    /// [`klieo_core::LeaderHandle::drop`]) when the body drops, so a
    /// replica failure manifests as a TTL-expired KV entry that a
    /// follower's `stream_resume` orphan probe observes. `None` when
    /// leader election is disabled (no `with_leader_election`) or when
    /// the claim itself failed (fail-open per ADR-020).
    _leader: Option<klieo_core::LeaderHandle>,
    /// Held for the lifetime of the SSE response body. `Drop` fires a
    /// best-effort `kv.delete` inside
    /// [`klieo_core::OwnershipHandle::drop`] so the `klieo-tenants`
    /// entry no longer survives the stream. `None` when tenant
    /// binding is disabled (no `with_tenant_binding`), when no
    /// authenticator produced a non-anonymous principal, or when the
    /// claim itself failed (fail-open per ADR-022). Resume-side
    /// streams never hold this — claims belong to the originating
    /// invoke.
    _ownership: Option<klieo_core::OwnershipHandle>,
}

impl<S: futures::Stream + Unpin> futures::Stream for CancelOnDrop<S> {
    type Item = S::Item;

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<S::Item>> {
        std::pin::Pin::new(&mut self.inner).poll_next(cx)
    }
}

impl<S> Drop for CancelOnDrop<S> {
    fn drop(&mut self) {
        // This body runs FIRST; `_guard` drops after the body returns
        // (normal field-drop order) and fires the local request token.
        // Cross-replica fan-out is delegated to
        // [`klieo_core::cancel::spawn_drop_publish`], which handles
        // the empty-subject short-circuit and the no-runtime guard.
        let mut trace_headers = klieo_core::Headers::default();
        klieo_core::inject_traceparent(&mut trace_headers, &opentelemetry::Context::current());
        klieo_core::cancel::spawn_drop_publish(
            self.pubsub.clone(),
            std::mem::take(&mut self.cancel_subject),
            "mcp.cancel",
            Some(self.permits.clone()),
            trace_headers,
        );
    }
}

/// Dispatch one parsed JSON-RPC value, supporting batch arrays.
#[instrument(
    skip_all,
    fields(
        rpc.system = "klieo-mcp",
        rpc.method = tracing::field::Empty,
    ),
)]
async fn dispatch(
    server: &McpServer,
    raw: serde_json::Value,
    session: Option<&std::sync::Arc<crate::session::Session>>,
) -> serde_json::Value {
    if let Some(method) = raw.get("method").and_then(|m| m.as_str()) {
        tracing::Span::current().record("rpc.method", method);
    }
    match raw {
        serde_json::Value::Array(items) => {
            if items.len() > MAX_BATCH_ITEMS {
                warn!(
                    items = items.len(),
                    max = MAX_BATCH_ITEMS,
                    "rejected oversized JSON-RPC batch"
                );
                return rpc_error(None, JSONRPC_SERVER_ERROR, "batch size exceeds limit");
            }
            let mut out = Vec::with_capacity(items.len());
            for item in items {
                if server.parent_cancel.is_cancelled() {
                    out.push(rpc_error(
                        item.get("id").cloned(),
                        JSONRPC_SERVER_ERROR,
                        "server shutting down",
                    ));
                    continue;
                }
                out.push(server.handle_jsonrpc(item, session).await);
            }
            serde_json::Value::Array(out)
        }
        single => server.handle_jsonrpc(single, session).await,
    }
}

#[cfg(test)]
mod post_body_classification_tests {
    //! Unit tests for the POST /mcp body-classification arm + the
    //! `touch_last_activity` helper introduced for HTTP outbound
    //! responses. Driven through the axum [`Router`] via
    //! `tower::ServiceExt::oneshot` so the wire-side semantics
    //! (status codes, headers) are exercised end to end without
    //! binding a port.
    use super::*;
    use crate::outbound::OutboundRequests;
    use crate::{OutboundFrameSink, OutboundSinkError};
    use async_trait::async_trait;
    use axum::body::{to_bytes, Body};
    use axum::http::{header, Method, Request, StatusCode};
    use klieo_core::error::ToolError;
    use klieo_core::llm::ToolDef;
    use klieo_core::tool::{ToolCtx, ToolInvoker};
    use serde_json::{json, Value};
    use tokio::sync::Mutex as AsyncMutex;
    use tower::ServiceExt;

    struct NoopInvoker;

    #[async_trait]
    impl ToolInvoker for NoopInvoker {
        fn catalogue(&self) -> Vec<ToolDef> {
            Vec::new()
        }
        async fn invoke(
            &self,
            name: &str,
            _args: Value,
            _ctx: ToolCtx,
        ) -> Result<Value, ToolError> {
            Err(ToolError::UnknownTool(name.into()))
        }
    }

    fn server() -> Arc<McpServer> {
        McpServer::builder()
            .add_tools(Arc::new(NoopInvoker))
            .build_arc()
            .unwrap()
    }

    /// Capturing frame sink so the second test can wire an
    /// `OutboundRequests` primitive onto the server without spinning
    /// a transport. Mirrors the test-only sink used by
    /// `outbound::tests::CapturingSink`.
    struct LocalCapturingSink {
        frames: AsyncMutex<Vec<Value>>,
    }

    #[async_trait]
    impl OutboundFrameSink for LocalCapturingSink {
        async fn send_frame(&self, frame: std::sync::Arc<Value>) -> Result<(), OutboundSinkError> {
            self.frames.lock().await.push((*frame).clone());
            Ok(())
        }
    }

    async fn post_init(server: &Arc<McpServer>) -> String {
        let body = json!({
            "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}
        });
        let req = Request::builder()
            .method(Method::POST)
            .uri("/mcp")
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(serde_json::to_vec(&body).unwrap()))
            .unwrap();
        let resp = server.router().oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        resp.headers()
            .get(MCP_SESSION_ID_HEADER)
            .expect("initialize must echo Mcp-Session-Id")
            .to_str()
            .unwrap()
            .to_string()
    }

    fn outbound_response_request(session_id: &str, id: i64) -> Request<Body> {
        let body = json!({"jsonrpc": "2.0", "id": id, "result": {"x": 1}});
        Request::builder()
            .method(Method::POST)
            .uri("/mcp")
            .header(header::CONTENT_TYPE, "application/json")
            .header(MCP_SESSION_ID_HEADER, session_id)
            .body(Body::from(serde_json::to_vec(&body).unwrap()))
            .unwrap()
    }

    /// Without an outbound primitive wired on the server (the SSE-
    /// stream open path wires it in a follow-on task), a POST body
    /// shaped `{id, result}` must fall through to the rejection arm
    /// and surface as 400 Bad Request with a JSON-RPC parse-error
    /// envelope. Pins the no-outbound branch behaviour.
    #[tokio::test]
    async fn post_outbound_response_with_no_outbound_wired_returns_400() {
        let server = server();
        let session_id = post_init(&server).await;
        let session_uuid = uuid::Uuid::parse_str(&session_id).expect("session id is a uuid");
        {
            let sessions = server.sessions.read().await;
            let session = sessions
                .get(&session_uuid)
                .expect("post_init inserts the session into the registry");
            assert!(
                session.outbound.get().is_none(),
                "outbound must be unset on a plain HTTP server"
            );
        }

        let resp = server
            .router()
            .oneshot(outbound_response_request(&session_id, 42))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        let bytes = to_bytes(resp.into_body(), 1 << 16).await.unwrap();
        let envelope: Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(envelope["error"]["code"], JSONRPC_PARSE_ERROR);
    }

    /// With the outbound primitive wired (mocked by directly
    /// populating the `OnceCell` over a capturing sink), a POST body
    /// shaped `{id, result}` must route into `complete_pending` and
    /// return 202 Accepted. Drives the production write path via
    /// `outbound_request` so the awaited future resolves with the
    /// supplied result — the integration ledger that the body-shape
    /// branch + the correlation table cooperate end to end.
    #[tokio::test]
    async fn post_outbound_response_routes_when_outbound_wired() {
        let server = server();
        let session_id = post_init(&server).await;

        let sink: Arc<dyn OutboundFrameSink> = Arc::new(LocalCapturingSink {
            frames: AsyncMutex::new(Vec::new()),
        });
        let outbound = Arc::new(OutboundRequests::new(sink));
        // Production reads route through the per-session registry;
        // seed the mock onto the Session cell so route_outbound_response
        // observes it.
        let session_uuid = uuid::Uuid::parse_str(&session_id).expect("session id is a uuid");
        let session = {
            let sessions = server.sessions.read().await;
            sessions
                .get(&session_uuid)
                .expect("post_init inserts the session into the registry")
                .clone()
        };
        if session.outbound.set(outbound.clone()).is_err() {
            panic!("session.outbound OnceCell must be empty for this test");
        }

        let call_handle = {
            let outbound = outbound.clone();
            tokio::spawn(async move {
                use klieo_core::ServerOutbound;
                outbound
                    .outbound_request(
                        "custom/method",
                        Value::Null,
                        std::time::Duration::from_secs(2),
                    )
                    .await
            })
        };

        // Yield + sleep so the spawned task registers its pending entry
        // (id=1, the AtomicI64 seed) before we deliver the response.
        // Without this settle the inbound POST may arrive before
        // `outbound_request` has inserted the oneshot sender, and
        // `complete_pending` would log+drop as unknown id.
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;

        let resp = server
            .router()
            .oneshot(outbound_response_request(&session_id, 1))
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::ACCEPTED);

        let result = tokio::time::timeout(std::time::Duration::from_secs(2), call_handle)
            .await
            .expect("outbound_request did not resolve")
            .expect("task panicked")
            .expect("outbound_request returned error");
        assert_eq!(result["x"], 1);
    }

    /// Every successful POST must bump `session_last_activity` so the
    /// idle-timeout watchdog sees fresh traffic. Captures the clock
    /// before + after a tools/list POST that passes session
    /// validation and asserts strict monotonicity.
    #[tokio::test]
    async fn post_updates_last_activity() {
        let server = server();
        let session_id = post_init(&server).await;
        let session_uuid = uuid::Uuid::parse_str(&session_id).expect("session id is a uuid");
        let session = {
            let sessions = server.sessions.read().await;
            sessions
                .get(&session_uuid)
                .expect("post_init inserts the session into the registry")
                .clone()
        };

        let before = session
            .last_activity_millis
            .load(std::sync::atomic::Ordering::Relaxed);
        // Ensure the monotonic clock advances at least one tick.
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;

        let body = json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"});
        let req = Request::builder()
            .method(Method::POST)
            .uri("/mcp")
            .header(header::CONTENT_TYPE, "application/json")
            .header(MCP_SESSION_ID_HEADER, &session_id)
            .body(Body::from(serde_json::to_vec(&body).unwrap()))
            .unwrap();
        let resp = server.router().oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let after = session
            .last_activity_millis
            .load(std::sync::atomic::Ordering::Relaxed);
        assert!(
            after > before,
            "session last_activity must advance on successful POST"
        );
    }
}

#[cfg(test)]
mod get_outbound_wiring_tests {
    //! Unit tests for the `GET /mcp` outbound + roots-cache wiring.
    //! A successful GET MUST populate the active session's `outbound`
    //! cell over the same per-session mpsc tx the SSE body drains,
    //! and MUST populate `session.roots_cache` iff the server was
    //! built with `with_client_sampling()`.
    use super::*;
    use axum::body::Body;
    use axum::http::{header, Method, Request, StatusCode};
    use klieo_core::error::ToolError;
    use klieo_core::llm::ToolDef;
    use klieo_core::tool::{ToolCtx, ToolInvoker};
    use serde_json::{json, Value};
    use tower::ServiceExt;

    struct NoopInvoker;

    #[async_trait::async_trait]
    impl ToolInvoker for NoopInvoker {
        fn catalogue(&self) -> Vec<ToolDef> {
            Vec::new()
        }
        async fn invoke(
            &self,
            name: &str,
            _args: Value,
            _ctx: ToolCtx,
        ) -> Result<Value, ToolError> {
            Err(ToolError::UnknownTool(name.into()))
        }
    }

    fn server_with_sampling() -> Arc<McpServer> {
        McpServer::builder()
            .add_tools(Arc::new(NoopInvoker))
            .with_client_sampling()
            .build_arc()
            .unwrap()
    }

    fn server_without_sampling() -> Arc<McpServer> {
        McpServer::builder()
            .add_tools(Arc::new(NoopInvoker))
            .build_arc()
            .unwrap()
    }

    async fn post_init(server: &Arc<McpServer>) -> String {
        let body = json!({
            "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}
        });
        let req = Request::builder()
            .method(Method::POST)
            .uri("/mcp")
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(serde_json::to_vec(&body).unwrap()))
            .unwrap();
        let resp = server.router().oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        resp.headers()
            .get(MCP_SESSION_ID_HEADER)
            .expect("initialize echoes session id")
            .to_str()
            .unwrap()
            .to_string()
    }

    async fn get_mcp_with_session(server: &Arc<McpServer>, session_id: &str) -> StatusCode {
        let req = Request::builder()
            .method(Method::GET)
            .uri("/mcp")
            .header(MCP_SESSION_ID_HEADER, session_id)
            .body(Body::empty())
            .unwrap();
        let resp = server.router().oneshot(req).await.unwrap();
        resp.status()
    }

    #[tokio::test]
    async fn http_get_wires_outbound_primitive() {
        let server = server_with_sampling();
        let session_id = post_init(&server).await;
        let session_uuid = uuid::Uuid::parse_str(&session_id).expect("session id is a uuid");
        let session = {
            let sessions = server.sessions.read().await;
            sessions
                .get(&session_uuid)
                .expect("post_init inserts the session into the registry")
                .clone()
        };
        assert!(
            session.outbound.get().is_none(),
            "outbound must be unset before GET"
        );
        let status = get_mcp_with_session(&server, &session_id).await;
        assert_eq!(status, StatusCode::OK);
        assert!(
            session.outbound.get().is_some(),
            "GET must populate the outbound primitive"
        );
    }

    #[tokio::test]
    async fn http_get_wires_roots_cache_when_sampling_declared() {
        let server = server_with_sampling();
        let session_id = post_init(&server).await;
        let session_uuid = uuid::Uuid::parse_str(&session_id).expect("session id is a uuid");
        let session = {
            let sessions = server.sessions.read().await;
            sessions
                .get(&session_uuid)
                .expect("post_init inserts the session into the registry")
                .clone()
        };
        assert!(session.roots_cache.get().is_none());
        let status = get_mcp_with_session(&server, &session_id).await;
        assert_eq!(status, StatusCode::OK);
        assert!(
            session.roots_cache.get().is_some(),
            "with_client_sampling + GET must populate roots_cache"
        );
    }

    #[tokio::test]
    async fn http_get_skips_roots_cache_when_sampling_absent() {
        let server = server_without_sampling();
        let session_id = post_init(&server).await;
        let session_uuid = uuid::Uuid::parse_str(&session_id).expect("session id is a uuid");
        let session = {
            let sessions = server.sessions.read().await;
            sessions
                .get(&session_uuid)
                .expect("post_init inserts the session into the registry")
                .clone()
        };
        let status = get_mcp_with_session(&server, &session_id).await;
        assert_eq!(status, StatusCode::OK);
        assert!(
            session.outbound.get().is_some(),
            "outbound is wired regardless of sampling"
        );
        assert!(
            session.roots_cache.get().is_none(),
            "roots_cache is gated on declare_sampling"
        );
    }

    /// Dropping the SSE body must fire the [`GuardedSseStream`] cleanup
    /// path: pending outbound oneshots are drained so awaiting callers
    /// resolve with [`klieo_core::ServerOutboundError::TransportClosed`].
    /// Pins ADR-028's "single-session reaping" failure-semantics
    /// guarantee.
    #[tokio::test]
    async fn disconnect_drains_pending_outbound() {
        use klieo_core::{ServerOutbound, ServerOutboundError};

        let server = server_with_sampling();
        let session_id = post_init(&server).await;

        // Open the SSE stream; the response body owns the GuardedSseStream
        // whose Drop fires the cleanup task.
        let req = Request::builder()
            .method(Method::GET)
            .uri("/mcp")
            .header(MCP_SESSION_ID_HEADER, &session_id)
            .body(Body::empty())
            .unwrap();
        let resp = server.router().oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let session_uuid = uuid::Uuid::parse_str(&session_id).expect("session id is a uuid");
        let outbound = {
            let sessions = server.sessions.read().await;
            sessions
                .get(&session_uuid)
                .and_then(|s| s.outbound.get().cloned())
                .expect("GET must populate outbound primitive")
        };

        // Spawn an outbound caller that parks on its receiver; wait
        // until the pending entry is registered so the drain sees it.
        let call_handle = {
            let outbound = outbound.clone();
            tokio::spawn(async move {
                outbound
                    .outbound_request(
                        "custom/method",
                        Value::Null,
                        std::time::Duration::from_secs(5),
                    )
                    .await
            })
        };
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;

        // Dropping the response drops the body → GuardedSseStream::drop
        // fires cleanup_tx → spawn_session_cleanup awaits + marks the
        // session closed + drains pending outbound oneshots.
        drop(resp);

        let outcome = tokio::time::timeout(std::time::Duration::from_secs(2), call_handle)
            .await
            .expect("outbound_request did not resolve within 2s of disconnect")
            .expect("task panicked");
        assert!(
            matches!(outcome, Err(ServerOutboundError::TransportClosed)),
            "disconnect must surface as TransportClosed; got {outcome:?}"
        );
    }
}

#[cfg(test)]
mod idle_watchdog_tests {
    //! Unit tests for the idle-reaper loop. The reaper is armed on
    //! the first successful `initialize` POST and evicts a session
    //! once `session_last_activity` has been idle longer than the
    //! configured deadline. ADR-028.
    use super::*;
    use axum::body::Body;
    use axum::http::{header, Method, Request, StatusCode};
    use klieo_core::error::ToolError;
    use klieo_core::llm::ToolDef;
    use klieo_core::tool::{ToolCtx, ToolInvoker};
    use serde_json::{json, Value};
    use tower::ServiceExt;

    struct NoopInvoker;

    #[async_trait::async_trait]
    impl ToolInvoker for NoopInvoker {
        fn catalogue(&self) -> Vec<ToolDef> {
            Vec::new()
        }
        async fn invoke(
            &self,
            name: &str,
            _args: Value,
            _ctx: ToolCtx,
        ) -> Result<Value, ToolError> {
            Err(ToolError::UnknownTool(name.into()))
        }
    }

    /// POST `initialize` against the router and return the minted
    /// session id parsed out of the `Mcp-Session-Id` response header.
    async fn post_init(server: &Arc<McpServer>) -> uuid::Uuid {
        let body = json!({
            "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}
        });
        let req = Request::builder()
            .method(Method::POST)
            .uri("/mcp")
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(serde_json::to_vec(&body).unwrap()))
            .unwrap();
        let resp = server.router().oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let raw = resp
            .headers()
            .get(MCP_SESSION_ID_HEADER)
            .and_then(|v| v.to_str().ok())
            .expect("Mcp-Session-Id header on initialize");
        uuid::Uuid::parse_str(raw).expect("Mcp-Session-Id parses as UUID")
    }

    /// Poll [`McpServer::is_session_closed_by_id`] until it reports
    /// the id has been evicted (returns `None`) or the deadline
    /// elapses. The reaper removes idle sessions from the registry
    /// before marking them closed, so eviction surfaces as `None`.
    async fn wait_for_session_evicted(server: &Arc<McpServer>, id: uuid::Uuid) {
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
        loop {
            if server.is_session_closed_by_id(id).await.is_none() {
                return;
            }
            if std::time::Instant::now() >= deadline {
                panic!("session {id} never evicted by idle reaper");
            }
            tokio::time::sleep(std::time::Duration::from_millis(20)).await;
        }
    }

    /// A session left idle past `session_idle_timeout` MUST observe
    /// the idle reaper evicting it from the registry and draining
    /// pending outbound oneshots. The short tick override drives the
    /// reaper fast enough that the test stays cheap on CI.
    #[tokio::test]
    async fn idle_timeout_fires_after_inactivity() {
        let server = McpServer::builder()
            .add_tools(Arc::new(NoopInvoker))
            .with_session_idle_timeout(std::time::Duration::from_millis(150))
            .with_idle_reaper_tick(std::time::Duration::from_millis(50))
            .build_arc()
            .unwrap();
        let id = post_init(&server).await;
        assert_eq!(server.is_session_closed_by_id(id).await, Some(false));

        wait_for_session_evicted(&server, id).await;
    }

    /// `Duration::ZERO` disables the reaper scan. After an idle
    /// stretch the session must still be live — the reaper loop wakes
    /// but the zero-timeout branch skips the scan.
    #[tokio::test]
    async fn zero_timeout_disables_watchdog() {
        let server = McpServer::builder()
            .add_tools(Arc::new(NoopInvoker))
            .with_session_idle_timeout(std::time::Duration::ZERO)
            .with_idle_reaper_tick(std::time::Duration::from_millis(50))
            .build_arc()
            .unwrap();
        let id = post_init(&server).await;
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
        assert_eq!(
            server.is_session_closed_by_id(id).await,
            Some(false),
            "Duration::ZERO must skip eviction"
        );
    }
}

#[cfg(test)]
mod mint_race_tests {
    //! Direct unit tests for [`mint_session_race_500`]. The
    //! concurrent-initialize integration test
    //! (`tests/http_outbound.rs::concurrent_initialize_yields_one_200_and_rest_409_or_500`)
    //! asserts the UNION `{409, 500}` of race-loser counts but never
    //! proves the 500 branch is reachable. If the helper became dead
    //! code (e.g. `.set()` always loses to `.get()` in the scheduler),
    //! that test would still pass with every loser surfacing as 409.
    //!
    //! These tests pin the helper's wire contract independently of
    //! race timing: status, JSON-RPC code, the stable operator-facing
    //! message, and the id-echo behaviour. A future refactor that
    //! drifts any of these breaks the suite — by design.
    use super::*;
    use axum::body::to_bytes;
    use axum::http::StatusCode;

    async fn extract_envelope(resp: Response) -> (StatusCode, serde_json::Value) {
        let status = resp.status();
        let body_bytes = to_bytes(resp.into_body(), usize::MAX)
            .await
            .expect("response body collects");
        let envelope: serde_json::Value =
            serde_json::from_slice(&body_bytes).expect("response body is JSON-RPC envelope");
        (status, envelope)
    }

    #[tokio::test]
    async fn mint_session_race_500_returns_500_with_stable_wire_envelope() {
        let raw_id = serde_json::json!(7);
        let attempted = uuid::Uuid::from_u128(0x0123_4567_89ab_cdef_0123_4567_89ab_cdef);
        let resp = mint_session_race_500(Some(&raw_id), "active_session", Some(attempted));

        let (status, envelope) = extract_envelope(resp).await;
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(envelope["jsonrpc"], "2.0");
        assert_eq!(envelope["id"], 7);
        assert_eq!(envelope["error"]["code"], JSONRPC_SERVER_ERROR);
        assert_eq!(
            envelope["error"]["message"], "internal: session mint race",
            "stable wire message must not drift — operators key alerting on this string"
        );
    }

    #[tokio::test]
    async fn mint_session_race_500_handles_none_attempted_session_id() {
        // wire_session_outbound passes Option<Uuid> directly from
        // active_session_id() — when None, the helper must still
        // return 500 + the stable envelope (operator log shape
        // differs but the wire shape is invariant).
        let resp = mint_session_race_500(None, "outbound", None);
        let (status, envelope) = extract_envelope(resp).await;
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(envelope["error"]["code"], JSONRPC_SERVER_ERROR);
        assert_eq!(envelope["error"]["message"], "internal: session mint race");
        // raw_id == None → JSON-RPC `id: null` (the rpc_error builder
        // emits Null when no id was provided).
        assert_eq!(envelope["id"], serde_json::Value::Null);
    }

    #[tokio::test]
    async fn mint_session_race_500_distinct_message_from_session_already_active() {
        // Negative fixture: confirm the 500-helper's wire message is
        // NOT the same as the legitimate 409 "session already
        // active" path. If a future refactor accidentally collapses
        // both paths to the same string, operators lose the ability
        // to distinguish client mistake from server invariant
        // violation.
        let resp = mint_session_race_500(None, "active_session", None);
        let (_, envelope) = extract_envelope(resp).await;
        assert_ne!(
            envelope["error"]["message"], "session already active",
            "race-500 path must remain distinct from the .get().is_some() 409 path"
        );
    }
}

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

    #[test]
    fn both_none_passes() {
        // Auth-disabled deployment: no authenticator wired on the
        // request, no principal recorded on the session. Every
        // caller can reach every session — the backwards-compatible
        // shape for servers that never opted into auth.
        assert!(principal_matches(None, None));
    }

    #[test]
    fn matching_some_passes() {
        // Verified caller equals the principal stamped on the session
        // at initialize time — the only `Some, Some` shape that may
        // pass.
        let caller = Identity::new("alice");
        assert!(principal_matches(Some(&caller), Some("alice")));
    }

    #[test]
    fn mismatched_some_fails() {
        // Cross-tenant attempt: a verified peer presenting another
        // principal's session id. CWE-639 boundary — must reject so
        // the caller path returns 404 rather than honour the request.
        let caller = Identity::new("alice");
        assert!(!principal_matches(Some(&caller), Some("bob")));
    }

    #[test]
    fn caller_authenticated_session_anonymous_fails() {
        // Authenticator wired AFTER an anonymous session was minted.
        // The session carries no principal; rejecting denies the
        // verified caller without forcing operators to drop every
        // pre-auth session when policy flips on.
        let caller = Identity::new("alice");
        assert!(!principal_matches(Some(&caller), None));
    }

    #[test]
    fn caller_anonymous_session_authenticated_fails() {
        // Authenticator removed AFTER an authenticated session was
        // minted. An anonymous caller cannot reach a session bound
        // to a specific principal — the binding outlives the policy
        // change.
        assert!(!principal_matches(None, Some("alice")));
    }
}

#[cfg(test)]
mod run_resume_authz_tests {
    //! Direct tests for the `klieo/run/resume` authorization seam
    //! (`claim_resume_record`): anonymous, foreign-principal, and
    //! unknown-ticket callers all deny with the same opaque envelope and
    //! do NOT consume the ticket (IDOR / CWE-639); the rightful owner
    //! then claims exactly once, and a replayed claim loses the race.
    use super::*;
    use crate::resume_ticket::{ResumeTicketRecord, ResumeTicketStore};
    use async_trait::async_trait;
    use axum::body::to_bytes;
    use klieo_bus_memory::MemoryKv;
    use klieo_core::error::ToolError;
    use klieo_core::llm::ToolDef;
    use klieo_core::tool::{ToolCtx, ToolInvoker};
    use serde_json::Value;

    struct NoopInvoker;

    #[async_trait]
    impl ToolInvoker for NoopInvoker {
        fn catalogue(&self) -> Vec<ToolDef> {
            Vec::new()
        }
        async fn invoke(
            &self,
            name: &str,
            _args: Value,
            _ctx: ToolCtx,
        ) -> Result<Value, ToolError> {
            Err(ToolError::UnknownTool(name.into()))
        }
    }

    fn seeded_record(principal: &str) -> ResumeTicketRecord {
        let cp = serde_json::json!({
            "run_id": klieo_core::ids::RunId::new(),
            "step_index": 1,
            "thread_id": "t-authz",
            "messages": [],
            "pending_tool_calls": null,
            "created_at": "2026-06-18T00:00:00Z",
        });
        ResumeTicketRecord {
            principal: principal.into(),
            workflow_name: "wf".into(),
            checkpoint: serde_json::from_value(cp).unwrap(),
            created_at: chrono::Utc::now(),
        }
    }

    /// Build a server whose resume-ticket store shares `kv`, so a ticket
    /// seeded through a sibling store over the same KV is visible to the
    /// handler.
    fn server_over(kv: Arc<MemoryKv>) -> Arc<McpServer> {
        McpServer::builder()
            .add_tools(Arc::new(NoopInvoker))
            .with_checkpoint_kv(kv)
            .build_arc()
            .unwrap()
    }

    async fn deny_message(resp: Response) -> String {
        let body = to_bytes(resp.into_body(), usize::MAX)
            .await
            .expect("deny body collects");
        let json: serde_json::Value =
            serde_json::from_slice(&body).expect("deny body is JSON-RPC");
        json["error"]["message"]
            .as_str()
            .expect("deny envelope carries an error message")
            .to_string()
    }

    #[tokio::test]
    async fn anonymous_caller_is_denied_and_ticket_survives() {
        let kv = Arc::new(MemoryKv::new());
        let server = server_over(kv.clone());
        let store = ResumeTicketStore::new(kv);
        let token = ResumeTicketStore::mint_token();
        store
            .persist(&token, &seeded_record("alice@x"))
            .await
            .unwrap();

        let resp = claim_resume_record(&server, &token, Some(Identity::anonymous()), None)
            .await
            .expect_err("anonymous caller must be denied");
        assert_eq!(deny_message(resp).await, RUN_RESUME_DENY_MESSAGE);

        let owner =
            claim_resume_record(&server, &token, Some(Identity::new("alice@x")), None).await;
        assert!(
            owner.is_ok(),
            "an anonymous denial must not consume the ticket"
        );
    }

    #[tokio::test]
    async fn foreign_principal_is_denied_and_owner_still_claims() {
        let kv = Arc::new(MemoryKv::new());
        let server = server_over(kv.clone());
        let store = ResumeTicketStore::new(kv);
        let token = ResumeTicketStore::mint_token();
        store
            .persist(&token, &seeded_record("alice@x"))
            .await
            .unwrap();

        let resp = claim_resume_record(&server, &token, Some(Identity::new("mallory@x")), None)
            .await
            .expect_err("foreign principal must be denied (IDOR)");
        assert_eq!(deny_message(resp).await, RUN_RESUME_DENY_MESSAGE);

        let owner = claim_resume_record(&server, &token, Some(Identity::new("alice@x")), None)
            .await
            .expect("rightful owner claims after the foreign denial");
        assert_eq!(owner.principal, "alice@x");
    }

    #[tokio::test]
    async fn unknown_ticket_is_denied_with_opaque_message() {
        let kv = Arc::new(MemoryKv::new());
        let server = server_over(kv);
        let resp =
            claim_resume_record(&server, "no-such-token", Some(Identity::new("alice@x")), None)
                .await
                .expect_err("unknown ticket must be denied");
        assert_eq!(deny_message(resp).await, RUN_RESUME_DENY_MESSAGE);
    }

    #[tokio::test]
    async fn owner_claims_exactly_once_replay_loses_race() {
        let kv = Arc::new(MemoryKv::new());
        let server = server_over(kv.clone());
        let store = ResumeTicketStore::new(kv);
        let token = ResumeTicketStore::mint_token();
        store
            .persist(&token, &seeded_record("alice@x"))
            .await
            .unwrap();

        let first =
            claim_resume_record(&server, &token, Some(Identity::new("alice@x")), None).await;
        assert!(first.is_ok(), "the first claim by the owner succeeds");

        let replay = claim_resume_record(&server, &token, Some(Identity::new("alice@x")), None)
            .await
            .expect_err("a replayed claim must lose the race");
        assert_eq!(deny_message(replay).await, RUN_RESUME_DENY_MESSAGE);
    }

    /// A `WorkflowResumeHandle` stub whose outcome the test controls,
    /// so `drive_resume`'s success vs. failure routing is exercised
    /// without standing up a real workflow.
    struct StubResumeHandle {
        fail: bool,
    }

    #[async_trait]
    impl crate::workflow::WorkflowResumeHandle for StubResumeHandle {
        async fn resume(
            &self,
            _checkpoint: klieo_core::checkpoint::RunCheckpoint,
            _decision: klieo_core::checkpoint::ApprovalDecision,
            _tenant_label: String,
        ) -> Result<Value, ToolError> {
            if self.fail {
                Err(ToolError::Permanent("resume blew up".into()))
            } else {
                Ok(serde_json::json!({ "resumed": true }))
            }
        }
    }

    fn server_with_handle(fail: bool) -> McpServer {
        let mut server = McpServer::builder()
            .add_tools(Arc::new(NoopInvoker))
            .build()
            .unwrap();
        server.workflow_resume_handles.insert(
            "wf".to_string(),
            Arc::new(StubResumeHandle { fail })
                as Arc<dyn crate::workflow::WorkflowResumeHandle>,
        );
        server
    }

    async fn result_value(resp: Response) -> serde_json::Value {
        let body = to_bytes(resp.into_body(), usize::MAX)
            .await
            .expect("body collects");
        serde_json::from_slice(&body).expect("body is JSON-RPC")
    }

    #[tokio::test]
    async fn drive_resume_unregistered_workflow_is_unavailable() {
        let server = McpServer::builder()
            .add_tools(Arc::new(NoopInvoker))
            .build()
            .unwrap();
        let decision = RunResumeDecision {
            approved: true,
            reason: None,
        };
        // `seeded_record` names workflow "wf"; the server has no handles.
        let resp = drive_resume(&server, decision, seeded_record("alice@x"), None).await;
        assert_eq!(deny_message(resp).await, RUN_RESUME_UNAVAILABLE_MESSAGE);
    }

    #[tokio::test]
    async fn drive_resume_dispatches_to_registered_handle() {
        let server = server_with_handle(false);
        let decision = RunResumeDecision {
            approved: true,
            reason: None,
        };
        let resp = drive_resume(&server, decision, seeded_record("alice@x"), None).await;
        let body = result_value(resp).await;
        assert_eq!(
            body["result"]["resumed"],
            serde_json::Value::Bool(true),
            "approved resume returns the handle's result envelope; got {body}"
        );
    }

    #[tokio::test]
    async fn drive_resume_handle_error_yields_server_error() {
        let server = server_with_handle(true);
        let decision = RunResumeDecision {
            approved: false,
            reason: Some("operator rejected".into()),
        };
        let resp = drive_resume(&server, decision, seeded_record("alice@x"), None).await;
        // Server error envelope, NOT the opaque deny string — the
        // failure is post-authz execution, not an authz refusal.
        assert_eq!(deny_message(resp).await, "resume execution failed");
    }
}