autumn-web 0.9.0

An opinionated, convention-over-configuration web framework for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
//! Project typed Autumn endpoints as [Model Context Protocol][mcp] tools.
//!
//! Autumn already builds a route registry of [`ApiDoc`](crate::openapi::ApiDoc)
//! metadata — handler name, summary/description, and the request-body /
//! `Query` / path-param JSON Schemas — the same data that feeds
//! [`openapi`](crate::openapi). This module *projects* that registry into an
//! MCP server the way `openapi` projects it into an OpenAPI document, so an
//! existing JSON API becomes agent-callable with near-zero new code.
//!
//! What you write:
//!
//! ```ignore
//! #[get("/api/todos")]
//! #[api_doc(mcp, summary = "List todos")]
//! async fn list_todos() -> AutumnResult<Json<Vec<Todo>>> { /* ... */ }
//!
//! autumn_web::app()
//!     .routes(routes![list_todos])
//!     .mount_mcp("/mcp")        // serves a Streamable-HTTP MCP endpoint
//!     .run().await;
//! ```
//!
//! Key properties (issue #1117):
//!
//! * **Opt-in per endpoint** via `#[api_doc(mcp)]`; nothing is exposed
//!   implicitly. A whole-API hatch ([`AppBuilder::expose_all_as_mcp`]) is an
//!   explicit, separate call and still requires opt-in for mutating verbs.
//! * **No second schema.** Each tool's `inputSchema` is derived from the
//!   handler's typed `ApiDoc`, so it cannot drift from the handler.
//! * **Real pipeline.** `tools/call` dispatches through the exact same router
//!   an HTTP request hits, so `#[secured]`, authorization, tenancy, rate
//!   limits, and validation all apply identically.
//! * **Bearer auth reuse.** Agents present an API token via the existing
//!   [`RequireApiToken`](crate::auth::RequireApiToken) surface; the
//!   `Authorization` header is forwarded into the dispatched call.
//!
//! Results are buffered by default. A tool tagged `#[api_doc(mcp, stream)]`
//! (issue #1118) returns an Autumn [`Sse`](crate::sse::Sse) stream that this
//! module projects onto the Streamable-HTTP SSE channel as
//! `notifications/progress` messages terminated by the final `tools/call`
//! result — see `serve_tools_call` / `stream_tool_result`. Streaming is
//! strictly opt-in per tool; the buffered path is unchanged.
//!
//! A tool tagged `#[api_doc(mcp, task)]` supports the MCP Tasks extension
//! (`io.modelcontextprotocol/tasks`). When the client declares the extension,
//! `tools/call` returns a task handle and the tool runs in the background.
//! The client polls `tasks/get`. See the `tasks` submodule.
//!
//! A large app can send a short catalog. `#[api_doc(mcp, core)]` marks a core
//! tool, and [`McpCatalog::Progressive`](crate::mcp::McpCatalog::Progressive)
//! lists only the core tools plus
//! `search_tools` and `call_tool`. See the `catalog` submodule.
//!
//! The endpoint is dual-era. A request with the protocol version in
//! `params._meta` uses revision `2026-07-28`. Other requests use the legacy
//! `initialize` flow. See the `modern` submodule.
//!
//! [`AppBuilder::expose_all_as_mcp`]: crate::app::AppBuilder::expose_all_as_mcp
//!
//! [mcp]: https://modelcontextprotocol.io

#![cfg(feature = "mcp")]

use std::collections::{HashMap, VecDeque};
use std::convert::Infallible;
use std::fmt::Write as _;
use std::pin::Pin;
use std::sync::Arc;

use axum::body::{Body, Bytes};
use axum::http::{HeaderMap, HeaderName, HeaderValue, StatusCode, header};
use axum::response::{IntoResponse, Response};
use futures::{FutureExt as _, Stream, StreamExt as _};
use serde_json::{Value, json};
use tower::ServiceExt as _;

use crate::sse::{Event, Sse};

use crate::openapi::{ApiDoc, SchemaDirection, schema_entry_to_value_in};

mod catalog;
mod modern;
mod tasks;

pub use catalog::McpCatalog;
pub use tasks::McpTaskConfig;

/// Protocol version advertised when a client requests an unsupported one (or
/// none). Also the newest version this server implements.
const DEFAULT_PROTOCOL_VERSION: &str = "2025-06-18";

/// MCP protocol revisions whose semantics this tools-only server honors
/// (results are buffered by default, with opt-in SSE streaming per tool — see
/// [`serve_tools_call`]). A client's requested version is echoed only if it
/// appears here;
/// otherwise the server replies with [`DEFAULT_PROTOCOL_VERSION`] and the
/// client decides whether it can proceed.
const SUPPORTED_PROTOCOL_VERSIONS: &[&str] = &["2025-06-18", "2025-03-26", "2024-11-05"];

/// MCP Streamable-HTTP transport headers a browser client attaches to its
/// JSON-RPC requests, and the x402 `payment-signature` of a paid tool call
/// (forwarded to the priced route). They are always added to the `OPTIONS`
/// preflight's `Access-Control-Allow-Headers` (on top of the app's configured
/// list) so a default CORS config doesn't block the follow-up `POST`. See
/// <https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#protocol-version-header>.
/// `Mcp-Name` and `Mcp-Method` are the routing headers a client sets on
/// `tasks/*` requests (MCP Tasks extension).
const MCP_REQUEST_HEADERS: &[&str] = &[
    "mcp-protocol-version",
    "mcp-session-id",
    "mcp-name",
    "mcp-method",
    "payment-signature",
];

/// Upper bound on a tool's buffered response body (10 MiB). MCP tool results
/// are structured JSON; this guards the in-process dispatch path against a
/// handler that would otherwise buffer an unbounded body into memory.
const MAX_TOOL_RESPONSE_BYTES: usize = 10 * 1024 * 1024;

/// Request headers copied verbatim from the `POST /mcp` envelope onto the
/// in-process request a `tools/call` replays, so the dispatched call
/// authenticates, resolves its tenant, and is rate-limited/deduped exactly as
/// the equivalent direct HTTP request would. (The configured header-based
/// tenant header, whose name is dynamic, is forwarded separately.)
const FORWARDED_HEADERS: &[&str] = &[
    "authorization",
    "cookie",
    "idempotency-key",
    "host",
    "forwarded",
    "x-forwarded-for",
    "x-forwarded-host",
    "x-forwarded-proto",
    "x-real-ip",
    // Locale negotiation: the `Locale` extractor falls back to `Accept-Language`
    // when no locale query/cookie is present, so forward it for the tool result
    // to match the localized data a direct HTTP call would return.
    "accept-language",
    // x402: the payment for a priced route (`[[aeo.paid_routes]]`). Without it
    // a priced tool could only ever answer `402`.
    "payment-signature",
];

/// Response headers copied from the replayed handler response onto the
/// rebuilt `/mcp` response: session and CSRF cookies, and the x402 challenge
/// and settlement receipt of a priced route.
const REPLAYED_RESPONSE_HEADERS: &[&str] = &["set-cookie", "payment-required", "payment-response"];

/// Layer applier for the optional whole-endpoint auth gate (e.g.
/// `RequireApiToken`). Boxed so any `tower::Layer` can be erased; applied to
/// the `/mcp` router before it is merged.
pub(crate) type McpEndpointLayer = Box<
    dyn FnOnce(axum::Router<crate::state::AppState>) -> axum::Router<crate::state::AppState> + Send,
>;

/// Runtime MCP configuration carried from the [`AppBuilder`](crate::app::AppBuilder)
/// through router assembly.
pub struct McpRuntime {
    /// Path the Streamable-HTTP endpoint is mounted at (e.g. `/mcp`).
    pub mount_path: String,
    /// When `true`, every eligible `GET` route is exposed without a
    /// per-endpoint tag (the whole-API hatch). Mutating verbs still require
    /// an explicit `#[api_doc(mcp)]` opt-in, and `#[api_doc(mcp = false)]`
    /// exclusions are always honored.
    pub expose_all: bool,
    /// Optional layer applied to the *entire* `/mcp` endpoint — gating the
    /// catalog (`initialize`/`tools/list`) as well as tool dispatch. Set via
    /// [`AppBuilder::secure_mcp`](crate::app::AppBuilder::secure_mcp).
    pub(crate) endpoint_layer: Option<McpEndpointLayer>,
    /// Settings for task tools (MCP Tasks extension). Set via
    /// [`AppBuilder::mcp_tasks`](crate::app::AppBuilder::mcp_tasks).
    pub(crate) tasks: McpTaskConfig,
    /// The server instructions. Set via
    /// [`AppBuilder::mcp_instructions`](crate::app::AppBuilder::mcp_instructions).
    pub(crate) instructions: Option<String>,
    /// How `tools/list` presents the catalog. Set via
    /// [`AppBuilder::mcp_catalog`](crate::app::AppBuilder::mcp_catalog).
    pub(crate) catalog: McpCatalog,
}

impl McpRuntime {
    /// Create a runtime config for a per-endpoint-opt-in MCP server.
    #[must_use]
    pub fn new(mount_path: impl Into<String>) -> Self {
        Self {
            mount_path: mount_path.into(),
            expose_all: false,
            endpoint_layer: None,
            tasks: McpTaskConfig::default(),
            instructions: None,
            catalog: McpCatalog::Full,
        }
    }
}

/// A single derived MCP tool plus the metadata needed to replay it as an
/// in-process HTTP request.
#[derive(Clone, Debug)]
#[allow(clippy::struct_excessive_bools)] // independent dispatch flags mirroring ApiDoc metadata
struct McpTool {
    name: String,
    description: Option<String>,
    input_schema: Value,
    annotations: Value,
    // ── dispatch metadata ──
    method: String,
    /// Full route path with `{param}` placeholders.
    path_template: String,
    path_params: Vec<String>,
    has_body: bool,
    has_query: bool,
    /// True for a `#[api_doc(mcp, stream)]` tool whose handler returns an
    /// Autumn `Sse` stream, projected onto the Streamable-HTTP SSE channel.
    streams: bool,
    /// True for a tool derived from an empty-body-contract route (declared
    /// 204/205, no response schema). Dispatch enforces the contract by
    /// returning empty text on success, so a route that mislabels its status
    /// (e.g. an HTML handler tagged `status = 204`) can't leak its body into
    /// the tool result.
    empty_body: bool,
    /// True for a `#[api_doc(mcp, task)]` tool. A client that declares the
    /// MCP Tasks extension gets a task handle.
    task: bool,
    /// The handler's build-time authority envelope (#1691), or `None` for an
    /// ungoverned tool. Drives the invocation's audit record and the
    /// reversibility-derived `destructiveHint`.
    agent_authority: Option<&'static crate::agent_authority::AgentAuthority>,
    /// True for a core tool (`#[api_doc(mcp, core)]`).
    core: bool,
    /// The route's `OpenAPI` tags. `search_tools` matches them.
    tags: Vec<String>,
}

impl McpTool {
    /// The JSON object advertised in `tools/list`.
    fn descriptor(&self) -> Value {
        let mut obj = serde_json::Map::new();
        obj.insert("name".into(), json!(self.name));
        if let Some(desc) = &self.description {
            obj.insert("description".into(), json!(desc));
        }
        obj.insert("inputSchema".into(), self.input_schema.clone());
        obj.insert("annotations".into(), self.annotations.clone());
        if self.core {
            obj.insert("_meta".into(), json!({ catalog::ALWAYS_LOAD: true }));
        }
        Value::Object(obj)
    }
}

/// Configuration threaded from router assembly into the MCP endpoint.
pub(crate) struct McpWiring {
    /// The app's CORS config: `allowed_origins` is the cross-origin `Origin`
    /// allowlist; the methods/headers/credentials/max-age fields answer this
    /// endpoint's own `OPTIONS` preflight (it is mounted outside the global
    /// CORS layer, so it must serve preflight for allowlisted browser clients).
    pub cors: crate::config::CorsConfig,
    /// The app's trusted-Host policy, gating the same-origin shortcut.
    pub trusted_hosts: crate::router::TrustedHostPolicy,
    /// Configured tenant header to forward (header-based tenancy), else `None`.
    pub tenant_header: Option<String>,
    /// Configured CSRF token header name (default `x-csrf-token`). Forwarded on
    /// dispatch so a session-authenticated caller passes `CsrfLayer`, which
    /// reads `CsrfConfig::token_header` — not a hard-coded name.
    pub csrf_header: String,
    /// Whether a [`RateLimitLayer`](crate::security::RateLimitLayer) wraps the
    /// `/mcp` envelope (true iff rate limiting is enabled). When set, a
    /// `tools/call` is counted once at the envelope, so its replayed dispatch is
    /// marked [`RateLimitExempt`](crate::security::RateLimitExempt) to avoid
    /// double-counting against the dispatch pipeline's own limiter.
    pub envelope_rate_limited: bool,
    /// Whether a [`LoadShedLayer`](crate::middleware::LoadShedLayer) wraps the
    /// `/mcp` envelope (true iff `server.max_concurrent_requests` is
    /// configured). The dispatch clone (cloned from the already-middleware-
    /// wrapped router) carries the SAME shared layer instance, so a
    /// `tools/call` is counted once at the envelope; its replayed dispatch is
    /// marked [`LoadShedExempt`](crate::middleware::LoadShedExempt) to avoid
    /// consuming a second slot for the same logical request.
    pub envelope_load_shed: bool,
    /// The application state, so `tools/call` can reach the installed
    /// [`AuditLogger`](crate::audit::AuditLogger) and the injected entropy seam
    /// without any per-handler wiring (#1691).
    pub state: crate::state::AppState,
    /// The session cookie name. Its value is part of a task's owner digest.
    pub session_cookie: String,
    /// Settings for task tools.
    pub tasks: McpTaskConfig,
    /// The author's server instructions, if any.
    pub instructions: Option<String>,
    /// How `tools/list` presents the catalog.
    pub catalog: McpCatalog,
}

/// The shared MCP server state attached to the endpoint handler. Holds the
/// derived tool catalog and a clone of the fully-assembled application router
/// to dispatch `tools/call` against.
pub struct McpServer {
    tools: Vec<McpTool>,
    by_name: HashMap<String, usize>,
    /// The real application router (state already applied) — the same path an
    /// HTTP request traverses. `tools/call` replays requests through it.
    dispatch: axum::Router,
    /// The app's CORS config. `cors.allowed_origins` is the cross-origin
    /// `Origin` allowlist (DNS-rebinding protection, per the MCP
    /// Streamable-HTTP spec); a present `Origin` that is neither same-origin
    /// (trusted-host-gated) nor allowlisted is rejected with 403. The remaining
    /// fields answer the endpoint's own `OPTIONS` preflight.
    cors: crate::config::CorsConfig,
    /// The app's trusted-Host policy. The same-origin shortcut only fires when
    /// the request's Host is trusted by this policy, so a DNS-rebinding request
    /// (whose `Origin` and `Host` are both the attacker's domain) cannot bypass
    /// `Origin` validation by Host-match alone — it must still be an explicitly
    /// trusted host, exactly as normal routes require.
    trusted_hosts: crate::router::TrustedHostPolicy,
    /// The configured tenant header name (e.g. `x-tenant-id`) when the app uses
    /// header-based tenancy (`[tenancy] enabled = true, source = "header"`).
    /// `tools/call` forwards this header onto the dispatched request so the
    /// `Tenant` extractor resolves the same tenant a direct HTTP call would.
    /// `None` for any other tenancy source (which keys off headers Autumn
    /// already forwards — `Authorization` for JWT, `Cookie`/Host otherwise).
    tenant_header: Option<String>,
    /// The configured CSRF token header name forwarded on dispatch.
    csrf_header: String,
    /// Whether the `/mcp` envelope is rate-limited; gates exempting the
    /// replayed `tools/call` dispatch from the pipeline limiter.
    envelope_rate_limited: bool,
    /// Whether the `/mcp` envelope is load-shed gated; gates exempting the
    /// replayed `tools/call` dispatch from double-counting against the same
    /// shared `LoadShedLayer` instance.
    envelope_load_shed: bool,
    /// The application state. `tools/call` writes its agent-authority audit
    /// records through this (#1691); an app with no `AuditLogger` installed
    /// makes those writes a no-op, so nothing here is conditional on one.
    state: crate::state::AppState,
    /// The session cookie name. Its value is part of a task's owner digest.
    session_cookie: String,
    /// Tasks created by task tools (MCP Tasks extension).
    tasks: tasks::TaskStore,
    /// True when one or more tools are task tools. Only then does the server
    /// advertise the extension and serve `tasks/*`.
    has_task_tools: bool,
    server_name: String,
    server_version: String,
    /// The server instructions: the author's text and the catalog guidance.
    instructions: Option<String>,
    /// How `tools/list` presents the catalog.
    catalog: McpCatalog,
    /// The `search_tools` and `call_tool` entries. Empty in the full catalog.
    meta_tools: Vec<Value>,
    /// The searchable words of each tool, in catalog order. Empty in the
    /// full catalog.
    search_index: Vec<catalog::ToolWords>,
    /// Enforces each grant's `rate` cap. Per process.
    rate_limiter: crate::agent_authority::rate::RateLimiter,
}

impl McpServer {
    /// Whether a browser `Origin` header value is permitted.
    ///
    /// A same-origin request — one whose `Origin` matches the request's own
    /// host (proxy/scheme-aware) **and** whose host is trusted by the app's
    /// trusted-Host policy — is always allowed: the CORS allowlist governs
    /// *cross*-origin access, and a browser MCP client served by this same
    /// Autumn app should not have to enable CORS for its own origin. The
    /// trusted-Host gate is essential: without it, a DNS-rebinding request
    /// (`Origin: http://attacker.example`, `Host: attacker.example`) would
    /// match by Host alone and defeat the very protection `Origin` validation
    /// exists to provide. Otherwise `*` in the allowlist permits any origin; an
    /// empty allowlist permits none (so any present cross-origin `Origin` is
    /// rejected).
    fn origin_allowed(&self, origin: &str, host: Option<&str>, scheme: Option<&str>) -> bool {
        if let Some(host) = host
            && is_same_origin(origin, host, scheme)
            && crate::router::extract_host_without_port(host)
                .is_some_and(|h| self.trusted_hosts.allows_host(&h.to_ascii_lowercase()))
        {
            return true;
        }
        self.cors
            .allowed_origins
            .iter()
            .any(|allowed| allowed == "*" || allowed == origin)
    }
}

/// Whether `origin` (an `Origin` header value like `https://app.example:8443`)
/// is the same origin as the request's own host.
///
/// The authority (`host[:port]`) must match exactly; when the request's own
/// scheme is known (resolved proxy-aware from `X-Forwarded-Proto`/URI), it must
/// match too. If the scheme is unknown we accept on the authority alone — the
/// host match is what matters for DNS-rebinding protection, and a stricter
/// scheme check would wrongly reject same-origin clients behind a
/// TLS-terminating proxy.
fn is_same_origin(origin: &str, host: &str, scheme: Option<&str>) -> bool {
    let Some((origin_scheme, origin_authority)) = origin.split_once("://") else {
        return false;
    };
    // When the request's own scheme is known, it must match the Origin's.
    if scheme.is_some_and(|s| !s.eq_ignore_ascii_case(origin_scheme)) {
        return false;
    }
    // Compare host + port with default-port normalization, so e.g.
    // `Host: app.example:443` (https) is the same origin as
    // `Origin: https://app.example`. When the request scheme is unknown we
    // assume the Origin's for the host's default-port resolution.
    let host_scheme = scheme.unwrap_or(origin_scheme);
    authority_matches(origin_authority, origin_scheme, host, host_scheme)
}

/// Compare two `host[:port]` authorities for origin equality, treating an
/// omitted port as the scheme's default (443 for https, 80 for http). The host
/// comparison is case-insensitive; IPv6 literals (`[::1]`) are handled.
fn authority_matches(a: &str, a_scheme: &str, b: &str, b_scheme: &str) -> bool {
    let (a_host, a_port) = split_host_port(a);
    let (b_host, b_port) = split_host_port(b);
    if !a_host.eq_ignore_ascii_case(b_host) {
        return false;
    }
    a_port.or_else(|| default_port(a_scheme)) == b_port.or_else(|| default_port(b_scheme))
}

/// Split an authority into its host and optional port. Bracketed IPv6 literals
/// keep their brackets in the host part; a trailing `:digits` is the port.
fn split_host_port(authority: &str) -> (&str, Option<&str>) {
    if authority.starts_with('[') {
        // IPv6: `[::1]` or `[::1]:8080`. The host is everything through `]`.
        if let Some(close) = authority.find(']') {
            let host = &authority[..=close];
            let port = authority[close + 1..]
                .strip_prefix(':')
                .filter(|p| !p.is_empty());
            return (host, port);
        }
        return (authority, None);
    }
    match authority.rsplit_once(':') {
        Some((host, port)) if !port.is_empty() && port.bytes().all(|c| c.is_ascii_digit()) => {
            (host, Some(port))
        }
        _ => (authority, None),
    }
}

/// The default TCP port for a URL scheme, used to normalize authorities.
fn default_port(scheme: &str) -> Option<&'static str> {
    match scheme.to_ascii_lowercase().as_str() {
        "https" => Some("443"),
        "http" => Some("80"),
        _ => None,
    }
}

/// Decide whether a route's `ApiDoc` should be projected as a tool.
///
/// `pub(crate)` for one reason: `agent_authority::manifest` carries an
/// unconditional copy of this rule (it must report the agent surface even when
/// the `mcp` feature is off), and a unit test there pins the copy equal to this
/// original so the two cannot drift.
///
/// Eligibility (JSON-out) gates everything: HTML/Maud routes have no response
/// schema and are silently ineligible. On top of that:
/// * `mcp_exclude` always wins.
/// * an explicit `mcp` opt-in always exposes (any verb).
/// * under the whole-API hatch, un-tagged `GET`s are auto-included but
///   mutating verbs are not.
pub(crate) fn should_expose(doc: &ApiDoc, expose_all: bool) -> bool {
    if doc.hidden || doc.mcp_exclude {
        return false;
    }
    // A streaming tool (`#[api_doc(mcp, stream)]`) returns an `Sse` body, so it
    // has no JSON response schema by nature. It is eligible purely on its
    // explicit opt-in (or the hatch, for a read-only verb), bypassing the
    // JSON-out gate below that would otherwise exclude every schema-less route.
    if doc.mcp_stream {
        if doc.mcp_tool {
            return true;
        }
        return expose_all && is_read_only(doc.method);
    }
    // JSON-out only: a response schema is the structural signal that this is a
    // JSON endpoint rather than an HTML/Maud route.
    //
    // Note this gates on the *response* shape only. The macro infers a request
    // body solely from `Json<T>`, so a route returning `Json<T>` but reading a
    // non-JSON body (`Form<T>`/multipart/`Bytes`/`String`) is indistinguishable
    // here from a legitimately body-less route — both leave `request_body`
    // unset. Such routes are a documented non-target for MCP exposure (see
    // `AppBuilder::mount_mcp`): opting one in yields a tool with no body input.
    // Exception: a status whose body is empty *by contract* (e.g. the
    // repository macro's generated DELETE returning 204) is structurally
    // distinct from an HTML route's schema-less 200-with-body. It stays
    // eligible, and dispatch enforces the empty result (see `call_tool`).
    if doc.response.is_none() && !has_empty_body_contract(doc.success_status) {
        return false;
    }
    if doc.mcp_tool {
        return true;
    }
    if expose_all {
        return is_read_only(doc.method);
    }
    false
}

/// `GET` (and `HEAD`) are read-only; everything else mutates.
fn is_read_only(method: &str) -> bool {
    matches!(method.to_ascii_uppercase().as_str(), "GET" | "HEAD")
}

/// A declared success status whose body is empty *by contract* (RFC 9110):
/// `204 No Content` and `205 Reset Content`. For these, a missing response
/// schema is the deliberate shape of the endpoint, not the signal of an
/// HTML/Maud route. Shared by [`should_expose`] and the warn/skip gate in
/// [`derive_tools`] so the exemption list lives in exactly one place.
const fn has_empty_body_contract(status: u16) -> bool {
    matches!(status, 204 | 205)
}

/// MCP safety annotations for a derived tool.
///
/// `readOnlyHint` is a statement about the HTTP verb and nothing else.
///
/// `destructiveHint` takes the verb as a **floor**, never as a fallback the
/// grant can talk its way under. A declared
/// [`Reversibility`](crate::agent_authority::Reversibility) can only ever *add*
/// the warning: it raises a `POST`/`PATCH` that the verb alone says nothing
/// about, and it cannot clear the one `DELETE` already carries.
///
/// That asymmetry is deliberate. `reversible` means the compiler proved the
/// effect set is bounded writes only — it does **not** mean the application can
/// put the row back, and nothing here checks for soft-delete or versioning. An
/// MCP client skips its confirmation prompt on `destructiveHint: false`, so
/// letting one unproved adjective in a grant clear a `DELETE`'s warning would
/// trade a real signal for an unverified claim (issue #1691 review, P2-1).
fn annotations_for(
    method: &str,
    title: &str,
    authority: Option<&'static crate::agent_authority::AgentAuthority>,
) -> Value {
    use crate::agent_authority::Reversibility;

    let upper = method.to_ascii_uppercase();
    let read_only = is_read_only(&upper);
    let mut obj = serde_json::Map::new();
    obj.insert("title".into(), json!(title));
    obj.insert("readOnlyHint".into(), json!(read_only));
    // DELETE is the destructive verb; flag it so agents/UIs can warn.
    let verb_is_destructive = upper == "DELETE";
    if let Some(authority) = authority {
        let destructive =
            authority.grant.reversibility != Reversibility::Reversible || verb_is_destructive;
        obj.insert("destructiveHint".into(), json!(destructive));
    } else if verb_is_destructive {
        obj.insert("destructiveHint".into(), json!(true));
    }
    Value::Object(obj)
}

/// Build the `inputSchema` for a tool from the handler's typed contract.
///
/// Path params become required string properties, the `Query<T>` extractor
/// becomes a `query` object property, and the JSON request body becomes a
/// `body` property. Named component refs are inlined into `$defs` so the
/// schema is self-contained.
fn build_input_schema(
    doc: &ApiDoc,
    components: &serde_json::Map<String, Value>,
    index: &crate::openapi::SchemaComponentIndex,
) -> Value {
    let mut properties = serde_json::Map::new();
    let mut required: Vec<Value> = Vec::new();
    let mut defs = serde_json::Map::new();

    // Path params, the `Query<T>` extractor, and the JSON body share one flat
    // argument object, keyed by the param name for path params and by the
    // reserved keys `query`/`body` for the other two.
    //
    // KNOWN LIMITATION: a path param literally named `query` or `body` collides
    // with those reserved keys — the inserts below overwrite the path-param
    // property, and `build_request` then feeds the `query`/`body` value to the
    // path slot. Such routes (e.g. `/search/{query}` with a `Query<T>`) are
    // vanishingly rare; the tool they generate is unusable, but the collision is
    // left undisambiguated rather than reshaping the argument contract for every
    // path-param tool.
    for param in doc.path_params {
        // axum catch-all params (`{*rest}`) surface with a leading `*`; clients
        // address them by the bare name, so advertise the stripped name.
        let name = param.strip_prefix('*').unwrap_or(param);
        properties.insert(name.to_owned(), json!({ "type": "string" }));
        required.push(json!(name));
    }

    if let Some(query) = &doc.query_schema {
        let schema = rewrite_refs(
            schema_entry_to_value_in(query, index, SchemaDirection::Request),
            components,
            &mut defs,
        );
        properties.insert("query".to_owned(), schema);
    }

    if let Some(body) = &doc.request_body {
        let schema = rewrite_refs(
            schema_entry_to_value_in(body, index, SchemaDirection::Request),
            components,
            &mut defs,
        );
        properties.insert("body".to_owned(), schema);
        required.push(json!("body"));
    }

    let mut schema = serde_json::Map::new();
    schema.insert("type".into(), json!("object"));
    schema.insert("properties".into(), Value::Object(properties));
    if !required.is_empty() {
        schema.insert("required".into(), Value::Array(required));
    }
    if !defs.is_empty() {
        schema.insert("$defs".into(), Value::Object(defs));
    }
    Value::Object(schema)
}

/// Recursively rewrite `#/components/schemas/X` refs to local `#/$defs/X`
/// refs, pulling each referenced component (resolved from `components`) into
/// `defs` so the resulting schema stands alone.
fn rewrite_refs(
    value: Value,
    components: &serde_json::Map<String, Value>,
    defs: &mut serde_json::Map<String, Value>,
) -> Value {
    match value {
        Value::Object(map) => {
            if let Some(Value::String(reference)) = map.get("$ref")
                && let Some(name) = reference.strip_prefix("#/components/schemas/")
            {
                let name = name.to_owned();
                let local = format!("#/$defs/{name}");
                if !defs.contains_key(&name) {
                    // Insert a placeholder first to break ref cycles, then
                    // resolve the real component schema (if registered).
                    defs.insert(name.clone(), Value::Null);
                    let resolved = components
                        .get(&name)
                        .cloned()
                        .unwrap_or_else(|| json!({ "type": "object", "title": name.clone() }));
                    let resolved = rewrite_refs(resolved, components, defs);
                    defs.insert(name, resolved);
                }
                return json!({ "$ref": local });
            }
            let rewritten: serde_json::Map<String, Value> = map
                .into_iter()
                .map(|(k, v)| (k, rewrite_refs(v, components, defs)))
                .collect();
            Value::Object(rewritten)
        }
        Value::Array(items) => Value::Array(
            items
                .into_iter()
                .map(|v| rewrite_refs(v, components, defs))
                .collect(),
        ),
        other => other,
    }
}

/// A build-time quality problem detected in a tool's derived `inputSchema`.
///
/// Surfaced as `tracing::warn` from [`derive_tools`] (mirroring the existing
/// ineligible-route warning) so an author sees it when assembling `/mcp`,
/// rather than a runtime surprise when an LLM client calls the tool.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum SchemaDegradation {
    /// The `query` property resolved to a bare `{"type":"object"}` placeholder
    /// (the arg type has no `OpenApiSchema`), so the tool advertises no query
    /// fields.
    OpaqueQuery,
    /// The `body` property resolved to a bare `{"type":"object"}` placeholder,
    /// so the tool advertises no body fields.
    OpaqueBody,
}

/// Resolve a schema node through a single `#/$defs/X` indirection (the form
/// [`rewrite_refs`] inlines), returning the node itself when it is not a ref.
fn resolve_local_ref<'a>(root: &'a Value, node: &'a Value) -> &'a Value {
    if let Some(name) = node
        .get("$ref")
        .and_then(Value::as_str)
        .and_then(|r| r.strip_prefix("#/$defs/"))
        && let Some(def) = root.get("$defs").and_then(|defs| defs.get(name))
    {
        return def;
    }
    node
}

/// Inspect a built `inputSchema` for the degradations in [`SchemaDegradation`].
///
/// Pure and self-contained (no logging) so it is unit-testable; [`derive_tools`]
/// turns the results into `tracing::warn` lines with route context.
fn detect_schema_degradations(
    input_schema: &Value,
    has_query: bool,
    has_body: bool,
) -> Vec<SchemaDegradation> {
    let mut out = Vec::new();
    let props = input_schema.get("properties");

    if has_body
        && let Some(body) = props.and_then(|p| p.get("body"))
        && crate::openapi::is_opaque_object_schema(resolve_local_ref(input_schema, body))
    {
        out.push(SchemaDegradation::OpaqueBody);
    }

    // A nested/array query field is NOT a degradation: `Query<T>` decodes the
    // bracketed dialect `build_request` renders it into (issue #1972), so the
    // advertised structure round-trips. Only a missing field-level schema is.
    if has_query
        && let Some(query) = props.and_then(|p| p.get("query"))
        && crate::openapi::is_opaque_object_schema(resolve_local_ref(input_schema, query))
    {
        out.push(SchemaDegradation::OpaqueQuery);
    }

    out
}

/// Emit a `tracing::warn` for each degradation in a tool's derived
/// `inputSchema`, naming the tool and the recommended fix (issue #1972).
fn warn_on_degraded_input_schema(doc: &ApiDoc, input_schema: &Value) {
    for degradation in detect_schema_degradations(
        input_schema,
        doc.query_schema.is_some(),
        doc.request_body.is_some(),
    ) {
        match degradation {
            SchemaDegradation::OpaqueBody => tracing::warn!(
                operation_id = doc.operation_id,
                method = doc.method,
                path = doc.path,
                "MCP tool body has no field-level schema (opaque object); derive or \
                 impl `OpenApiSchema` on the `Json<T>` body type so the tool advertises \
                 its real fields instead of a bare `{{\"type\":\"object\"}}` placeholder"
            ),
            SchemaDegradation::OpaqueQuery => tracing::warn!(
                operation_id = doc.operation_id,
                method = doc.method,
                path = doc.path,
                "MCP tool query has no field-level schema (opaque object); derive or \
                 impl `OpenApiSchema` on the `Query<T>` type so the tool advertises \
                 its real query parameters instead of a bare `{{\"type\":\"object\"}}` placeholder"
            ),
        }
    }
}

/// Derive the tool catalog from collected route docs.
///
/// Emits a build-time `tracing::warn` for any endpoint that opts into MCP but
/// is ineligible (e.g. an HTML/Maud route with no JSON response schema), so it
/// is a logged note rather than a runtime surprise.
#[must_use]
pub fn derive_tools(
    docs: &[ApiDoc],
    expose_all: bool,
    openapi: Option<&crate::openapi::OpenApiConfig>,
) -> Vec<McpToolInfo> {
    // Reuse the OpenAPI generator to resolve component schemas exactly once,
    // so tool input schemas share the handler's typed contract. Crucially,
    // reuse the *app's* OpenApiConfig when present so component schemas the
    // user registered via `OpenApiConfig::register_schema` resolve identically
    // to the served OpenAPI document, instead of drifting to placeholders.
    let refs: Vec<&ApiDoc> = docs.iter().collect();
    let config = openapi.cloned().unwrap_or_else(|| {
        crate::openapi::OpenApiConfig::new("autumn-mcp", env!("CARGO_PKG_VERSION"))
    });
    let spec = crate::openapi::generate_spec(&config, &refs);
    let components = spec
        .components
        .as_ref()
        .map(|c| serde_json::to_value(&c.schemas).unwrap_or(Value::Null))
        .and_then(|v| v.as_object().cloned())
        .unwrap_or_default();
    // Resolve `$ref` component keys through the exact same identity→display-key
    // mapping the OpenAPI generator used, so a tool's inlined `$defs` refs match
    // the served component names even when two types share a last segment
    // (issue #1972).
    let index = crate::openapi::schema_component_index_for(&config, &refs);

    let mut tools = Vec::new();
    let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
    for doc in docs {
        // Surface the "opted in but ineligible" case as a build-time note.
        // Streaming tools legitimately have no JSON response schema, and an
        // empty-body status (204/205) makes the missing schema the route's
        // contract, so both are exempt from this "missing response" warn/skip.
        if (doc.mcp_tool || (expose_all && is_read_only(doc.method)))
            && doc.response.is_none()
            && !has_empty_body_contract(doc.success_status)
            && !doc.mcp_stream
            && !doc.mcp_exclude
            && !doc.hidden
        {
            tracing::warn!(
                operation_id = doc.operation_id,
                method = doc.method,
                path = doc.path,
                "skipping MCP exposure: endpoint has no JSON response schema; \
                 eligible tools return Json<T>, declare an empty-body status \
                 (204/205), or opt in as streaming (`stream`/`Route::mcp_stream`) \
                 — HTML/Maud routes are not eligible"
            );
            continue;
        }
        if !should_expose(doc, expose_all) {
            continue;
        }
        // Tool names (operation ids) must be unique: the same handler mounted
        // under two scoped prefixes, or a reused explicit operation_id, would
        // otherwise advertise a duplicate that dispatch can't disambiguate.
        // Keep the first registration deterministically and warn on the rest.
        if !seen.insert(doc.operation_id) {
            tracing::warn!(
                operation_id = doc.operation_id,
                method = doc.method,
                path = doc.path,
                "duplicate MCP tool name; keeping the first registration and \
                 skipping this duplicate (set a distinct operation_id to expose both)"
            );
            continue;
        }
        let title = doc.summary.unwrap_or(doc.operation_id);
        let input_schema = build_input_schema(doc, &components, &index);
        warn_on_degraded_input_schema(doc, &input_schema);
        tools.push(McpToolInfo {
            name: doc.operation_id.to_owned(),
            description: doc.description.or(doc.summary).map(str::to_owned),
            input_schema,
            annotations: annotations_for(doc.method, title, doc.agent_authority),
            method: doc.method.to_owned(),
            path_template: doc.path.to_owned(),
            path_params: doc.path_params.iter().map(|p| (*p).to_owned()).collect(),
            has_body: doc.request_body.is_some(),
            has_query: doc.query_schema.is_some(),
            streams: doc.mcp_stream,
            empty_body: doc.response.is_none()
                && has_empty_body_contract(doc.success_status)
                && !doc.mcp_stream,
            task: doc.mcp_task,
            agent_authority: doc.agent_authority,
            core: doc.mcp_core,
            tags: doc.tags.iter().map(|tag| (*tag).to_owned()).collect(),
        });
    }
    tools
}

/// Remove each tool that has a meta-tool name, in progressive mode only.
/// The router calls it before the server and the AEO documents read the
/// tools.
pub(crate) fn drop_reserved_tools(tools: Vec<McpToolInfo>, mode: McpCatalog) -> Vec<McpToolInfo> {
    catalog::drop_reserved(tools, mode)
}

/// Public, transport-agnostic description of a derived tool. Returned by
/// [`derive_tools`] and consumed by the framework when assembling the MCP
/// endpoint router.
#[derive(Clone, Debug)]
#[allow(clippy::struct_excessive_bools)] // independent dispatch flags mirroring ApiDoc metadata
pub struct McpToolInfo {
    name: String,
    description: Option<String>,
    input_schema: Value,
    annotations: Value,
    method: String,
    path_template: String,
    path_params: Vec<String>,
    has_body: bool,
    has_query: bool,
    streams: bool,
    empty_body: bool,
    task: bool,
    agent_authority: Option<&'static crate::agent_authority::AgentAuthority>,
    core: bool,
    tags: Vec<String>,
}

impl McpToolInfo {
    /// Tool name advertised in `tools/list` (the route's operation id).
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Human-readable description derived from the route's
    /// `description`/`summary`.
    #[must_use]
    pub fn description(&self) -> Option<&str> {
        self.description.as_deref()
    }

    /// JSON Schema for the tool's arguments, built from the handler's typed
    /// contract (path params, query, JSON body).
    #[must_use]
    pub const fn input_schema(&self) -> &Value {
        &self.input_schema
    }

    /// MCP safety annotations (`readOnlyHint`, `destructiveHint`, `title`)
    /// derived from the HTTP verb.
    #[must_use]
    pub const fn annotations(&self) -> &Value {
        &self.annotations
    }

    /// HTTP method the tool dispatches with.
    #[must_use]
    pub fn method(&self) -> &str {
        &self.method
    }

    /// Route path template the tool dispatches to (e.g. `/api/todos/{id}`).
    #[must_use]
    pub fn path_template(&self) -> &str {
        &self.path_template
    }

    /// Path parameter names, in template order. A catch-all keeps its `*`.
    #[must_use]
    pub fn path_params(&self) -> &[String] {
        &self.path_params
    }

    /// Whether the tool sends a JSON body (the `body` argument).
    #[must_use]
    pub const fn has_body(&self) -> bool {
        self.has_body
    }

    /// Whether the tool sends a query string (the `query` argument).
    #[must_use]
    pub const fn has_query(&self) -> bool {
        self.has_query
    }

    /// Whether this is a streaming (`Sse`) tool.
    #[must_use]
    pub const fn streams(&self) -> bool {
        self.streams
    }

    /// Whether this is a task tool (`#[api_doc(mcp, task)]`).
    #[must_use]
    pub const fn supports_tasks(&self) -> bool {
        self.task
    }

    /// Whether this is a core tool (`#[api_doc(mcp, core)]`).
    #[must_use]
    pub const fn is_core(&self) -> bool {
        self.core
    }

    /// The build-time authority envelope proved for the handler behind this
    /// tool by `#[agent_operable(grant = ...)]` (issue #1691), or `None` for an
    /// **ungoverned** tool — one exposed to agents with no grant declared.
    ///
    /// Copied verbatim from [`ApiDoc::agent_authority`], so a tool is governed
    /// exactly when its handler is. `tools/call` reads it to record the
    /// compile-known grant and reversibility on the invocation's audit events,
    /// and the manifest reads it to tell `actions` from `ungoverned_tools`.
    #[must_use]
    pub const fn agent_authority(&self) -> Option<&'static crate::agent_authority::AgentAuthority> {
        self.agent_authority
    }
}

impl McpServer {
    /// Assemble the server state from derived tools, a dispatch router, and the
    /// router-supplied [`McpWiring`] (CORS, trusted hosts, tenant/CSRF headers).
    #[must_use]
    pub(crate) fn new(tools: Vec<McpToolInfo>, dispatch: axum::Router, wiring: McpWiring) -> Self {
        let progressive = wiring.catalog == McpCatalog::Progressive;
        // The router already removed a tool with a meta-tool name. A direct
        // caller of this function gets the same filter.
        let tools: Vec<McpTool> = catalog::drop_reserved(tools, wiring.catalog)
            .into_iter()
            .map(|t| McpTool {
                name: t.name,
                description: t.description,
                input_schema: t.input_schema,
                annotations: t.annotations,
                method: t.method,
                path_template: t.path_template,
                path_params: t.path_params,
                has_body: t.has_body,
                has_query: t.has_query,
                streams: t.streams,
                empty_body: t.empty_body,
                task: t.task,
                agent_authority: t.agent_authority,
                core: t.core,
                tags: t.tags,
            })
            .collect();
        let (meta_tools, search_index) = if progressive {
            (catalog::meta_descriptors(&tools), catalog::index(&tools))
        } else {
            (Vec::new(), Vec::new())
        };
        let has_task_tools = tools.iter().any(|t| t.task);
        let by_name = tools
            .iter()
            .enumerate()
            .map(|(i, t)| (t.name.clone(), i))
            .collect();
        Self {
            tools,
            by_name,
            dispatch,
            cors: wiring.cors,
            trusted_hosts: wiring.trusted_hosts,
            tenant_header: wiring.tenant_header,
            csrf_header: wiring.csrf_header,
            envelope_rate_limited: wiring.envelope_rate_limited,
            envelope_load_shed: wiring.envelope_load_shed,
            state: wiring.state,
            session_cookie: wiring.session_cookie,
            tasks: tasks::TaskStore::new(wiring.tasks),
            has_task_tools,
            server_name: "autumn-mcp".to_owned(),
            server_version: env!("CARGO_PKG_VERSION").to_owned(),
            instructions: catalog::instructions(wiring.instructions.as_deref(), wiring.catalog),
            catalog: wiring.catalog,
            meta_tools,
            search_index,
            rate_limiter: crate::agent_authority::rate::RateLimiter::default(),
        }
    }
}

/// Build an axum sub-router serving the MCP endpoint at `mount_path`.
///
/// `dispatch` must be the fully-assembled application router (state applied)
/// so `tools/call` traverses the real handler pipeline. `wiring` carries the
/// CORS config (cross-origin `Origin` allowlist + preflight settings), the
/// trusted-Host policy gating the same-origin shortcut, and the tenant/CSRF
/// header names forwarded on dispatch.
pub(crate) fn build_mcp_router(
    mount_path: &str,
    tools: Vec<McpToolInfo>,
    dispatch: axum::Router,
    wiring: McpWiring,
    endpoint_layer: Option<McpEndpointLayer>,
) -> axum::Router<crate::state::AppState> {
    let server = Arc::new(McpServer::new(tools, dispatch, wiring));
    tracing::debug!(
        path = mount_path,
        tools = server.tools.len(),
        "Mounted MCP endpoint"
    );
    // The JSON-RPC surface (GET probe + POST) carries the optional whole-endpoint
    // auth gate (`secure_mcp`). `OPTIONS` is deliberately mounted on a *separate*
    // sub-router so the auth layer never wraps it: a CORS preflight is sent
    // unauthenticated by the browser, so gating it would 401 the preflight and
    // the real POST would never fire. Disjoint methods on the same path merge
    // into one `MethodRouter` without overlap.
    let mut rpc = axum::Router::<crate::state::AppState>::new()
        .route(
            mount_path,
            axum::routing::get(serve_mcp_get).post(serve_mcp),
        )
        .layer(axum::extract::Extension(Arc::clone(&server)));
    if let Some(layer_fn) = endpoint_layer {
        rpc = layer_fn(rpc);
    }
    // Host/Origin gate, applied outermost on the JSON-RPC surface so an
    // untrusted Host or disallowed Origin is rejected before the optional auth
    // gate runs and before `serve_mcp` buffers the body (see
    // `mcp_host_origin_guard`). Mounted only on `rpc`, not the `OPTIONS`
    // preflight below, which a browser sends unauthenticated and host-agnostic.
    let guard_server = Arc::clone(&server);
    rpc = rpc.layer(axum::middleware::from_fn(move |req, next| {
        mcp_host_origin_guard(Arc::clone(&guard_server), req, next)
    }));
    let preflight = axum::Router::<crate::state::AppState>::new()
        .route(mount_path, axum::routing::options(serve_mcp_options))
        .layer(axum::extract::Extension(server));
    rpc.merge(preflight)
}

/// Wrap a fully-assembled MCP envelope so **every** response carries the CORS
/// grant — including ones produced by outer layers *before* `serve_mcp` runs:
/// `secure_mcp` auth rejections (401/403), the request-body limit (413), and
/// rate limiting (429). Applied as the outermost layer so it sees the final
/// response regardless of which inner layer produced it; without it an
/// allowlisted browser client's preflight succeeds but the rejection is masked
/// as an opaque CORS failure instead of surfacing the real status. The grant is
/// only added for allowlisted origins (see [`apply_cors_headers`]).
pub(crate) fn apply_mcp_cors_layer(
    router: axum::Router<crate::state::AppState>,
    cors: &crate::config::CorsConfig,
) -> axum::Router<crate::state::AppState> {
    let cors = cors.clone();
    router.layer(axum::middleware::from_fn(
        move |req: axum::extract::Request, next: axum::middleware::Next| {
            let cors = cors.clone();
            async move {
                let origin = req
                    .headers()
                    .get(header::ORIGIN)
                    .and_then(|v| v.to_str().ok())
                    .map(str::to_owned);
                let mut response = next.run(req).await;
                apply_cors_headers(&cors, origin.as_deref(), &mut response);
                response
            }
        },
    ))
}

/// Answer a CORS preflight (`OPTIONS`) for the MCP endpoint. Because the
/// endpoint is mounted outside the global CORS layer, an allowlisted browser
/// MCP client's preflight would otherwise get no `Access-Control-Allow-*`
/// headers and the browser would block the real `POST`. We reuse the app's CORS
/// config to answer it: only an explicitly allowlisted `Origin` (or `*`) gets
/// the allow headers; anything else gets a bare `204` with no CORS grant.
async fn serve_mcp_options(
    axum::extract::Extension(server): axum::extract::Extension<Arc<McpServer>>,
    headers: HeaderMap,
) -> Response {
    use axum::http::HeaderValue;

    let cors = &server.cors;
    let mut out = HeaderMap::new();
    // `Vary: Origin` since the response depends on the request Origin.
    out.insert(header::VARY, HeaderValue::from_static("origin"));

    let origin = headers.get(header::ORIGIN).and_then(|o| o.to_str().ok());

    // No Origin (non-CORS probe) or a non-allowlisted origin: advertise the
    // allowed methods but grant no cross-origin access.
    let Some(allow_origin) = cors_allow_origin(cors, origin) else {
        out.insert(
            header::ALLOW,
            HeaderValue::from_static("GET, POST, OPTIONS"),
        );
        return (StatusCode::NO_CONTENT, out).into_response();
    };

    if let Ok(v) = HeaderValue::from_str(&allow_origin) {
        out.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, v);
    }
    if let Ok(v) = HeaderValue::from_str(&cors.allowed_methods.join(", ")) {
        out.insert(header::ACCESS_CONTROL_ALLOW_METHODS, v);
    }
    // Mirror the app's configured allow-headers, but always include the MCP
    // Streamable-HTTP transport headers a browser client sends on follow-up
    // requests (`MCP-Protocol-Version`, and `Mcp-Session-Id` for stateful
    // clients). The default `allowed_headers` (`Content-Type, Authorization`)
    // omits them, which would otherwise make the browser block the POST.
    let mut allow_headers = cors.allowed_headers.clone();
    for extra in MCP_REQUEST_HEADERS {
        if !allow_headers.iter().any(|h| h.eq_ignore_ascii_case(extra)) {
            allow_headers.push((*extra).to_owned());
        }
    }
    if let Ok(v) = HeaderValue::from_str(&allow_headers.join(", ")) {
        out.insert(header::ACCESS_CONTROL_ALLOW_HEADERS, v);
    }
    if let Ok(v) = HeaderValue::from_str(&cors.max_age_secs.to_string()) {
        out.insert(header::ACCESS_CONTROL_MAX_AGE, v);
    }
    if cors.allow_credentials {
        out.insert(
            header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
            HeaderValue::from_static("true"),
        );
    }
    (StatusCode::NO_CONTENT, out).into_response()
}

/// Compute the `Access-Control-Allow-Origin` value to grant a request from
/// `origin`, mirroring the preflight's allowlist logic. Returns `None` when no
/// `Origin` is present or it is not allowlisted (a same-origin browser request
/// needs no CORS grant). With credentials the spec forbids `*`, so the concrete
/// origin is echoed instead.
fn cors_allow_origin(cors: &crate::config::CorsConfig, origin: Option<&str>) -> Option<String> {
    let origin = origin?;
    let allow_any = cors.allowed_origins.iter().any(|a| a == "*");
    if !(allow_any || cors.allowed_origins.iter().any(|a| a == origin)) {
        return None;
    }
    Some(if allow_any && !cors.allow_credentials {
        "*".to_owned()
    } else {
        origin.to_owned()
    })
}

/// Attach the actual-request CORS grant to a response. The MCP endpoint is
/// mounted outside the global CORS layer, so without this an allowlisted
/// browser client's preflight would pass but the browser would still block
/// reading the `POST`/`GET` body for lack of `Access-Control-Allow-Origin`.
fn apply_cors_headers(
    cors: &crate::config::CorsConfig,
    origin: Option<&str>,
    response: &mut Response,
) {
    use axum::http::HeaderValue;
    let headers = response.headers_mut();
    // The response varies by `Origin` whenever an origin is in play.
    headers.insert(header::VARY, HeaderValue::from_static("origin"));
    if let Some(allow_origin) = cors_allow_origin(cors, origin)
        && let Ok(v) = HeaderValue::from_str(&allow_origin)
    {
        headers.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, v);
        if cors.allow_credentials {
            headers.insert(
                header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
                HeaderValue::from_static("true"),
            );
        }
    }
}

/// MCP over Streamable HTTP: a `GET` opens a *server-initiated* stream (for
/// unsolicited server→client messages). Autumn only streams *in response to a
/// `tools/call`* — a streaming tool's SSE rides the POST response (see
/// [`serve_tools_call`]) — so there is nothing to serve on a bare `GET`, and we
/// decline it per spec.
async fn serve_mcp_get() -> Response {
    (
        StatusCode::METHOD_NOT_ALLOWED,
        [(header::ALLOW, "POST")],
        "MCP server-initiated streaming is not supported (POST JSON-RPC only)",
    )
        .into_response()
}

/// Per-request context threaded into a replayed `tools/call` so the in-process
/// dispatch sees the same client identity a direct HTTP request would: the
/// caller's headers, the proxy-resolved client identity, and the connection
/// peer address (for the IP-keyed rate limiter).
/// Header name for the `Server-Timing` response header (#1348), forwarded from
/// the dispatch clone onto the rebuilt JSON-RPC response.
static SERVER_TIMING: HeaderName = HeaderName::from_static("server-timing");

struct ReplayContext<'a> {
    headers: &'a HeaderMap,
    identity: Option<&'a crate::security::ResolvedClientIdentity>,
    peer: Option<std::net::SocketAddr>,
    /// The envelope's load-shed admission. A shed replay marks it, so the
    /// envelope gives no limiter sample.
    envelope_admission: Option<crate::middleware::EnvelopeAdmission>,
    /// The verified mTLS client identity of the connection the `/mcp` envelope
    /// arrived on (#1640), when there is one.
    #[cfg(feature = "tls")]
    client_cert: Option<std::sync::Arc<crate::tls::client_auth::ClientIdentity>>,
    /// True for a request in the modern era (protocol `2026-07-28`). Its
    /// results get `resultType` and `_meta.serverInfo`.
    modern: bool,
}

/// Reject an untrusted `Host`/`:authority` or a disallowed browser `Origin`
/// before the request body is buffered.
///
/// The `/mcp` envelope is merged after `apply_middleware`, so it does not pass
/// through the global `TrustedHostLayer` in [`crate::router`] that every direct
/// route runs; this layer restores that gate for the endpoint. Running as a
/// layer (rather than inside `serve_mcp`) means a bad-`Host` request is rejected
/// before the handler's `Bytes` extractor reads up to the configured
/// `max_request_size_bytes`, exactly as a direct route rejects in middleware
/// before handler extraction.
///
/// Host resolution mirrors `TrustedHostService`: the proxy-resolved
/// identity first (honouring `X-Forwarded-Host` from trusted upstreams), then
/// the HTTP/2 `:authority` carried in the request URI, then the `Host` header —
/// so an HTTP/2 client that sends `:authority` without a `Host` header is not
/// wrongly rejected as missing-host. The same proxy-resolved host drives the
/// same-origin `Origin` shortcut, so a same-origin client behind a
/// TLS-terminating proxy isn't 403'd.
async fn mcp_host_origin_guard(
    server: Arc<McpServer>,
    req: axum::extract::Request,
    next: axum::middleware::Next,
) -> Response {
    let identity = req
        .extensions()
        .get::<crate::security::ResolvedClientIdentity>();
    let host = identity
        .and_then(|id| id.host.as_deref())
        .or_else(|| req.uri().authority().map(http::uri::Authority::as_str))
        .or_else(|| {
            req.headers()
                .get(header::HOST)
                .and_then(|h| h.to_str().ok())
        });

    // Trusted-Host enforcement. Without it, because the DNS-rebinding `Origin`
    // check below only fires for browsers, a no-`Origin` agent could call
    // `initialize`/`tools/list` with an arbitrary `Host` and enumerate the tool
    // catalog — even though the same request to a direct route would be rejected.
    let host_trusted = host
        .and_then(crate::router::extract_host_without_port)
        .map(|h| h.trim_end_matches('.').to_ascii_lowercase())
        .filter(|h| !h.is_empty())
        .map_or_else(
            || server.trusted_hosts.allows_missing_host(),
            |h| server.trusted_hosts.allows_host(&h),
        );
    if !host_trusted {
        return (StatusCode::BAD_REQUEST, "Invalid Host header").into_response();
    }

    // DNS-rebinding protection (MCP Streamable-HTTP spec MUST): reject a
    // browser-supplied `Origin` that is neither same-origin nor allowlisted.
    // Non-browser agents send no `Origin` and are unaffected.
    if let Some(origin) = req.headers().get(header::ORIGIN) {
        let origin = origin.to_str().unwrap_or("");
        let scheme = identity.and_then(|id| id.scheme.as_deref());
        if !server.origin_allowed(origin, host, scheme) {
            return (StatusCode::FORBIDDEN, "origin not allowed").into_response();
        }
    }

    next.run(req).await
}

/// The Streamable-HTTP POST handler: parses one JSON-RPC message (or a batch)
/// and responds with `application/json`.
async fn serve_mcp(
    axum::extract::Extension(server): axum::extract::Extension<Arc<McpServer>>,
    identity: Option<axum::extract::Extension<crate::security::ResolvedClientIdentity>>,
    // The connection peer is stored as a `ConnectInfo<SocketAddr>` request
    // extension by axum's connect-info make-service; read it via `Extension`
    // (which is optional-friendly) rather than the `ConnectInfo` extractor.
    connect_info: Option<
        axum::extract::Extension<axum::extract::ConnectInfo<std::net::SocketAddr>>,
    >,
    // The verified mTLS client identity of this connection (#1640), stamped by
    // `ClientIdentityLayer`. Read as an `Extension` for the same
    // optional-friendly reason `connect_info` is.
    #[cfg(feature = "tls")] client_cert: Option<
        axum::extract::Extension<std::sync::Arc<crate::tls::client_auth::ClientIdentity>>,
    >,
    envelope_admission: Option<axum::extract::Extension<crate::middleware::EnvelopeAdmission>>,
    headers: HeaderMap,
    body: Bytes,
) -> Response {
    let identity = identity.as_ref().map(|ext| &ext.0);
    #[cfg(feature = "tls")]
    let client_cert = client_cert.map(|ext| ext.0);

    // Capture the request `Origin` (if any) so the actual JSON-RPC response can
    // carry the matching CORS grant, mirroring the `OPTIONS` preflight.
    let origin = headers
        .get(header::ORIGIN)
        .and_then(|o| o.to_str().ok())
        .map(str::to_owned);

    // Trusted-Host enforcement and DNS-rebinding `Origin` validation run in the
    // `mcp_host_origin_guard` layer (applied in `build_mcp_router`) rather than
    // here, so an untrusted Host or disallowed Origin is rejected *before* this
    // handler buffers `body` up to the configured `max_request_size_bytes` —
    // mirroring how direct routes reject in `TrustedHostService` before
    // handler extraction.
    let parsed: Value = match serde_json::from_slice(&body) {
        Ok(v) => v,
        Err(e) => {
            if modern::header_is_modern(&headers) {
                let rejection = modern::parse_error(&e.to_string());
                let mut response = json_response(&rejection.body);
                *response.status_mut() = rejection.status;
                return response;
            }
            return json_response(&parse_error(&e.to_string()));
        }
    };

    // A request with the modern `_meta` fields uses protocol `2026-07-28`.
    // Other requests use the legacy flow and its version header check.
    let modern = modern::wants_modern(&headers, &parsed);
    if !modern && let Some(rejection) = reject_unsupported_protocol_version(&headers, &parsed) {
        return rejection;
    }

    let ctx = ReplayContext {
        headers: &headers,
        identity,
        peer: connect_info.map(|ext| (ext.0).0),
        envelope_admission: envelope_admission.map(|ext| ext.0),
        #[cfg(feature = "tls")]
        client_cert,
        modern,
    };

    let mut response = if modern {
        serve_modern(&server, &ctx, parsed).await
    } else {
        serve_legacy(&server, &ctx, parsed).await
    };

    // The endpoint sits outside the global CORS layer, so an allowlisted
    // browser client needs the grant on the actual response to read the body.
    apply_cors_headers(&server.cors, origin.as_deref(), &mut response);
    response
}

/// Serve a legacy request: one JSON-RPC message or a batch, after an
/// `initialize` handshake (protocol `2025-06-18` and earlier).
async fn serve_legacy(server: &Arc<McpServer>, ctx: &ReplayContext<'_>, parsed: Value) -> Response {
    match parsed {
        // JSON-RPC 2.0: an empty batch is itself an Invalid Request.
        Value::Array(batch) if batch.is_empty() => {
            json_response(&error(Value::Null, -32600, "Invalid Request: empty batch"))
        }
        // A batch carrying a `tools/call` is refused outright. Batching would
        // let one envelope amplify two budgets a sequence of direct HTTP calls
        // can't: memory (each replayed call buffers up to
        // `MAX_TOOL_RESPONSE_BYTES`, and every response object is retained in
        // `out` until the whole batch serializes) and rate limiting (the
        // envelope is counted once, so each replayed call below would carry
        // `RateLimitExempt` and skip the per-route limiter). The newest protocol
        // revision dropped JSON-RPC batching entirely, so no conformant client
        // batches calls; rejecting here keeps `tools/call` a single-message
        // request — where the per-call limiter and the 10 MiB cap both still
        // apply. Harmless metadata methods (initialize/tools/list/ping) may
        // still be batched. The server also refuses `tasks/*` in a batch. The
        // owner check reads the request context. Only a single request has it.
        Value::Array(batch)
            if batch.iter().any(|msg| {
                msg.get("method")
                    .and_then(Value::as_str)
                    .is_some_and(|m| m == "tools/call" || is_task_method(m))
            }) =>
        {
            json_response(&error(
                Value::Null,
                -32600,
                "Invalid Request: batched tools/call or tasks/* is not supported; \
                 send each one as a single JSON-RPC request",
            ))
        }
        Value::Array(batch) => {
            let mut out = Vec::new();
            for msg in batch {
                // Only metadata methods reach here (a batched `tools/call` is
                // rejected above), so none set a `Set-Cookie`.
                if let Some(resp) = handle_message(server, &msg) {
                    out.push(resp);
                }
            }
            // An all-notification batch produces no responses → empty 202.
            if out.is_empty() {
                StatusCode::ACCEPTED.into_response()
            } else {
                json_response(&Value::Array(out))
            }
        }
        // A single request object. A `tools/call` is dispatched through a path
        // that can answer with the Streamable-HTTP SSE channel (a streaming
        // tool) or buffered JSON; everything else (initialize/tools/list/ping)
        // is buffered. A notification (no `id`) yields `None` → 202.
        msg @ Value::Object(_) => {
            if let Some((id, params)) = single_request(&msg, "tools/call") {
                serve_tools_call(server, ctx, id, params).await
            } else if let Some((method, id, params)) = single_task_request(&msg) {
                json_response(&serve_task_method(server, ctx, &method, id, &params))
            } else {
                handle_message(server, &msg).map_or_else(
                    || StatusCode::ACCEPTED.into_response(),
                    |v| json_response(&v),
                )
            }
        }
        // Anything else (scalar, null) is not a valid JSON-RPC message.
        _ => json_response(&error(
            Value::Null,
            -32600,
            "Invalid Request: expected a JSON object or array",
        )),
    }
}

/// Serve a modern request (protocol `2026-07-28`). Each POST carries one
/// message, with its version and client capabilities in `_meta`.
async fn serve_modern(server: &Arc<McpServer>, ctx: &ReplayContext<'_>, parsed: Value) -> Response {
    let reply = |status: StatusCode, mut message: Value| {
        modern::stamp(&mut message, &server.server_info());
        let mut response = json_response(&message);
        *response.status_mut() = status;
        response
    };
    let rejected = |rejection: modern::Rejection| reply(rejection.status, rejection.body);

    if parsed.is_array() {
        return rejected(modern::batch_rejection());
    }
    // This revision defines no client notifications over HTTP. Accept one
    // and send no body, as the transport requires.
    if modern::is_notification(&parsed) {
        return StatusCode::ACCEPTED.into_response();
    }
    if let Err(rejection) = modern::validate(ctx.headers, &parsed, |m| server.serves(m)) {
        return rejected(rejection);
    }
    let id = parsed.get("id").cloned().unwrap_or(Value::Null);
    let method = parsed.get("method").and_then(Value::as_str).unwrap_or("");
    let params = parsed.get("params").cloned().unwrap_or(Value::Null);
    match method {
        "server/discover" => reply(StatusCode::OK, success(id, discover_result(server))),
        "tools/list" => {
            let mut result = tools_list_result(server);
            modern::add_cache_hints(&mut result);
            reply(StatusCode::OK, success(id, result))
        }
        "tools/call" => serve_tools_call(server, ctx, id, params).await,
        m if is_task_method(m) => {
            let message = serve_task_method(server, ctx, m, id, &params);
            reply(modern::status_for(&message), message)
        }
        other => rejected(modern::method_not_found(id, other)),
    }
}

/// Enforce the Streamable-HTTP `MCP-Protocol-Version` header. Returns a 400
/// response when a non-`initialize` request carries an unsupported version —
/// otherwise a future client (e.g. a `2025-11-25` one) could run `tools/call`
/// under semantics this server never negotiated. A missing header means "assume
/// the pre-header default" (2025-03-26), which this server supports, so absence
/// is allowed. The `initialize` handshake is exempt: that is where the version
/// is negotiated (in the body), so pre-validating its header would make
/// negotiating a newer client down to a supported version impossible.
fn reject_unsupported_protocol_version(headers: &HeaderMap, parsed: &Value) -> Option<Response> {
    let is_initialize = parsed
        .as_object()
        .and_then(|o| o.get("method"))
        .and_then(Value::as_str)
        == Some("initialize");
    if is_initialize {
        return None;
    }
    let version = headers.get("mcp-protocol-version")?.to_str().unwrap_or("");
    if SUPPORTED_PROTOCOL_VERSIONS.contains(&version) {
        return None;
    }
    Some(
        (
            StatusCode::BAD_REQUEST,
            format!("unsupported MCP-Protocol-Version: {version}"),
        )
            .into_response(),
    )
}

/// Handle a single buffered JSON-RPC message (everything except `tools/call`,
/// which [`serve_tools_call`] handles so it can stream). Returns `None` only
/// for a *valid* notification (a `2.0` message with a `method` and no `id`).
fn handle_message(server: &McpServer, msg: &Value) -> Option<Value> {
    let id = msg.get("id").cloned();

    // A JSON-RPC 2.0 `id`, when present, must be a string, number, or null;
    // an object/array id is invalid and must not reach dispatch.
    let id_ok = id
        .as_ref()
        .is_none_or(|v| v.is_string() || v.is_number() || v.is_null());

    // Reject anything that isn't a well-formed JSON-RPC 2.0 request/notification
    // object (e.g. `5`, `{}`, a message missing `jsonrpc`/`method`, or one with
    // a structured `id`). A bare notification-shaped-but-invalid item must still
    // produce an error rather than being silently swallowed.
    let is_valid = msg.is_object()
        && msg.get("jsonrpc").and_then(Value::as_str) == Some("2.0")
        && msg.get("method").and_then(Value::as_str).is_some()
        && id_ok;
    if !is_valid {
        // Echo the id only when it is a usable string/number; otherwise (missing
        // or structurally invalid) the spec requires `id: null`.
        let err_id = match &id {
            Some(v) if v.is_string() || v.is_number() => v.clone(),
            _ => Value::Null,
        };
        return Some(error(err_id, -32600, "Invalid Request"));
    }

    // A valid notification (method present, no `id`) gets no response.
    let id = id?;
    let method = msg.get("method").and_then(Value::as_str).unwrap_or("");
    let params = msg.get("params").cloned().unwrap_or(Value::Null);

    let result = match method {
        "initialize" => Ok(initialize_result(server, &params)),
        "ping" => Ok(json!({})),
        "tools/list" => Ok(tools_list_result(server)),
        // A single `tools/call` is diverted to `serve_tools_call` before reaching
        // here, and a batched one is rejected upstream; this arm is defensive.
        "tools/call" => Err((
            -32600,
            "tools/call must be sent as a single JSON-RPC request".to_owned(),
        )),
        other => Err((-32601, format!("method not found: {other}"))),
    };

    Some(match result {
        Ok(value) => success(id, value),
        Err((code, message)) => error(id, code, &message),
    })
}

impl McpServer {
    /// The server capabilities. The tasks extension is listed only when a
    /// task tool exists.
    fn capabilities(&self) -> Value {
        let mut capabilities = json!({ "tools": { "listChanged": false } });
        if self.has_task_tools {
            capabilities["extensions"] = json!({ tasks::EXTENSION_ID: {} });
        }
        capabilities
    }

    /// Whether a modern request for `method` is served. Others get `-32601`.
    fn serves(&self, method: &str) -> bool {
        matches!(method, "server/discover" | "tools/list" | "tools/call")
            || (is_task_method(method) && self.has_task_tools)
    }

    /// The server name and version (an MCP `Implementation`).
    fn server_info(&self) -> Value {
        json!({ "name": self.server_name, "version": self.server_version })
    }
}

/// The `server/discover` result (protocol `2026-07-28`).
fn discover_result(server: &McpServer) -> Value {
    let mut result = json!({
        "supportedVersions": modern::VERSIONS,
        "capabilities": server.capabilities(),
    });
    if let Some(text) = &server.instructions {
        result["instructions"] = json!(text);
    }
    modern::add_cache_hints(&mut result);
    result
}

fn initialize_result(server: &McpServer, params: &Value) -> Value {
    // Echo the client's requested version only if we actually implement it;
    // otherwise advertise our newest supported version (MCP negotiation).
    let protocol = match params.get("protocolVersion").and_then(Value::as_str) {
        Some(requested) if SUPPORTED_PROTOCOL_VERSIONS.contains(&requested) => requested,
        _ => DEFAULT_PROTOCOL_VERSION,
    };
    let mut result = json!({
        "protocolVersion": protocol,
        "capabilities": server.capabilities(),
        "serverInfo": {
            "name": server.server_name,
            "version": server.server_version,
        },
    });
    if let Some(text) = &server.instructions {
        result["instructions"] = json!(text);
    }
    result
}

/// The `tools/list` result. The full catalog lists every tool. The
/// progressive catalog lists the meta-tools, then the core tools.
fn tools_list_result(server: &McpServer) -> Value {
    let tools: Vec<Value> = match server.catalog {
        McpCatalog::Progressive => server
            .meta_tools
            .iter()
            .cloned()
            .chain(
                server
                    .tools
                    .iter()
                    .filter(|t| t.core)
                    .map(McpTool::descriptor),
            )
            .collect(),
        McpCatalog::Full => server.tools.iter().map(McpTool::descriptor).collect(),
    };
    json!({ "tools": tools })
}

/// Whether `msg` is a well-formed single request for `method` (JSON-RPC 2.0
/// object, with a usable `id`). Returns the cloned
/// `id` and `params`. A `tools/call` is handled apart from [`handle_message`]
/// so its (possibly streaming) result can ride the Streamable-HTTP SSE channel.
///
/// A malformed one (bad `jsonrpc`/`id`) returns `None` and falls through to
/// [`handle_message`], which produces the standard `-32600` error; a
/// `tools/call` *notification* (no `id`) likewise falls through and is treated
/// as a no-op notification (`202`), matching the pre-streaming behavior.
fn single_request(msg: &Value, method: &str) -> Option<(Value, Value)> {
    let obj = msg.as_object()?;
    if obj.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
        return None;
    }
    if obj.get("method").and_then(Value::as_str) != Some(method) {
        return None;
    }
    let id = obj.get("id")?;
    if !(id.is_string() || id.is_number() || id.is_null()) {
        return None;
    }
    let params = obj.get("params").cloned().unwrap_or(Value::Null);
    Some((id.clone(), params))
}

/// Methods of the MCP Tasks extension.
const TASK_METHODS: &[&str] = &["tasks/get", "tasks/update", "tasks/cancel"];

fn is_task_method(method: &str) -> bool {
    TASK_METHODS.contains(&method)
}

/// A well-formed single `tasks/*` request: the method, `id` and `params`.
fn single_task_request(msg: &Value) -> Option<(String, Value, Value)> {
    let method = msg.get("method").and_then(Value::as_str)?;
    if !is_task_method(method) {
        return None;
    }
    let (id, params) = single_request(msg, method)?;
    Some((method.to_owned(), id, params))
}

impl McpServer {
    /// The digest of the credentials on this request. A task is visible only
    /// to a request with the same digest.
    ///
    /// Parts: `Authorization`, the session cookie, the tenant header and the
    /// mTLS certificate fingerprint. The envelope does not resolve a
    /// principal, so the raw credentials are the parts. A caller with none of
    /// them is anonymous. Only the 256-bit task ID protects such a task.
    fn task_owner(&self, ctx: &ReplayContext<'_>) -> tasks::Owner {
        let headers = ctx.headers;
        let header = |name: &str| headers.get(name).and_then(|v| v.to_str().ok());
        let session = headers
            .get_all(header::COOKIE)
            .iter()
            .filter_map(|v| v.to_str().ok())
            .flat_map(|v| v.split(';'))
            .filter_map(|pair| pair.trim().split_once('='))
            .find(|(name, _)| *name == self.session_cookie)
            .map(|(_, value)| value);
        #[cfg(feature = "tls")]
        let certificate = ctx.client_cert.as_deref().map(|c| c.fingerprint.as_str());
        #[cfg(not(feature = "tls"))]
        let certificate = None;
        tasks::Owner::new(&[
            header("authorization"),
            session,
            self.tenant_header.as_deref().and_then(header),
            certificate,
        ])
    }

    /// A new task ID: 32 bytes from the injected entropy source, as hex.
    fn new_task_id(&self) -> String {
        let mut bytes = [0u8; 32];
        self.state.entropy().fill_bytes(&mut bytes);
        bytes.iter().fold(String::with_capacity(64), |mut out, b| {
            let _ = write!(out, "{b:02x}");
            out
        })
    }
}

/// Serve `tasks/get`, `tasks/update` or `tasks/cancel`.
fn serve_task_method(
    server: &McpServer,
    ctx: &ReplayContext<'_>,
    method: &str,
    id: Value,
    params: &Value,
) -> Value {
    if !server.has_task_tools {
        return error(id, -32601, &format!("method not found: {method}"));
    }
    if !tasks::client_declares_tasks(params) {
        return error_with_data(
            id,
            tasks::MISSING_CAPABILITY,
            "Missing required client capability",
            tasks::missing_capability_data(),
        );
    }
    let Some(task_id) = params.get("taskId").and_then(Value::as_str) else {
        return error(id, -32602, "`taskId` must be a string");
    };
    let owner = server.task_owner(ctx);
    let now = server.state.clock().now();
    let ack = || json!({ "resultType": "complete" });
    // A task of another caller gives the same error as an unknown task, so a
    // caller cannot find out that the ID exists.
    let found = match method {
        "tasks/get" => server.tasks.get(task_id, &owner, now),
        "tasks/cancel" => server.tasks.cancel(task_id, &owner, now).then(ack),
        // `inputResponses` is required. Autumn never asks for input, so no
        // key is outstanding. The spec says to ignore such keys.
        _ if !params.get("inputResponses").is_some_and(Value::is_object) => {
            return error(id, -32602, "`inputResponses` must be a JSON object");
        }
        _ => server.tasks.contains(task_id, &owner, now).then(ack),
    };
    found.map_or_else(
        || {
            error(
                id.clone(),
                -32602,
                "Failed to retrieve task: Task not found",
            )
        },
        |result| success(id.clone(), result),
    )
}

// ──────────────────────────────────────────────────────────────────
// Agent-authority audit (#1691)
// ──────────────────────────────────────────────────────────────────

/// Most effects recorded on an agent audit event. An action with more than this
/// is already far outside what a reviewer reads inline; the manifest holds the
/// complete set.
const MAX_AUDITED_EFFECTS: usize = 16;

/// Byte cap on the `argument_names` metadata value, so a pathological argument
/// object cannot bloat every row it touches.
const MAX_ARGUMENT_NAMES_BYTES: usize = 512;

/// Actor recorded when no principal was resolved for the call. Never empty: an
/// audit row that cannot name who acted is still a row that must be greppable.
const ANONYMOUS_AGENT: &str = "agent:anonymous";

/// Admit a call. It must be inside the `rate` cap. Its attempt record must be
/// writable, unless the action is provably reversible. A refusal becomes the
/// tool error text.
async fn admit_call(server: &McpServer, tool: &McpTool, audit: &AgentAudit) -> Result<(), String> {
    if let Err(refusal) = check_rate_cap(server, tool) {
        audit.record_refusal(&server.state, &refusal).await;
        return Err(refusal);
    }
    // The last thing before the action runs: if this record cannot be written
    // and the action is not provably reversible, it does not run.
    audit
        .record_attempt(&server.state)
        .await
        .map_err(str::to_owned)
}

/// Refuse a call that is over its grant's declared `rate` cap. A cap that
/// cannot be read refuses every call: it must never mean "no cap".
fn check_rate_cap(server: &McpServer, tool: &McpTool) -> Result<(), String> {
    let Some(grant) = tool.agent_authority.map(|a| a.grant) else {
        return Ok(());
    };
    let Some(rate) = grant.rate else {
        return Ok(());
    };
    let Some(cap) = crate::agent_authority::rate::parse_rate(rate) else {
        return Err(format!(
            "rate cap `{rate}` for grant {} cannot be read; the call is refused",
            grant.name
        ));
    };
    server
        .rate_limiter
        .check(grant.name, grant.location, cap, server.state.clock().now())
        .map_err(|wait| {
            format!(
                "rate cap {rate} for grant {} exceeded; retry in {wait}s",
                grant.name
            )
        })
}

/// Longest actor id an audit row keeps.
const MAX_ACTOR_LEN: usize = 128;

/// An actor id fit for an audit row: letters, digits and plain id punctuation
/// only, capped in length.
///
/// An allowlist, because line separators, zero-width marks and bidirectional
/// marks are not control characters, and a list of them is never complete.
fn clean_actor(actor: &str) -> Option<String> {
    let clean: String = actor
        .chars()
        .filter(|c| {
            c.is_alphanumeric()
                || matches!(
                    c,
                    '-' | '_' | '.' | ':' | '@' | '+' | '/' | '=' | '#' | '~' | ' '
                )
        })
        .take(MAX_ACTOR_LEN)
        .collect();
    (!clean.trim().is_empty()).then_some(clean)
}

/// The tool error returned when a non-reversible action cannot be recorded.
const UNAUDITABLE_REFUSAL: &str =
    "audit attempt record could not be written; refusing a non-reversible action";

/// Deadline for the pre-dispatch audit write.
///
/// This write sits inline on the request path, ahead of the handler, so a sink
/// that hangs — a saturated DB pool, a remote collector that accepted the
/// connection and went quiet — would otherwise stall every `tools/call` until
/// the envelope's `request_timeout_ms` fires. Expiry is treated as a write
/// failure, which means a non-reversible action is refused rather than served
/// unrecorded (issue #1691 review, P3-6).
const AUDIT_WRITE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);

/// Everything both of an invocation's audit events share, resolved once before
/// dispatch.
///
/// `Clone` so a streaming projection's drop guard can hand a copy to a spawned
/// task: `Drop` cannot await, and the outcome of an aborted stream still has to
/// reach the sink.
///
/// Two events are written per `tools/call` — `agent.tool.<name>.attempt` before
/// dispatch and `agent.tool.<name>` after it — because an invocation that never
/// returns (a panic, a hang, a killed process) must still leave evidence that
/// an agent reached for the action. They share a correlation id, minted here so
/// it exists before anything can go wrong.
#[derive(Clone)]
struct AgentAudit {
    tool: String,
    path_template: String,
    correlation_id: String,
    reversibility: Option<crate::agent_authority::Reversibility>,
    grant: Option<&'static str>,
    actor: String,
    ip: Option<std::net::IpAddr>,
    /// Metadata common to both events. Deliberately built once: the pair must
    /// agree field for field, or joining them is guesswork.
    shared: std::collections::BTreeMap<String, String>,
}

impl AgentAudit {
    /// Resolve the invocation's audit context from the tool's compile-time
    /// authority and the call's *shape*.
    ///
    /// `via_call_tool` is true for a call that `call_tool` wrapped. The
    /// record names the inner tool and adds `via = "call_tool"`.
    fn new(
        server: &McpServer,
        tool: &McpTool,
        arguments: &Value,
        ctx: &ReplayContext<'_>,
        via_call_tool: bool,
    ) -> Self {
        let authority = tool.agent_authority;
        let grant = authority.map(|a| a.grant.name);
        let reversibility = authority.map(|a| a.grant.reversibility);
        let correlation_id = server.state.entropy().uuid_v4().to_string();

        let mut shared = std::collections::BTreeMap::new();
        shared.insert("correlation_id".to_owned(), correlation_id.clone());
        shared.insert("transport".to_owned(), "mcp".to_owned());
        shared.insert("tool".to_owned(), tool.name.clone());
        if let Some(grant) = grant {
            shared.insert("grant".to_owned(), grant.to_owned());
        }
        // "unknown" rather than a guess: an ungoverned tool's blast radius is
        // exactly what nobody has established, and calling it `reversible`
        // would be the one wrong answer.
        shared.insert(
            "reversibility".to_owned(),
            reversibility.map_or_else(|| "unknown".to_owned(), |r| r.as_str().to_owned()),
        );
        if let Some(authority) = authority {
            shared.insert("effects".to_owned(), render_effects(authority.effects));
        }
        shared.insert("argument_names".to_owned(), argument_names(tool, arguments));
        if via_call_tool {
            shared.insert("via".to_owned(), catalog::CALL_TOOL.to_owned());
        }

        Self {
            tool: tool.name.clone(),
            path_template: tool.path_template.clone(),
            correlation_id,
            reversibility,
            grant,
            // The principal the *envelope* resolved, if any. `Current` is set by
            // the auth layer on the request scope, so a `secure_mcp` app names
            // its caller and an open one falls back rather than recording "".
            actor: crate::current::Current::scoped_actor()
                .and_then(|actor| clean_actor(&actor))
                .unwrap_or_else(|| ANONYMOUS_AGENT.to_owned()),
            ip: ctx.peer.map(|peer| peer.ip()),
            shared,
        }
    }

    /// The extension handlers read via `Extension<AgentInvocation>`.
    fn invocation(&self) -> crate::agent_authority::AgentInvocation {
        crate::agent_authority::AgentInvocation {
            correlation_id: self.correlation_id.clone(),
            tool: self.tool.clone(),
            grant: self.grant,
            reversibility: self.reversibility,
        }
    }

    /// Whether a lost audit record is grounds for refusing the action.
    ///
    /// Only a *proved* `reversible` grant earns the benefit of the doubt.
    /// Ungoverned (`None`) counts as non-reversible: the whole point of the
    /// unknown marker is that we do not get to assume.
    fn refuse_when_unauditable(&self) -> bool {
        self.reversibility != Some(crate::agent_authority::Reversibility::Reversible)
    }

    /// Name the principal the route's own auth layer resolved. Only the rows
    /// written after dispatch carry it. The envelope's own actor, when it
    /// resolved one, wins.
    fn adopt_actor(&mut self, actor: Option<&str>) {
        if self.actor != ANONYMOUS_AGENT {
            return;
        }
        if let Some(clean) = actor.and_then(clean_actor) {
            self.actor = clean;
        }
    }

    /// Build one of this invocation's events.
    ///
    /// `phase` is what tells the three rows apart once they are in the sink:
    /// `attempt` is written before anything runs, `outcome` after the handler
    /// returned, and `refused` when the attempt could not be recorded and the
    /// action was therefore not taken. Without it an operator filtering on
    /// `status` alone cannot distinguish "an attempt was logged" from "the call
    /// succeeded" — the attempt is deliberately `Success` (the *write*
    /// succeeded; nothing has been tried yet) — nor a refusal from a 5xx.
    fn event(
        &self,
        action: String,
        status: crate::audit::AuditStatus,
        phase: &str,
    ) -> crate::audit::AuditEvent {
        let mut event = crate::audit::AuditEvent::new(
            self.actor.clone(),
            action,
            self.path_template.clone(),
            self.ip,
            status,
        );
        event.metadata = self.shared.clone();
        event.metadata.insert("phase".to_owned(), phase.to_owned());
        event
    }

    /// Write one event under [`AUDIT_WRITE_TIMEOUT`], flattening an expiry into
    /// the same `Err` shape a sink failure produces.
    ///
    /// Takes the state rather than the server because the streaming drop guard
    /// outlives the borrow of `McpServer` — it writes from a spawned task.
    async fn write_bounded(
        state: &crate::state::AppState,
        event: crate::audit::AuditEvent,
    ) -> Result<(), String> {
        match tokio::time::timeout(
            AUDIT_WRITE_TIMEOUT,
            crate::audit::write_from_state(state, event),
        )
        .await
        {
            Ok(Ok(())) => Ok(()),
            Ok(Err(error)) => Err(error.to_string()),
            Err(_elapsed) => Err(format!(
                "audit sink did not respond within {AUDIT_WRITE_TIMEOUT:?}"
            )),
        }
    }

    /// The fields every `autumn.agent` line carries, so the attempt and the
    /// outcome lines describe one invocation in the same vocabulary.
    fn reversibility_field(&self) -> Option<&str> {
        self.shared.get("reversibility").map(String::as_str)
    }

    /// Record the attempt, before anything has run.
    ///
    /// `Err` carries the tool-error text: the record could not be written and
    /// the action is not reversible, so it must not happen at all.
    async fn record_attempt(&self, state: &crate::state::AppState) -> Result<(), &'static str> {
        let event = self.event(
            format!("agent.tool.{}.attempt", self.tool),
            // The *write* is what succeeded here; `phase` carries the fact that
            // nothing has been attempted yet.
            crate::audit::AuditStatus::Success,
            "attempt",
        );
        let Err(error) = Self::write_bounded(state, event).await else {
            // Mirrored to the trace so an app with no sink installed still sees
            // both halves of every invocation, not just the outcome.
            tracing::info!(
                target: "autumn.agent",
                tool = %self.tool,
                correlation_id = %self.correlation_id,
                transport = "mcp",
                phase = "attempt",
                grant = self.grant,
                reversibility = self.reversibility_field(),
                effects = self.shared.get("effects").map(String::as_str),
                argument_names = self.shared.get("argument_names").map(String::as_str),
                actor = %self.actor,
                target = %self.path_template,
                "agent tool call attempted"
            );
            return Ok(());
        };
        if self.refuse_when_unauditable() {
            tracing::error!(
                target: "autumn.agent",
                tool = %self.tool,
                correlation_id = %self.correlation_id,
                transport = "mcp",
                phase = "refused",
                grant = self.grant,
                reversibility = self.reversibility_field(),
                actor = %self.actor,
                target = %self.path_template,
                error = %error,
                "refusing an agent tool call: its attempt record could not be written \
                 and the action is not reversible"
            );
            self.record_refusal(state, &error).await;
            return Err(UNAUDITABLE_REFUSAL);
        }
        tracing::warn!(
            target: "autumn.agent",
            tool = %self.tool,
            correlation_id = %self.correlation_id,
            phase = "attempt",
            error = %error,
            "agent tool attempt record could not be written; the action is reversible, \
             so the call proceeds"
        );
        Ok(())
    }

    /// Best-effort record that the invocation was refused for want of an audit
    /// trail.
    ///
    /// The write that just failed was an aggregate across every configured sink
    /// ([`AuditLogger::write`](crate::audit::AuditLogger::write) attempts them
    /// all and joins the errors), so one broken sink fails the whole call —
    /// while the healthy ones would happily have taken the row. Retrying here
    /// gives them the refusal, which is the single most interesting thing that
    /// happened. Its own failure is ignored on purpose: there is nowhere left to
    /// report it, the `tracing::error!` above already fired, and the refusal
    /// itself does not depend on this landing.
    async fn record_refusal(&self, state: &crate::state::AppState, error: &str) {
        let mut event = self.event(
            // Its own action, not the outcome action with a different `phase`:
            // a refusal and a completed call are different things, and an
            // operator filtering for one should not have to parse metadata to
            // exclude the other.
            format!("agent.tool.{}.refused", self.tool),
            crate::audit::AuditStatus::Failure,
            "refused",
        );
        // No `http_status`: nothing was dispatched.
        event
            .metadata
            .insert("refused_reason".to_owned(), error.to_owned());
        let _ = Self::write_bounded(state, event).await;
    }

    /// Record how the invocation ended. Never alters the tool result: a broken
    /// sink is an operational problem, not a reason to fail a call that already
    /// happened.
    async fn record_outcome(
        &self,
        state: &crate::state::AppState,
        status: Option<StatusCode>,
        request_id: Option<&str>,
        disposition: Disposition,
    ) {
        // The status line alone is not the verdict: a streaming tool answers
        // `200` before it has done anything, and a buffered tool can answer
        // `200` and then fail to hand its body over. `disposition` carries what
        // actually became of the action.
        // `None`: the work stopped before the handler gave a status.
        let succeeded = status.is_some_and(|s| s.is_success()) && disposition.is_success();
        let audit_status = if succeeded {
            crate::audit::AuditStatus::Success
        } else {
            crate::audit::AuditStatus::Failure
        };
        let mut event = self.event(format!("agent.tool.{}", self.tool), audit_status, "outcome");
        if let Some(status) = status {
            event
                .metadata
                .insert("http_status".to_owned(), status.as_u16().to_string());
        }
        if let Some(stream) = disposition.stream_state() {
            event
                .metadata
                .insert("stream_state".to_owned(), stream.to_owned());
        }
        if let Some(result) = disposition.result() {
            event
                .metadata
                .insert("result".to_owned(), result.to_owned());
        }
        // The replayed pipeline's own id, so an audit row joins to the access
        // log line and the traces for the same dispatch.
        if let Some(request_id) = request_id {
            event
                .metadata
                .insert("request_id".to_owned(), request_id.to_owned());
        }
        // Emitted whether or not a sink is installed, so an app that configured
        // none still has a trace of every agent action it served.
        tracing::info!(
            target: "autumn.agent",
            tool = %self.tool,
            correlation_id = %self.correlation_id,
            transport = "mcp",
            phase = "outcome",
            grant = self.grant,
            reversibility = self.reversibility_field(),
            effects = self.shared.get("effects").map(String::as_str),
            argument_names = self.shared.get("argument_names").map(String::as_str),
            actor = %self.actor,
            target = %self.path_template,
            http_status = status.map(|s| s.as_u16()),
            stream_state = disposition.stream_state(),
            result = disposition.result(),
            request_id = request_id,
            "agent tool call"
        );
        // Bounded like the attempt write: the handler has already run, so a
        // hanging sink here cannot change what happened — but it can still hold
        // the response open, and the caller is owed one.
        if let Err(error) = Self::write_bounded(state, event).await {
            tracing::warn!(
                target: "autumn.agent",
                tool = %self.tool,
                correlation_id = %self.correlation_id,
                phase = "outcome",
                error = %error,
                "agent tool outcome record could not be written"
            );
        }
    }
}

/// Why the buffered path could not hand the handler's body to the agent.
///
/// The buffered branch answers the agent from a body it has to read *after* the
/// handler's status is known, so a `200` is not yet proof the call succeeded
/// (issue #1691 review round 2).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BufferedFailure {
    /// The body exceeded [`MAX_TOOL_RESPONSE_BYTES`].
    Overflow,
    /// The body stream itself errored part-way through.
    BodyError,
}

impl BufferedFailure {
    /// Classify what [`axum::body::to_bytes`] returned.
    ///
    /// It collects through `http_body_util::Limited`, so a `LengthLimitError`
    /// anywhere in the source chain means the cap was hit; anything else is a
    /// transport failure on the body itself.
    fn classify(error: &axum::Error) -> Self {
        let mut source: Option<&(dyn std::error::Error + 'static)> = Some(error);
        while let Some(err) = source {
            if err.is::<http_body_util::LengthLimitError>() {
                return Self::Overflow;
            }
            source = err.source();
        }
        Self::BodyError
    }

    const fn as_str(self) -> &'static str {
        match self {
            Self::Overflow => "body_overflow",
            Self::BodyError => "body_error",
        }
    }
}

/// What became of an invocation once its HTTP status was known.
///
/// The status line is necessary but not sufficient: both the streaming and the
/// buffered branch can still fail the agent after a `200`, and an audit row
/// that only reflected the status would claim a success neither delivered.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Disposition {
    /// The handler answered and its result reached the agent unaltered — the
    /// status line is the whole story.
    Settled,
    /// A streaming projection ended this way.
    Stream(StreamState),
    /// The buffered path could not deliver the handler's body.
    Buffered(BufferedFailure),
    /// A task stopped before its handler gave a result.
    Task(TaskEnd),
}

impl Disposition {
    /// Whether this disposition permits the outcome to be recorded as a
    /// success (the HTTP status still has to agree).
    const fn is_success(self) -> bool {
        match self {
            Self::Settled => true,
            Self::Stream(state) => state.is_success(),
            Self::Buffered(_) | Self::Task(_) => false,
        }
    }

    const fn stream_state(self) -> Option<&'static str> {
        match self {
            Self::Stream(state) => Some(state.as_str()),
            _ => None,
        }
    }

    const fn result(self) -> Option<&'static str> {
        match self {
            Self::Buffered(failure) => Some(failure.as_str()),
            Self::Task(end) => Some(end.as_str()),
            _ => None,
        }
    }
}

/// Why a task stopped before its handler gave a result.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TaskEnd {
    /// `tasks/cancel` or the TTL stopped the work.
    Aborted,
    /// The handler panicked.
    Panicked,
}

impl TaskEnd {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Aborted => "task_aborted",
            Self::Panicked => "task_panicked",
        }
    }
}

/// How a streaming tool's projection ended.
///
/// A streaming handler returns `200` before it has produced anything, so the
/// status line says nothing about whether the work happened. Recording the
/// outcome up front would durably claim success for a stream that then errored
/// or was cut off by a client disconnect, with no later event to correct it
/// (issue #1691 review round 1).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum StreamState {
    /// The handler's body ended normally: everything it meant to emit, it
    /// emitted.
    Completed,
    /// The projection was dropped before the handler's body ended — a client
    /// disconnect, or the response being discarded mid-flight.
    Aborted,
    /// The handler's body yielded a transport error part-way through.
    Errored,
}

impl StreamState {
    const fn as_str(self) -> &'static str {
        match self {
            Self::Completed => "completed",
            Self::Aborted => "aborted",
            Self::Errored => "errored",
        }
    }

    /// Only a stream that ran to the end counts as a successful action.
    const fn is_success(self) -> bool {
        matches!(self, Self::Completed)
    }
}

/// Owns the one outcome record a streaming or task `tools/call` still owes.
///
/// The work writes the record when it reaches a terminal state. If that does
/// not occur (the client hangs up, or cancels the task), `Drop` writes
/// `abandoned`. `Drop` cannot await, so it spawns the write. `recorded` makes
/// the two paths mutually exclusive: one outcome reaches the sink per call.
struct OutcomeGuard {
    audit: AgentAudit,
    state: crate::state::AppState,
    /// The handler's status. `None` until a task's dispatch returns.
    status: Option<StatusCode>,
    request_id: Option<String>,
    /// What `Drop` records: the work stopped before it ended.
    abandoned: Disposition,
    recorded: bool,
}

impl OutcomeGuard {
    const fn new(audit: AgentAudit, state: crate::state::AppState, abandoned: Disposition) -> Self {
        Self {
            audit,
            state,
            status: None,
            request_id: None,
            abandoned,
            recorded: false,
        }
    }

    /// Record the outcome inline, from the work's own async context.
    async fn record(&mut self, disposition: Disposition) {
        if self.recorded {
            return;
        }
        self.recorded = true;
        self.audit
            .record_outcome(
                &self.state,
                self.status,
                self.request_id.as_deref(),
                disposition,
            )
            .await;
    }
}

impl Drop for OutcomeGuard {
    fn drop(&mut self) {
        if self.recorded {
            return;
        }
        self.recorded = true;
        // The work never reached an end: a stream's response body was dropped
        // while the handler still had output to give, or a task was cancelled,
        // expired or panicked. The trail has to say so rather than stay silent.
        let disposition = match self.abandoned {
            // A drop during unwinding is a panic, not an abort.
            Disposition::Task(_) if std::thread::panicking() => {
                Disposition::Task(TaskEnd::Panicked)
            }
            other => other,
        };
        let audit = self.audit.clone();
        let state = self.state.clone();
        let status = self.status;
        let request_id = self.request_id.clone();
        // `try_current` rather than `spawn`: during runtime shutdown there is
        // no reactor left to spawn onto, and a panic in `Drop` would be far
        // worse than a missing row on a process that is already going away.
        if let Ok(handle) = tokio::runtime::Handle::try_current() {
            handle.spawn(async move {
                audit
                    .record_outcome(&state, status, request_id.as_deref(), disposition)
                    .await;
            });
        }
    }
}

/// Render an authority's proved effects as `kind:subject`, comma-joined.
fn render_effects(effects: &[crate::agent_authority::Effect]) -> String {
    let mut out = String::new();
    for effect in effects.iter().take(MAX_AUDITED_EFFECTS) {
        if !out.is_empty() {
            out.push(',');
        }
        out.push_str(effect.kind.as_str());
        out.push(':');
        out.push_str(effect.subject);
    }
    if effects.len() > MAX_AUDITED_EFFECTS {
        out.push_str(",…");
    }
    out
}

/// The call's top-level argument **names**, sorted and comma-joined, followed
/// by a count of the ones this tool does not recognise.
///
/// Names only, never values: an audit sink is a long-lived, widely-readable
/// store, and the arguments of an agent call routinely carry exactly the
/// payloads that must not be duplicated into one. The shape of a call is what
/// makes a row reviewable; its contents are the handler's business.
///
/// Only names drawn from the tool's own argument surface — the reserved
/// `body`/`query` keys and its declared path params — are echoed verbatim.
/// Everything else is counted, never quoted (`body,id,+2 unknown`).
///
/// The caller chooses those keys and nothing validates them against the
/// advertised schema, so an un-intersected name list is an
/// attacker-controlled string landing in a durable audit row *and* in the
/// `autumn.agent` trace line, where an embedded newline forges a log entry and
/// a key like `ssn-123-45-6789` smuggles the very payload the names-only rule
/// exists to keep out (issue #1691 review, P2-2). Counting the unknowns keeps
/// the useful signal — "this call carried arguments the tool ignores" — without
/// reproducing a single byte the caller wrote.
fn argument_names(tool: &McpTool, arguments: &Value) -> String {
    let Some(object) = arguments.as_object() else {
        return String::new();
    };

    // The keys `build_request` actually reads. Catch-all params (`{*rest}`)
    // surface from `ApiDoc` with a leading `*` but are addressed by the bare
    // name, exactly as `build_request` strips it.
    let is_known = |name: &str| {
        name == "body"
            || name == "query"
            || tool
                .path_params
                .iter()
                .any(|param| param.strip_prefix('*').unwrap_or(param) == name)
    };

    let mut known: Vec<&str> = Vec::new();
    let mut unknown: usize = 0;
    for name in object.keys() {
        if is_known(name) {
            known.push(name);
        } else {
            unknown += 1;
        }
    }
    known.sort_unstable();

    let mut out = String::new();
    for name in known {
        // +1 for the separator this name would need.
        if out.len() + name.len() + 1 > MAX_ARGUMENT_NAMES_BYTES {
            out.push_str(",…");
            break;
        }
        if !out.is_empty() {
            out.push(',');
        }
        out.push_str(name);
    }
    if unknown > 0 {
        if !out.is_empty() {
            out.push(',');
        }
        // A count, not the names: the whole point is that these are the ones
        // nobody vouched for.
        let _ = write!(out, "+{unknown} unknown");
    }
    out
}

/// Carry the envelope's context onto the request the `tools/call` replays.
///
/// Everything here exists because the replay traverses the *real* pipeline: it
/// has to look to that pipeline like the direct HTTP call it stands in for,
/// while not being double-charged for work the envelope already did.
fn apply_replay_extensions(
    request: &mut axum::extract::Request,
    server: &McpServer,
    ctx: &ReplayContext<'_>,
    audit: &AgentAudit,
    detached: bool,
) {
    let extensions = request.extensions_mut();

    // Inserted for EVERY tool — a handler is entitled to know it is being
    // driven by an agent whether or not anyone declared a grant for it.
    extensions.insert(audit.invocation());

    // The caller's resolved identity and connection peer, so the dispatch
    // pipeline attributes the call like a direct request would — the
    // proxy-aware tenancy host and the IP-keyed rate limiter both read these.
    if let Some(identity) = ctx.identity {
        extensions.insert(identity.clone());
    }
    if let Some(peer) = ctx.peer {
        extensions.insert(axum::extract::ConnectInfo(peer));
    }
    // The verified client certificate of the envelope's own connection (#1640).
    // The replay traverses the router's `RequireClientCert` layer, so without
    // this a legitimately-certified caller would be refused on an mTLS-only
    // tool — and `ClientCert` would disagree with the `PolicyContext`, which
    // reads the ambient scope and therefore already sees it.
    #[cfg(feature = "tls")]
    if let Some(client_cert) = &ctx.client_cert {
        extensions.insert(std::sync::Arc::clone(client_cert));
    }
    // When the `/mcp` envelope is itself rate-limited, this call was already
    // counted there; mark the replay envelope-counted so the framework-default
    // limiter (which shares the envelope bucket) doesn't charge a second token
    // for the same tool call. User/per-route limiters (path overrides,
    // `#[throttle]`) don't share that bucket and still charge the replay.
    if server.envelope_rate_limited {
        extensions.insert(crate::security::RateLimitEnvelopeCounted);
    }
    // Likewise for load shedding: the envelope and the dispatch pipeline share
    // the SAME `LoadShedLayer` instance (same `Arc` in-flight counter), so
    // without this a `tools/call` would acquire one slot at the envelope and a
    // second at this replay for the same logical request — silently halving the
    // effective ceiling for MCP traffic.
    //
    // A task (`detached`) outlives the envelope and its slot, so it takes
    // its own slot instead.
    if server.envelope_load_shed && !detached {
        extensions.insert(crate::middleware::LoadShedExempt);
        if let Some(admission) = &ctx.envelope_admission {
            extensions.insert(admission.clone());
        }
    }
}

/// What must be read off a dispatched response *before* its body is consumed or
/// handed to the SSE projection.
///
/// Grouped because they share one deadline, not one purpose: once the body is
/// taken, the response is gone and none of these can be recovered.
struct Dispatched {
    status: StatusCode,
    /// The replayed pipeline's own `x-request-id`, so the audit row joins to
    /// the access log line for the same dispatch.
    request_id: Option<String>,
    /// Whether the handler answered with `text/event-stream`.
    is_event_stream: bool,
    /// The [`REPLAYED_RESPONSE_HEADERS`] the inner handler or middleware set
    /// (session renewal, CSRF-cookie refresh, login, an x402 receipt),
    /// replayed onto the outer HTTP response so a tool call sends what the
    /// equivalent direct call would have.
    replayed: Vec<(HeaderName, HeaderValue)>,
    /// The principal the route's own auth layer resolved, if any.
    actor: Option<String>,
}

impl Dispatched {
    fn inspect(response: &Response) -> Self {
        let headers = response.headers();
        Self {
            actor: response
                .extensions()
                .get::<crate::agent_authority::AgentActor>()
                .map(|actor| actor.0.clone()),
            status: response.status(),
            request_id: headers
                .get("x-request-id")
                .and_then(|value| value.to_str().ok())
                .map(str::to_owned),
            is_event_stream: headers
                .get(header::CONTENT_TYPE)
                .and_then(|v| v.to_str().ok())
                .is_some_and(|c| {
                    c.trim_start()
                        .to_ascii_lowercase()
                        .starts_with("text/event-stream")
                }),
            replayed: REPLAYED_RESPONSE_HEADERS
                .iter()
                .flat_map(|&name| {
                    headers
                        .get_all(name)
                        .iter()
                        .map(move |value| (HeaderName::from_static(name), value.clone()))
                })
                .collect(),
        }
    }
}

/// Write the [`Dispatched::replayed`] headers onto the rebuilt `/mcp`
/// response. A paid call's challenge or receipt also carries x402's
/// `private, no-store`, so the paid result is not cached.
fn apply_replayed(headers: &mut HeaderMap, replayed: Vec<(HeaderName, HeaderValue)>) {
    let mut paid = false;
    for (name, value) in replayed {
        paid |= name.as_str().starts_with("payment-");
        headers.append(name, value);
    }
    if paid {
        headers.insert(
            header::CACHE_CONTROL,
            HeaderValue::from_static("private, no-store"),
        );
        crate::aeo::commerce::expose_payment_headers(headers);
    }
}

/// Dispatch a `tools/call` through the real router and shape the response as an
/// MCP tool result — buffered JSON for an ordinary tool, or a progressive SSE
/// stream for a `#[api_doc(mcp, stream)]` tool whose handler returns `Sse`.
async fn serve_tools_call(
    server: &Arc<McpServer>,
    ctx: &ReplayContext<'_>,
    id: Value,
    params: Value,
) -> Response {
    // A modern request's result gets `resultType` and `_meta.serverInfo`.
    let server_info = ctx.modern.then(|| server.server_info());
    let reply = |mut message: Value| {
        if let Some(info) = &server_info {
            modern::stamp(&mut message, info);
        }
        json_response(&message)
    };
    let (params, arguments, via_call_tool) = match prepare_call(server, &id, params, reply) {
        PreparedCall::Run(params, arguments, via_call_tool) => (params, arguments, via_call_tool),
        PreparedCall::Done(response) => return response,
    };
    let name = params.get("name").and_then(Value::as_str).unwrap_or("");

    let Some(&idx) = server.by_name.get(name) else {
        return json_response(&error(id, -32602, &format!("unknown tool: {name}")));
    };
    let tool = &server.tools[idx];

    let mut request = match build_request(
        tool,
        ctx.headers,
        &arguments,
        &server.csrf_header,
        server.tenant_header.as_deref(),
    ) {
        Ok(req) => req,
        Err(message) => return json_response(&error(id, -32602, &message)),
    };

    // Agent-authority envelope (#1691). Resolved before dispatch so the
    // correlation id exists ahead of anything that can go wrong.
    let mut audit = AgentAudit::new(server, tool, &arguments, ctx, via_call_tool);

    if let Err(refusal) = admit_call(server, tool, &audit).await {
        return reply(success(id, tool_error(&refusal)));
    }

    // MCP Tasks extension: give a task handle to a client that declared the
    // extension. If the store is full, the tool runs as a blocking call.
    // An x402-priced tool always answers on `/mcp`: a task has no response
    // to carry the payment challenge or the receipt.
    if tool.task
        && tasks::client_declares_tasks(&params)
        && !crate::aeo::commerce::prices_route(&server.state, &tool.method, &tool.path_template)
        && let Some((task_id, created)) = reserve_task(server, ctx, &tool.name)
    {
        apply_replay_extensions(&mut request, server, ctx, &audit, true);
        spawn_task(server, idx, &task_id, request, audit);
        return reply(success(id, created));
    }
    apply_replay_extensions(&mut request, server, ctx, &audit, false);

    let response = match server.dispatch.clone().oneshot(request).await {
        Ok(resp) => resp,
        Err(e) => {
            audit
                .record_outcome(
                    &server.state,
                    Some(StatusCode::INTERNAL_SERVER_ERROR),
                    None,
                    Disposition::Settled,
                )
                .await;
            return reply(success(id, tool_error(&format!("dispatch failed: {e}"))));
        }
    };

    let Dispatched {
        status,
        request_id,
        is_event_stream,
        replayed,
        actor,
    } = Dispatched::inspect(&response);
    audit.adopt_actor(actor.as_deref());
    let client_accepts_sse = ctx
        .headers
        .get(header::ACCEPT)
        .and_then(|v| v.to_str().ok())
        .is_some_and(accept_includes_event_stream);

    // A streaming tool whose handler streamed (text/event-stream) and whose
    // client can read SSE: project the stream onto the MCP SSE channel. This is
    // the only path that escapes buffering; every other case (a buffered tool, a
    // streaming handler that errored before streaming, or a client that can't
    // read SSE) falls through to the buffered branch below — so the base #1117
    // path and non-SSE clients are entirely unaffected.
    if tool.streams && status.is_success() && is_event_stream && client_accepts_sse {
        // The outcome is NOT recorded here. A streaming handler answers `200`
        // before it has produced anything, so recording now would durably claim
        // success for a stream that then errors or is cut off by a client
        // disconnect — with no later event to correct it. The guard travels
        // with the projection and writes exactly one outcome when it reaches a
        // terminal state, or from its `Drop` if the client hangs up first.
        let mut stream_audit = OutcomeGuard::new(
            audit,
            server.state.clone(),
            Disposition::Stream(StreamState::Aborted),
        );
        stream_audit.status = Some(status);
        stream_audit.request_id = request_id;
        return stream_tool_result(id, &params, response, replayed, stream_audit, server_info);
    }

    // Buffered path: the outcome is recorded only once the body has actually
    // been read and packaged. A `200` here is not yet proof the agent got
    // anything — the body can still overflow the tool-result cap or error
    // mid-read, and the agent would then see a tool error while the audit row
    // claimed success (issue #1691 review round 2).
    let (resp, failure) = buffered_tool_response(
        tool,
        id,
        status,
        is_event_stream,
        replayed,
        response,
        server_info.as_ref(),
    )
    .await;
    let disposition = failure.map_or(Disposition::Settled, Disposition::Buffered);
    audit
        .record_outcome(
            &server.state,
            Some(status),
            request_id.as_deref(),
            disposition,
        )
        .await;
    resp
}

/// A `tools/call` after the meta-tool step and the argument check.
enum PreparedCall {
    /// Run the call: its parameters, its `arguments` object, and whether
    /// `call_tool` wrapped it.
    Run(Value, Value, bool),
    /// End the call with this response.
    Done(Response),
}

/// Serve the meta-tools of the progressive catalog, then check the
/// `arguments` of the call to run.
///
/// `search_tools` gets its answer here. `call_tool` gives the parameters of
/// the inner call, which then takes the same path as a direct call.
fn prepare_call(
    server: &McpServer,
    id: &Value,
    params: Value,
    reply: impl Fn(Value) -> Response,
) -> PreparedCall {
    let invalid =
        |message: &str| PreparedCall::Done(json_response(&error(id.clone(), -32602, message)));
    let (params, via_call_tool) = match params.get("name").and_then(Value::as_str) {
        Some(catalog::SEARCH_TOOL) if server.catalog == McpCatalog::Progressive => {
            return match search_tools(server, &params) {
                Ok(result) => PreparedCall::Done(reply(success(id.clone(), result))),
                Err(message) => invalid(&message),
            };
        }
        Some(catalog::CALL_TOOL) if server.catalog == McpCatalog::Progressive => {
            match catalog::unwrap_call(&params) {
                Ok(inner) => (inner, true),
                Err(message) => return invalid(&message),
            }
        }
        _ => (params, false),
    };
    match call_arguments(&params) {
        Ok(arguments) => PreparedCall::Run(params, arguments, via_call_tool),
        Err(message) => invalid(message),
    }
}

/// The `arguments` object of a `tools/call`. Absent arguments are `{}`.
///
/// `inputSchema` is always an object. A non-object `arguments` (null,
/// string, array) is an error, not a value to coerce to `{}`.
fn call_arguments(params: &Value) -> Result<Value, &'static str> {
    match params.get("arguments") {
        None => Ok(json!({})),
        Some(value) if value.is_object() => Ok(value.clone()),
        Some(_) => Err("`arguments` must be a JSON object"),
    }
}

/// Serve a `search_tools` call. Returns the tool result, or the reason that
/// the arguments are not valid.
fn search_tools(server: &McpServer, params: &Value) -> Result<Value, String> {
    let arguments = call_arguments(params)?;
    let args = catalog::parse_search(&arguments)?;
    let found = catalog::search(&server.tools, &server.search_index, &args);
    let mut result = tool_ok(&found.to_string());
    result["structuredContent"] = found;
    Ok(result)
}

/// Add a `working` task to the store. Returns its ID and `CreateTaskResult`,
/// or `None` (with a warning) when the store or the client's quota is full.
fn reserve_task(
    server: &McpServer,
    ctx: &ReplayContext<'_>,
    tool: &str,
) -> Option<(String, Value)> {
    let task_id = server.new_task_id();
    let owner = server.task_owner(ctx);
    // The quota key is the client IP. The caller cannot change it, so a new
    // credential does not give a new quota.
    let quota = ctx
        .identity
        .and_then(|id| id.addr)
        .or_else(|| ctx.peer.map(|peer| peer.ip()))
        .map_or_else(|| "unknown".to_owned(), |ip| ip.to_string());
    let now = server.state.clock().now();
    let Some(created) = server.tasks.create(&task_id, owner, &quota, now) else {
        tracing::warn!(
            tool = %tool,
            "MCP task store is full; the tool call runs as a blocking call"
        );
        return None;
    };
    Some((task_id, created))
}

/// Run a task tool call in the background. The task is already in the store.
fn spawn_task(
    server: &Arc<McpServer>,
    idx: usize,
    task_id: &str,
    request: axum::extract::Request,
    audit: AgentAudit,
) {
    // Make the guard before the spawn. If tokio aborts the job before its
    // first poll, the guard writes the outcome.
    let outcome = OutcomeGuard::new(
        audit,
        server.state.clone(),
        Disposition::Task(TaskEnd::Aborted),
    );
    let ttl = server.tasks.ttl();
    let job_server = Arc::clone(server);
    let job_id = task_id.to_owned();
    let job = tokio::spawn(async move {
        let server = job_server;
        let run = std::panic::AssertUnwindSafe(run_task(&server, idx, request, outcome));
        // The TTL bounds the job, also when no request comes to purge it.
        // A timeout drops the guard, which writes `task_aborted`.
        let Ok(ran) = tokio::time::timeout(ttl, run.catch_unwind()).await else {
            let error = json!({ "code": -32603, "message": "Internal error" });
            let state = tasks::TaskState::Failed(error, "The task TTL ended.".to_owned());
            server
                .tasks
                .finish(&job_id, state, server.state.clock().now());
            return;
        };
        let Ok((mut result, mut outcome, disposition, permit)) = ran else {
            // A tool error is a result (`isError`). A panic outside the
            // pipeline's own panic catch is a JSON-RPC internal error.
            let error = json!({ "code": -32603, "message": "Internal error" });
            let state = tasks::TaskState::Failed(error, "The tool handler panicked.".to_owned());
            server
                .tasks
                .finish(&job_id, state, server.state.clock().now());
            return;
        };
        // The reference client reads `resultType` on the result.
        if let Some(object) = result.as_object_mut() {
            object.insert("resultType".to_owned(), json!("complete"));
        }
        // Finish before the audit write. After `finish`, a cancel or the TTL
        // cannot abort the job, so the result and the outcome record stay.
        let state = tasks::TaskState::Completed(Arc::new(result));
        server
            .tasks
            .finish(&job_id, state, server.state.clock().now());
        drop(permit);
        outcome.record(disposition).await;
    });
    server.tasks.set_abort(task_id, &job.abort_handle());
    // Delete the task when its TTL ends, also when no request comes. The job
    // can end early, so this timer is a separate task.
    let sweep_server = Arc::clone(server);
    tokio::spawn(async move {
        tokio::time::sleep(ttl).await;
        sweep_server.tasks.sweep(sweep_server.state.clock().now());
    });
}

/// Dispatch a task's request. Returns its `CallToolResult`, the guard and
/// disposition for the outcome record, and the buffer permit. The caller
/// writes the record after it stores the result.
async fn run_task(
    server: &McpServer,
    idx: usize,
    request: axum::extract::Request,
    mut outcome: OutcomeGuard,
) -> (
    Value,
    OutcomeGuard,
    Disposition,
    Option<tokio::sync::SemaphorePermit<'_>>,
) {
    let tool = &server.tools[idx];
    let response = match server.dispatch.clone().oneshot(request).await {
        Ok(resp) => resp,
        Err(e) => {
            outcome.status = Some(StatusCode::INTERNAL_SERVER_ERROR);
            let result = tool_error(&format!("dispatch failed: {e}"));
            return (result, outcome, Disposition::Settled, None);
        }
    };
    let Dispatched {
        status,
        request_id,
        is_event_stream,
        actor,
        ..
    } = Dispatched::inspect(&response);
    outcome.audit.adopt_actor(actor.as_deref());
    // A task has no HTTP response to carry `Set-Cookie` or `Server-Timing`.
    outcome.status = Some(status);
    outcome.request_id = request_id;
    // Limit how many task results buffer at once. The caller keeps the
    // permit until the result is stored.
    let permit = server.tasks.buffer_permit().await;
    let (result, failure) =
        read_tool_result(tool, status, is_event_stream, response.into_body()).await;
    let disposition = failure.map_or(Disposition::Settled, Disposition::Buffered);
    (result, outcome, disposition, permit)
}

/// Repackage a fully-buffered handler response as the JSON-RPC tool result.
///
/// Split out of [`serve_tools_call`] so that function stays readable (and under
/// clippy's `too_many_lines` ceiling): everything here runs only on the
/// buffered path.
///
/// Returns the response to send plus, when the handler's body could not be
/// delivered at all, why — the caller records that as the invocation's outcome,
/// so a tool error never sits behind an audit row claiming success.
async fn buffered_tool_response(
    tool: &McpTool,
    id: Value,
    status: StatusCode,
    is_event_stream: bool,
    replayed: Vec<(HeaderName, HeaderValue)>,
    response: Response,
    server_info: Option<&Value>,
) -> (Response, Option<BufferedFailure>) {
    // Capture the dispatch clone's `Server-Timing` header (#1348) so its
    // non-`total` metrics can be forwarded onto the rebuilt response. The clone
    // runs the primary `ServerTimingLayer`, which builds the full metric set —
    // including `db;dur;desc="N queries"` for a DB-backed tool — but that inner
    // response is discarded when the JSON-RPC envelope is rebuilt below. Without
    // forwarding, a DB-backed `tools/call` would lose the query count. Only the
    // non-`total` metrics are forwarded (see the append below); the inner
    // `total` measured the dispatch clone alone and is dropped in favour of the
    // outer fallback's real `/mcp` `total`. Captured before this function
    // consumes the body, exactly as the caller captured `Set-Cookie`.
    let mut server_timings: Vec<HeaderValue> = Vec::new();
    for value in response.headers().get_all(&SERVER_TIMING) {
        server_timings.push(value.clone());
    }

    let (value, failure) =
        read_tool_result(tool, status, is_event_stream, response.into_body()).await;
    let mut message = success(id, value);
    if let Some(info) = server_info {
        modern::stamp(&mut message, info);
    }
    let mut resp = json_response(&message);
    // The handler already ran: its cookies, and an x402 receipt for a payment
    // already settled, reach the client even when its body failed to read.
    apply_replayed(resp.headers_mut(), replayed);
    if failure.is_some() {
        return (resp, failure);
    }
    // Forward only the inner dispatch's non-`total` `Server-Timing` metrics
    // (e.g. `db;dur=…;desc="N queries"`) onto the rebuilt response, dropping the
    // inner `total`. That inner `total` measured only the dispatch clone; it was
    // captured before this endpoint buffered the body (`to_bytes`), collapsed an
    // SSE body for a non-SSE client, and repackaged the JSON-RPC envelope, so it
    // under-reports `/mcp` latency. By NOT marking the outer `ServerTimingEmitted`
    // sentinel, the fallback `ServerTimingLayer` appends the real `/mcp` `total`
    // (which brackets that buffering/serialization). Net result on a DB-backed
    // call: the fallback's true `total` plus the inner `db` metric, with exactly
    // one `total`. A non-DB call forwards nothing and the fallback emits
    // total-only.
    for timing in server_timings {
        if let Ok(value) = timing.to_str()
            && let Some(kept) = strip_total_metric(value)
            && let Ok(hv) = HeaderValue::from_str(&kept)
        {
            resp.headers_mut().append(SERVER_TIMING.clone(), hv);
        }
    }
    (resp, None)
}

/// Read a handler body and package it as a `CallToolResult`.
///
/// Returns the result plus, when the body could not be delivered, why.
async fn read_tool_result(
    tool: &McpTool,
    status: StatusCode,
    is_event_stream: bool,
    body: Body,
) -> (Value, Option<BufferedFailure>) {
    // Unlike a normal HTTP response (streamed straight to the socket), the MCP
    // path buffers the whole body to repackage it as a tool result. Cap that
    // buffer so a runaway handler can't OOM the process; report an overflow as
    // an explicit tool error rather than silently truncating to an empty body.
    let bytes = match axum::body::to_bytes(body, MAX_TOOL_RESPONSE_BYTES).await {
        Ok(bytes) => bytes,
        Err(error) => {
            // The agent gets a tool error, so the audit row must record one
            // too: the call did not deliver what the handler produced.
            let failure = BufferedFailure::classify(&error);
            let message = match failure {
                BufferedFailure::Overflow => format!(
                    "handler response exceeded the {MAX_TOOL_RESPONSE_BYTES}-byte MCP tool-result limit"
                ),
                BufferedFailure::BodyError => {
                    format!("handler response body failed mid-read: {error}")
                }
            };
            return (tool_error(&message), Some(failure));
        }
    };
    // A streaming handler buffered for a non-SSE client: collapse the SSE wire
    // frames into their concatenated data payload so the client still receives a
    // usable single result instead of raw `data:`-framed text.
    let text = if is_event_stream {
        collapse_sse_body(&bytes)
    } else {
        String::from_utf8_lossy(&bytes).into_owned()
    };

    (buffered_tool_result(tool, status, &text), None)
}

/// Strip the `total` metric from a `Server-Timing` header value, returning the
/// remaining comma-separated metrics (e.g. `db;dur=…;desc="N queries"`), or
/// `None` when only `total` (or nothing usable) was present.
///
/// A `Server-Timing` value is a comma-separated list of metrics, each of the
/// form `name` optionally followed by `;`-separated parameters (`dur`, `desc`).
/// The metric name is the token before the first `;` or `=`. This keeps the
/// output W3C-valid and preserves any future non-`total` metrics the inner
/// pipeline emits.
fn strip_total_metric(value: &str) -> Option<String> {
    let kept: Vec<&str> = value
        .split(',')
        .map(str::trim)
        .filter(|entry| !entry.is_empty())
        .filter(|entry| {
            let name = entry.split([';', '=']).next().unwrap_or("").trim();
            !name.eq_ignore_ascii_case("total")
        })
        .collect();
    if kept.is_empty() {
        None
    } else {
        Some(kept.join(", "))
    }
}

/// Package a buffered handler response as a `CallToolResult`.
///
/// An empty-body-contract tool (declared 204/205, no response schema)
/// advertises "empty text on success". Enforce that here rather than
/// trusting the declaration: a handler whose real response carries a body
/// (e.g. an HTML route mislabeled `status = 204`) must not leak it into the
/// tool result. Discarding silently would hide the mislabel, so surface it.
fn buffered_tool_result(tool: &McpTool, status: StatusCode, text: &str) -> Value {
    if !status.is_success() {
        return tool_error(&format!(
            "handler returned HTTP {}: {text}",
            status.as_u16()
        ));
    }
    if tool.empty_body {
        if !text.is_empty() {
            tracing::warn!(
                tool = %tool.name,
                body_len = text.len(),
                "empty-body-contract tool returned a non-empty body; \
                 discarding it (the route's declared 204/205 status does \
                 not match what its handler actually returns)"
            );
        }
        return tool_ok("");
    }
    tool_ok(text)
}

// ── Progressive (SSE) tool-result projection ──────────────────────
//
// A streaming tool is a normal Autumn route returning `Sse` (issue #1118). Its
// dispatched response is already SSE wire bytes (`event:`/`data:` frames). The
// MCP endpoint *re-projects* those frames onto the Streamable-HTTP SSE channel:
// each handler event becomes a `notifications/progress` message (when the
// client supplied `_meta.progressToken`), and the stream is terminated by the
// final id-correlated `tools/call` result. The developer writes a plain Autumn
// stream — zero hand-written JSON-RPC/SSE framing — and time-to-first-signal is
// decoupled from total tool duration because frames are forwarded as they
// arrive rather than buffered.

/// Whether an `Accept` header opts the client in to an SSE response. The MCP
/// Streamable-HTTP transport has a streaming client advertise
/// `Accept: ..., text/event-stream`; a client that does not is served a
/// buffered JSON result instead (see [`serve_tools_call`]). `*/*` is treated as
/// "does not explicitly accept SSE" so a plain JSON client isn't handed a body
/// it can't parse.
fn accept_includes_event_stream(accept: &str) -> bool {
    accept.split(',').any(|part| {
        let media = part
            .split(';')
            .next()
            .unwrap_or("")
            .trim()
            .to_ascii_lowercase();
        media == "text/event-stream" || media == "text/*"
    })
}

/// Build the JSON-RPC `notifications/progress` message for one streamed event.
///
/// When the event's data is a JSON object carrying a numeric `progress`, its
/// `progress`/`total`/`message` fields are forwarded verbatim (structured
/// progress). Otherwise the event text is the human-readable `message` and
/// `progress` is the running per-event counter.
fn progress_notification(token: &Value, progress: f64, message: &str) -> Value {
    if let Ok(Value::Object(map)) = serde_json::from_str::<Value>(message)
        && map.get("progress").is_some_and(Value::is_number)
    {
        let mut params = serde_json::Map::new();
        params.insert("progressToken".into(), token.clone());
        for key in ["progress", "total", "message"] {
            if let Some(v) = map.get(key) {
                params.insert((*key).to_owned(), v.clone());
            }
        }
        return json!({
            "jsonrpc": "2.0",
            "method": "notifications/progress",
            "params": Value::Object(params),
        });
    }
    json!({
        "jsonrpc": "2.0",
        "method": "notifications/progress",
        "params": { "progressToken": token, "progress": progress, "message": message },
    })
}

/// Phase of the SSE projection state machine.
enum ProjectionPhase {
    /// Reading frames from the handler's stream.
    Streaming,
    /// Handler stream ended; the final `tools/call` result is pending.
    Final,
    /// Final result emitted; the stream is complete.
    Done,
}

/// State threaded through the projection `unfold` (see [`stream_tool_result`]).
struct StreamProjection {
    /// The handler's SSE response body, as a byte stream of wire frames.
    body: Pin<Box<dyn Stream<Item = Result<Bytes, axum::Error>> + Send>>,
    parser: SseWireParser,
    /// MCP messages parsed but not yet emitted (one inner chunk may yield many).
    ready: VecDeque<Event>,
    /// The client's `_meta.progressToken`, if any; absent ⇒ no progress notes.
    progress_token: Option<Value>,
    /// The original request id, echoed on the terminating result.
    id: Value,
    /// Running per-event progress counter (used when the handler doesn't supply
    /// its own structured `progress`).
    progress: f64,
    /// Accumulated text of progress (default/`progress`-typed) events.
    progress_parts: Vec<String>,
    /// Accumulated text of explicit `event: result` frames, if the handler uses
    /// them to distinguish the final payload from incremental progress.
    result_parts: Vec<String>,
    phase: ProjectionPhase,
    /// The invocation's outstanding outcome record. Dropped with the rest of
    /// the projection when the client hangs up, which is how an aborted stream
    /// still gets a row (#1691).
    audit: OutcomeGuard,
    /// The server info for a modern request. The final result gets
    /// `resultType` and `_meta.serverInfo`.
    stamp: Option<Value>,
}

/// Project a streaming handler's `Sse` response onto the MCP SSE channel.
///
/// Back-pressure / disconnect: the returned [`Sse`] writes frames to the socket
/// as the agent consumes them; if the agent disconnects, axum drops the
/// response future, which drops this `unfold` state — and with it the boxed
/// handler body stream — so the handler's task unwinds with no leak and no panic
/// on a closed stream, exactly as `sse.rs` handles a dropped subscriber.
fn stream_tool_result(
    id: Value,
    params: &Value,
    response: Response,
    replayed: Vec<(HeaderName, HeaderValue)>,
    audit: OutcomeGuard,
    stamp: Option<Value>,
) -> Response {
    let progress_token = params
        .get("_meta")
        .and_then(|m| m.get("progressToken"))
        .cloned();

    let state = StreamProjection {
        body: Box::pin(response.into_body().into_data_stream()),
        parser: SseWireParser::new(),
        ready: VecDeque::new(),
        progress_token,
        id,
        progress: 0.0,
        progress_parts: Vec::new(),
        result_parts: Vec::new(),
        phase: ProjectionPhase::Streaming,
        audit,
        stamp,
    };

    let stream = futures::stream::unfold(state, project_next);
    let mut resp = Sse::new(stream)
        .keep_alive(crate::sse::keep_alive())
        .into_response();
    // Ask reverse proxies (nginx) not to buffer the stream.
    resp.headers_mut()
        .insert("x-accel-buffering", HeaderValue::from_static("no"));
    apply_replayed(resp.headers_mut(), replayed);
    resp
}

/// Yield the next MCP message (as an SSE [`Event`]) for the projection.
async fn project_next(
    mut st: StreamProjection,
) -> Option<(Result<Event, Infallible>, StreamProjection)> {
    loop {
        if let Some(event) = st.ready.pop_front() {
            return Some((Ok(event), st));
        }
        match st.phase {
            ProjectionPhase::Done => return None,
            ProjectionPhase::Final => {
                // Prefer explicit `event: result` payloads; otherwise the joined
                // progress text is the complete result.
                let content = if st.result_parts.is_empty() {
                    st.progress_parts.join("\n")
                } else {
                    st.result_parts.concat()
                };
                let mut value = success(st.id.clone(), tool_ok(&content));
                if let Some(server_info) = &st.stamp {
                    modern::stamp(&mut value, server_info);
                }
                st.phase = ProjectionPhase::Done;
                return Some((Ok(Event::default().data(value.to_string())), st));
            }
            ProjectionPhase::Streaming => match st.body.next().await {
                Some(Ok(bytes)) => {
                    let events = st.parser.push(&bytes);
                    enqueue_projected(&mut st, events);
                }
                // The handler's body is finished — cleanly (`None`) or with a
                // transport error (`Some(Err)`, the only `Some` left here).
                // Either way this is the action's terminal state, so the
                // outcome is recorded now rather than left to the drop guard:
                // whatever the client does with the remaining projection, the
                // handler has already done everything it was going to do.
                terminal => {
                    let outcome = if terminal.is_some() {
                        StreamState::Errored
                    } else {
                        StreamState::Completed
                    };
                    let trailing = st.parser.finish();
                    enqueue_projected(&mut st, trailing);
                    st.phase = ProjectionPhase::Final;
                    st.audit.record(Disposition::Stream(outcome)).await;
                }
            },
        }
    }
}

/// Fold parsed handler frames into the projection: accumulate their text for the
/// final result and, when a `progressToken` is present, enqueue a
/// `notifications/progress` message per incremental frame.
fn enqueue_projected(st: &mut StreamProjection, events: Vec<ParsedSseEvent>) {
    for ev in events {
        if ev.event.as_deref() == Some("result") {
            // Explicit final-result content — not surfaced as progress.
            st.result_parts.push(ev.data);
            continue;
        }
        st.progress_parts.push(ev.data.clone());
        if let Some(token) = &st.progress_token {
            st.progress += 1.0;
            let note = progress_notification(token, st.progress, &ev.data);
            st.ready.push_back(Event::default().data(note.to_string()));
        }
    }
}

/// One logical SSE frame parsed off the wire.
struct ParsedSseEvent {
    /// The `event:` field, if any (`None` ⇒ the default unnamed event).
    event: Option<String>,
    /// The `data:` payload (multiple `data:` lines joined by `\n`).
    data: String,
}

/// Incremental parser for the SSE wire format (`event:`/`data:` lines, blank
/// line dispatches, `:`-comment keep-alives ignored). Fed arbitrary byte chunks;
/// emits one [`ParsedSseEvent`] per completed frame.
struct SseWireParser {
    /// Bytes received but not yet split into a complete line.
    buffer: String,
    event_type: Option<String>,
    data_lines: Vec<String>,
    /// Whether any field line has been seen since the last dispatch (so a lone
    /// blank line or a comment doesn't emit an empty frame).
    has_fields: bool,
}

impl SseWireParser {
    const fn new() -> Self {
        Self {
            buffer: String::new(),
            event_type: None,
            data_lines: Vec::new(),
            has_fields: false,
        }
    }

    /// Feed a chunk; return any frames completed by it.
    fn push(&mut self, bytes: &[u8]) -> Vec<ParsedSseEvent> {
        self.buffer.push_str(&String::from_utf8_lossy(bytes));
        let mut out = Vec::new();
        while let Some(pos) = self.buffer.find('\n') {
            let line: String = self.buffer.drain(..=pos).collect();
            if let Some(event) = self.process_line(line.trim_end_matches(['\n', '\r'])) {
                out.push(event);
            }
        }
        out
    }

    /// Flush the trailing partial line and any pending (unterminated) frame.
    fn finish(&mut self) -> Vec<ParsedSseEvent> {
        let mut out = Vec::new();
        if !self.buffer.is_empty() {
            let line = std::mem::take(&mut self.buffer);
            if let Some(event) = self.process_line(line.trim_end_matches(['\n', '\r'])) {
                out.push(event);
            }
        }
        if let Some(event) = self.dispatch() {
            out.push(event);
        }
        out
    }

    fn process_line(&mut self, line: &str) -> Option<ParsedSseEvent> {
        if line.is_empty() {
            return self.dispatch();
        }
        // A leading colon marks a comment line (SSE keep-alive); ignore it.
        if line.starts_with(':') {
            return None;
        }
        let (field, value) = match line.split_once(':') {
            // One optional leading space after the colon is stripped per spec.
            Some((f, v)) => (f, v.strip_prefix(' ').unwrap_or(v)),
            None => (line, ""),
        };
        match field {
            "event" => {
                self.event_type = Some(value.to_owned());
                self.has_fields = true;
            }
            "data" => {
                self.data_lines.push(value.to_owned());
                self.has_fields = true;
            }
            // `id:`/`retry:` and any unknown field are irrelevant to projection.
            _ => {}
        }
        None
    }

    fn dispatch(&mut self) -> Option<ParsedSseEvent> {
        if !self.has_fields {
            return None;
        }
        let event = ParsedSseEvent {
            event: self.event_type.take(),
            data: self.data_lines.join("\n"),
        };
        self.data_lines.clear();
        self.has_fields = false;
        Some(event)
    }
}

/// Collapse a fully-buffered SSE body into a single result string — the
/// non-SSE-client fallback for a streaming tool. Mirrors the streaming final
/// content: explicit `event: result` frames win, else the joined frame data.
fn collapse_sse_body(bytes: &[u8]) -> String {
    let mut parser = SseWireParser::new();
    let mut events = parser.push(bytes);
    events.extend(parser.finish());
    let (results, progress): (Vec<_>, Vec<_>) = events
        .into_iter()
        .partition(|e| e.event.as_deref() == Some("result"));
    if results.is_empty() {
        progress
            .into_iter()
            .map(|e| e.data)
            .collect::<Vec<_>>()
            .join("\n")
    } else {
        results.into_iter().map(|e| e.data).collect()
    }
}

/// Reconstruct an in-process HTTP request from a tool call's arguments.
fn build_request(
    tool: &McpTool,
    headers: &HeaderMap,
    arguments: &Value,
    csrf_header: &str,
    tenant_header: Option<&str>,
) -> Result<axum::http::Request<Body>, String> {
    // Fill the path template from top-level string-ish arguments.
    let mut path = tool.path_template.clone();
    for param in &tool.path_params {
        // axum catch-all params (`/files/{*rest}`) surface from `ApiDoc` with a
        // leading `*`. Clients address them by the bare name, and their value is
        // a multi-segment path whose `/` separators must be preserved (each
        // segment is still percent-encoded individually).
        let is_catch_all = param.starts_with('*');
        let arg_key = param.strip_prefix('*').unwrap_or(param);
        let raw = arguments
            .get(arg_key)
            .ok_or_else(|| format!("missing required path parameter `{arg_key}`"))?;
        // The tool schema advertises every path param as `{"type":"string"}`.
        // A string passes through; a number/bool coerces to a single safe
        // segment. `null`, an object, or an array has no valid single-segment
        // representation — replaying its literal `null`/JSON text as a path
        // segment could hit a real (possibly mutating) resource, so reject it
        // as invalid params (mapped to `-32602`) instead.
        let value = match raw {
            Value::String(s) => s.clone(),
            Value::Number(_) | Value::Bool(_) => raw.to_string(),
            _ => return Err(format!("path parameter `{arg_key}` must be a string")),
        };
        // Use the same full segment encoder the typed path helpers use, so an
        // MCP call accepts the same values a direct HTTP caller could pass.
        let encoded = if is_catch_all {
            crate::paths::encode_catch_all_param(&value)
        } else {
            crate::paths::encode_path_segment(&value)
        };
        path = replace_path_param(&path, param, &encoded);
    }

    // Build the query string from the `query` object, if any. The advertised
    // `inputSchema` types `query` as an object, so a present-but-non-object
    // value (`null`, a string, an array) is an invalid-params error rather than
    // being silently dropped — which would otherwise replay the tool with
    // defaulted/unfiltered query parameters.
    if tool.has_query
        && let Some(query) = arguments.get("query")
    {
        let Value::Object(map) = query else {
            return Err("`query` must be a JSON object".to_owned());
        };
        let mut pairs = QueryPairs::new();
        for (key, value) in map {
            // The tool's own `query` property names get the same rule its
            // nested object fields do — a dynamic query object can carry an
            // arbitrary key here, and `filter[x]` would otherwise reach the
            // decoder as structure rather than as the name the caller sent.
            if !is_expressible_field_name(key) {
                return Err(inexpressible_field_name("query"));
            }
            encode_query_arg(key, value, 1, &mut pairs)?;
        }
        if !pairs.pairs.is_empty() {
            let qs = serde_urlencoded::to_string(&pairs.pairs)
                .map_err(|e| format!("invalid query arguments: {e}"))?;
            path = format!("{path}?{qs}");
        }
    }

    let mut builder = axum::http::Request::builder()
        .method(tool.method.as_str())
        .uri(&path);

    // Replay the caller's headers verbatim so the dispatched request
    // authenticates and is attributed exactly as a direct HTTP call would:
    //  * `Authorization` — bearer-token (`RequireApiToken`) auth.
    //  * `Cookie` — session-based `#[secured]` routes / session tenancy.
    //  * `Idempotency-Key` — `IdempotencyLayer` dedupe on retried writes.
    //  * `Host` / `Forwarded` / `X-Forwarded-*` / `X-Real-IP` — subdomain
    //    tenancy host resolution and the rate limiter's client-IP attribution.
    for name in FORWARDED_HEADERS {
        // Forward *every* value, not just the first: a header like `Cookie` can
        // appear multiple times, and `CsrfLayer` inspects all `Cookie` headers
        // to detect cookie-tossing (duplicate CSRF cookies). Collapsing them to
        // one value here would let a replayed write slip past that check.
        for value in headers.get_all(*name) {
            builder = builder.header(*name, value);
        }
    }
    // Forward the configured CSRF token header (default `x-csrf-token`) so a
    // session-authenticated write tool passes `CsrfLayer`, which reads
    // `CsrfConfig::token_header` — not a hard-coded name.
    if let Some(value) = headers.get(csrf_header) {
        builder = builder.header(csrf_header, value);
    }
    // Header-based tenancy: forward the configured tenant header (default
    // `x-tenant-id`) so the `Tenant` extractor on the dispatched request
    // resolves the same tenant a direct HTTP caller would.
    if let Some(name) = tenant_header
        && let Some(value) = headers.get(name)
    {
        builder = builder.header(name, value);
    }

    let body = if tool.has_body {
        // The tool schema marks `body` required; reject a call that omits it
        // rather than dispatching an empty `{}` that a defaults-only DTO would
        // silently accept (violating the advertised contract).
        let payload = arguments
            .get("body")
            .ok_or_else(|| "missing required `body` argument".to_owned())?;
        builder = builder.header(header::CONTENT_TYPE, "application/json");
        Body::from(serde_json::to_vec(payload).unwrap_or_default())
    } else {
        Body::empty()
    };

    builder
        .body(body)
        .map_err(|e| format!("invalid request: {e}"))
}

/// Render a single query-argument value as a string for the query string.
/// Strings pass through unquoted; other scalars use their JSON text.
fn query_scalar(value: &Value) -> String {
    match value {
        Value::String(s) => s.clone(),
        other => other.to_string(),
    }
}

/// Upper bound on the pairs one tool call may expand its `query` object into.
///
/// `tools/call` arguments are client-supplied and only bounded by the request
/// body limit (32 MiB by default), while building a bracketed key copies its
/// whole prefix per child — quadratic in the argument size. Both this and
/// [`MAX_QUERY_BYTES`] bail out long before that matters, and well inside the
/// 64 KiB `http::Uri` limit the assembled request would hit anyway.
const MAX_QUERY_PAIRS: usize = 1024;

/// Upper bound on the total key+value bytes one tool call may expand into.
const MAX_QUERY_BYTES: usize = 8 * 1024;

/// Accumulator for the `key=value` pairs a tool call's `query` object expands
/// Ceiling on **nodes visited** while flattening, whether or not a node emits a
/// pair.
///
/// [`MAX_QUERY_PAIRS`] / [`MAX_QUERY_BYTES`] bound only what reaches the wire,
/// so a container of hundreds of thousands of `null` fields paid nothing: each
/// one still cost a formatted child key (copying the parent), and the all-null
/// check that rejects it runs only *after* the whole subtree is walked. Charging
/// every visit stops that traversal at a fixed bound instead, so a body inside
/// the documented limit cannot amplify into unbounded key-copying work.
const MAX_QUERY_NODES: usize = 4 * MAX_QUERY_PAIRS;

/// into, enforcing [`MAX_QUERY_PAIRS`] / [`MAX_QUERY_BYTES`].
struct QueryPairs {
    pairs: Vec<(String, String)>,
    bytes: usize,
    nodes: usize,
}

impl QueryPairs {
    const fn new() -> Self {
        Self {
            pairs: Vec::new(),
            bytes: 0,
            nodes: 0,
        }
    }

    /// Charge one visited node against [`MAX_QUERY_NODES`].
    ///
    /// Called for every node the encoder descends into — including the ones
    /// that emit nothing (`null`, and containers before their leaves are
    /// known) — so traversal cost is bounded independently of output size.
    fn visit(&mut self) -> Result<(), String> {
        self.nodes += 1;
        if self.nodes > MAX_QUERY_NODES {
            return Err(format!(
                "query arguments traverse more than {MAX_QUERY_NODES} values; \
                 move the field to a JSON body"
            ));
        }
        Ok(())
    }

    fn push(&mut self, key: &str, value: String) -> Result<(), String> {
        self.bytes = self
            .bytes
            .saturating_add(key.len())
            .saturating_add(value.len());
        if self.pairs.len() >= MAX_QUERY_PAIRS || self.bytes > MAX_QUERY_BYTES {
            return Err(format!(
                "query arguments expand past the dispatch limit of {MAX_QUERY_PAIRS} \
                 parameters / {MAX_QUERY_BYTES} bytes"
            ));
        }
        self.pairs.push((key.to_owned(), value));
        Ok(())
    }
}

/// True when a JSON field name survives the bracketed query encoding.
///
/// `[` and `]` are structure in that encoding and an empty name addresses the
/// append position, so a field called any of those cannot be carried: emitting
/// it verbatim would invent, move, or lose a nesting level on the way back in.
/// Applied to every name the encoder introduces — the tool's top-level `query`
/// properties as well as nested object fields.
fn is_expressible_field_name(name: &str) -> bool {
    !name.is_empty() && !name.contains('[') && !name.contains(']')
}

/// The error for a field name [`is_expressible_field_name`] rejects.
fn inexpressible_field_name(owner: &str) -> String {
    format!(
        "query argument `{owner}` has a field name that a query string cannot carry: a name \
         may not be empty or contain `[` or `]`, which are structure in the query encoding"
    )
}

/// Flatten one `query` argument into the `key=value` pairs the
/// [`Query<T>`](crate::extract::Query) extractor decodes (issue #1972).
///
/// The wire format is the extractor's own dialect
/// ([`query_string`](crate::query_string)), so a tool's advertised
/// `inputSchema` and the request dispatch actually agree:
///
/// * scalars render flat (`page=2`);
/// * an array of scalars expands to repeated keys (`tags=a&tags=b`) — the
///   `OpenAPI` `form`/`explode` shape;
/// * an array containing any container uses explicit positions
///   (`items[0][sku]=A-1`), so element order survives;
/// * an object nests by key (`filter[status]=open`).
///
/// A `null` **field** renders no pair at all: a query string has no null, and
/// emitting the literal text `null` would fail the handler's coercion instead
/// of decoding as the absent/`None` the caller meant.
///
/// # Errors
///
/// Refuses, rather than silently dispatching something the caller did not ask
/// for, when the argument cannot be expressed in a query string:
///
/// * an **empty** array or object — dropping it would turn a present-but-empty
///   value into an absent one (and 400 a required field downstream);
/// * a `null` **array element** — dropping it would shorten the sequence and
///   shift every later element;
/// * an object field name that is empty or contains `[` / `]` — those are
///   structure in the bracketed dialect, so interpolating one would invent or
///   lose a nesting level;
/// * nesting past
///   [`query_string::MAX_DEPTH`](crate::query_string::MAX_DEPTH), or an
///   expansion past [`MAX_QUERY_PAIRS`] / [`MAX_QUERY_BYTES`].
fn encode_query_arg(
    key: &str,
    value: &Value,
    depth: usize,
    out: &mut QueryPairs,
) -> Result<(), String> {
    if depth > crate::query_string::MAX_DEPTH {
        return Err(format!(
            "query argument `{key}` nests deeper than the maximum of {}",
            crate::query_string::MAX_DEPTH
        ));
    }
    // Bail before formatting any child key: a single absurd key would otherwise
    // be copied once per descendant.
    if key.len() > MAX_QUERY_BYTES {
        return Err(format!(
            "query argument key exceeds {MAX_QUERY_BYTES} bytes"
        ));
    }
    // Before descending, and so before any child key is formatted: a `null`
    // leaf emits no pair, so without this it would pay nothing for the parent
    // key its sibling count forces the encoder to copy.
    out.visit()?;
    let is_container = matches!(value, Value::Array(_) | Value::Object(_));
    let before = out.pairs.len();
    match value {
        Value::Null => {}
        Value::Array(items) if items.is_empty() => {
            return Err(format!(
                "query argument `{key}` is an empty array; a query string cannot express an \
                 empty sequence — omit the argument, or move the field to a JSON body"
            ));
        }
        Value::Array(items) => {
            if let Some(position) = items.iter().position(Value::is_null) {
                return Err(format!(
                    "query argument `{key}[{position}]` is null; a query string cannot \
                     express a null element — omit it, or move the field to a JSON body"
                ));
            }
            let all_scalar = items
                .iter()
                .all(|item| !matches!(item, Value::Array(_) | Value::Object(_)));
            if all_scalar {
                if let [only] = items.as_slice() {
                    // Repeated keys carry a sequence only from the *second*
                    // occurrence on: one `tags=only` pair is indistinguishable
                    // from a scalar, so `deserialize_any` (an untyped
                    // `serde_json::Value` target) would yield `"only"` for the
                    // `["only"]` the caller sent — and the field would turn
                    // back into an array on gaining a second element. The
                    // explicit position pins the kind. A typed `Vec` target
                    // decodes either form identically.
                    out.push(&format!("{key}[0]"), query_scalar(only))?;
                } else {
                    for item in items {
                        out.push(key, query_scalar(item))?;
                    }
                }
            } else {
                for (index, item) in items.iter().enumerate() {
                    encode_query_arg(&format!("{key}[{index}]"), item, depth + 1, out)?;
                }
            }
        }
        Value::Object(fields) if fields.is_empty() => {
            return Err(format!(
                "query argument `{key}` is an empty object; a query string cannot express an \
                 empty object — omit the argument, or move the field to a JSON body"
            ));
        }
        // Every key digit-only means every segment decodes as a *position*
        // (`query_string::classify_segment`), so the tree comes back a sequence
        // and an untyped target (`serde_json::Value`, which takes whatever
        // `deserialize_any` yields) receives an array where the caller sent an
        // object — with the tell that adding one named key silently flips it
        // back. A typed map target is unaffected, but the encoder cannot see
        // the target, so it refuses the shape rather than dispatch a value the
        // caller did not ask for. Mixed keys are fine: the named one forces the
        // decoder to promote the whole node to a map.
        // A `null` field emits no pair, so it cannot disambiguate anything: it
        // is invisible to the decoder. Judging the shape on *declared* keys let
        // `{"0": 5, "kind": null}` through, which reaches the wire as the bare
        // `counts[0]=5` this arm exists to refuse. So the check runs over the
        // fields that actually emit. An all-null object is left to fall through
        // to the collapse check below, which describes it better.
        Value::Object(fields)
            if {
                let mut emitting = fields
                    .iter()
                    .filter(|(_, value)| !value.is_null())
                    .peekable();
                emitting.peek().is_some()
                    && emitting.all(|(field, _)| {
                        !field.is_empty() && field.bytes().all(|b| b.is_ascii_digit())
                    })
            } =>
        {
            return Err(format!(
                "query argument `{key}` is an object whose field names are all numeric; a \
                 query string cannot tell that from a sequence — rename a field, or move the \
                 field to a JSON body"
            ));
        }
        Value::Object(fields) => {
            for (field, nested) in fields {
                if !is_expressible_field_name(field) {
                    return Err(inexpressible_field_name(key));
                }
                encode_query_arg(&format!("{key}[{field}]"), nested, depth + 1, out)?;
            }
        }
        scalar => out.push(key, query_scalar(scalar))?,
    }
    // A container every one of whose leaves is `null` emits no pair at all.
    // Left alone it would vanish — and inside an array the decoder would then
    // compact the gap, shortening the sequence. That is the same silent
    // alteration the empty-container and null-element checks above prevent, so
    // it is refused here rather than dispatched. A `null` **field** is exempt by
    // construction: it is not a container, so it stays the absent marker.
    if is_container && out.pairs.len() == before {
        return Err(format!(
            "query argument `{key}` carries no value; a query string cannot express a \
             container whose every field is null — omit it, or move the field to a JSON body"
        ));
    }
    Ok(())
}

/// Replace a single `{name}` / `{name:regex}` capture in a path template.
fn replace_path_param(path: &str, name: &str, value: &str) -> String {
    let mut out = String::with_capacity(path.len());
    let mut rest = path;
    while let Some(start) = rest.find('{') {
        out.push_str(&rest[..start]);
        let after = &rest[start + 1..];
        if let Some(end) = after.find('}') {
            let inner = &after[..end];
            let capture = inner.split(':').next().unwrap_or(inner).trim();
            if capture == name {
                out.push_str(value);
            } else {
                out.push('{');
                out.push_str(inner);
                out.push('}');
            }
            rest = &after[end + 1..];
        } else {
            out.push_str(&rest[start..]);
            return out;
        }
    }
    out.push_str(rest);
    out
}

// ── MCP tool-result helpers ───────────────────────────────────────

fn tool_ok(text: &str) -> Value {
    json!({
        "content": [ { "type": "text", "text": text } ],
        "isError": false,
    })
}

fn tool_error(text: &str) -> Value {
    json!({
        "content": [ { "type": "text", "text": text } ],
        "isError": true,
    })
}

// ── JSON-RPC envelope helpers ─────────────────────────────────────

fn success(id: Value, result: Value) -> Value {
    // Build by hand so `id`/`result` are moved (not borrowed via `json!`).
    let mut obj = serde_json::Map::new();
    obj.insert("jsonrpc".into(), json!("2.0"));
    obj.insert("id".into(), id);
    obj.insert("result".into(), result);
    Value::Object(obj)
}

fn error(id: Value, code: i64, message: &str) -> Value {
    let mut obj = serde_json::Map::new();
    obj.insert("jsonrpc".into(), json!("2.0"));
    obj.insert("id".into(), id);
    obj.insert("error".into(), json!({ "code": code, "message": message }));
    Value::Object(obj)
}

fn error_with_data(id: Value, code: i64, message: &str, data: Value) -> Value {
    let mut out = error(id, code, message);
    out["error"]["data"] = data;
    out
}

fn parse_error(message: &str) -> Value {
    json!({
        "jsonrpc": "2.0",
        "id": Value::Null,
        "error": { "code": -32700, "message": format!("parse error: {message}") },
    })
}

fn json_response(value: &Value) -> Response {
    (
        [(header::CONTENT_TYPE, "application/json")],
        serde_json::to_string(value).unwrap_or_else(|_| "{}".to_owned()),
    )
        .into_response()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::openapi::{SchemaEntry, SchemaKind};

    fn doc(method: &'static str, path: &'static str, op: &'static str) -> ApiDoc {
        ApiDoc {
            method,
            path,
            operation_id: op,
            success_status: 200,
            response: Some(SchemaEntry {
                name: "Todo",
                kind: SchemaKind::Ref,
                identity: None,
            }),
            ..Default::default()
        }
    }

    #[test]
    fn strip_total_metric_drops_only_total() {
        // Inner `total` is dropped; the `db` metric (with a comma-free quoted
        // desc) is preserved so the outer fallback's real `/mcp` `total` is the
        // only one on the response.
        assert_eq!(
            strip_total_metric("total;dur=5.000, db;dur=1.250;desc=\"2 queries\""),
            Some("db;dur=1.250;desc=\"2 queries\"".to_owned())
        );
        // Metric order and a leading non-total entry are preserved.
        assert_eq!(
            strip_total_metric("app;dur=1.500, total;dur=42.000"),
            Some("app;dur=1.500".to_owned())
        );
        // A total-only header forwards nothing.
        assert_eq!(strip_total_metric("total;dur=9.000"), None);
        // The metric-name token is matched case-insensitively before `;`/`=`,
        // so a bare `total` (no params) is also dropped.
        assert_eq!(strip_total_metric("Total"), None);
        // Empty / whitespace-only input yields nothing.
        assert_eq!(strip_total_metric("  "), None);
    }

    #[test]
    fn opt_in_required_without_hatch() {
        let mut d = doc("GET", "/a", "a");
        assert!(!should_expose(&d, false), "no opt-in => not exposed");
        d.mcp_tool = true;
        assert!(should_expose(&d, false));
    }

    #[test]
    fn exclude_always_wins() {
        let mut d = doc("GET", "/a", "a");
        d.mcp_tool = true;
        d.mcp_exclude = true;
        assert!(!should_expose(&d, false));
        assert!(!should_expose(&d, true));
    }

    #[test]
    fn hatch_includes_reads_excludes_unopted_writes() {
        let read = doc("GET", "/a", "a");
        let write = doc("POST", "/a", "b");
        assert!(should_expose(&read, true));
        assert!(!should_expose(&write, true), "mutating verb needs opt-in");
    }

    #[test]
    fn hatch_still_allows_opted_in_writes() {
        let mut write = doc("POST", "/a", "b");
        write.mcp_tool = true;
        assert!(should_expose(&write, true));
    }

    #[test]
    fn html_routes_are_ineligible() {
        let mut d = doc("GET", "/page", "page");
        d.response = None; // HTML/Maud route
        d.mcp_tool = true;
        assert!(!should_expose(&d, false));
    }

    #[test]
    fn no_content_delete_with_opt_in_is_eligible() {
        // A 204 No Content route (e.g. the repository macro's generated
        // DELETE) has no response schema *by contract*, not because it is an
        // HTML route. An explicit opt-in must expose it.
        let mut d = doc("DELETE", "/api/widgets/{id}", "widget_api_delete");
        d.response = None;
        d.success_status = 204;
        d.mcp_tool = true;
        assert!(
            should_expose(&d, false),
            "opted-in 204 route is a deliberate empty success contract"
        );
    }

    #[test]
    fn reset_content_205_with_opt_in_is_eligible() {
        // 205 Reset Content is the other empty-body-by-contract status; the
        // exemption is a shared predicate, not a hard-coded 204 literal.
        let mut d = doc("POST", "/api/forms/clear", "clear_form");
        d.response = None;
        d.success_status = 205;
        d.mcp_tool = true;
        assert!(should_expose(&d, false));
        let tools = derive_tools(&[d], false, None);
        assert_eq!(tools.len(), 1, "opted-in 205 route must derive a tool");
    }

    // ── Agent authority carried onto derived tools (#1691) ──────────────────
    //
    // The authority envelope is what makes a `tools/call` auditable with a
    // *compile-known* blast radius: the grant name, the effect set, and the
    // reversibility all come from the const assertions the macro already made
    // against the handler body. Losing it between `ApiDoc` and `McpToolInfo`
    // would silently downgrade a governed tool to `reversibility=unknown` in
    // the audit trail and to `ungoverned_tools` in the manifest.

    /// One construction site for the test grants, so the shape of
    /// [`crate::agent_authority::Grant`] is pinned in exactly one place here.
    const fn test_grant(
        name: &'static str,
        reversibility: crate::agent_authority::Reversibility,
    ) -> crate::agent_authority::Grant {
        crate::agent_authority::Grant {
            name,
            writes: &[],
            unbounded_writes: &[],
            tenant_scope: crate::agent_authority::TenantScope::Scoped,
            outbound: &[],
            webhooks: &[],
            jobs: &[],
            rate: None,
            spend: None,
            reversibility,
            location: "autumn/src/mcp.rs",
        }
    }

    /// Likewise for [`crate::agent_authority::AgentAuthority`].
    const fn test_authority(
        action: &'static str,
        grant: &'static crate::agent_authority::Grant,
    ) -> crate::agent_authority::AgentAuthority {
        crate::agent_authority::AgentAuthority {
            action,
            module_path: "autumn_web::mcp::tests",
            location: "autumn/src/mcp.rs",
            grant,
            effects: &[],
            asserted_effect_free_sites: 0,
            asserted_effect_free: &[],
        }
    }

    static REVERSIBLE_GRANT: crate::agent_authority::Grant = test_grant(
        "DraftOnly",
        crate::agent_authority::Reversibility::Reversible,
    );
    static COMPENSABLE_GRANT: crate::agent_authority::Grant = test_grant(
        "RefundDrafter",
        crate::agent_authority::Reversibility::Compensable,
    );
    static IRREVERSIBLE_GRANT: crate::agent_authority::Grant = test_grant(
        "PayoutSender",
        crate::agent_authority::Reversibility::Irreversible,
    );

    static REVERSIBLE_AUTHORITY: crate::agent_authority::AgentAuthority =
        test_authority("draft_note", &REVERSIBLE_GRANT);
    static COMPENSABLE_AUTHORITY: crate::agent_authority::AgentAuthority =
        test_authority("draft_refund", &COMPENSABLE_GRANT);
    static IRREVERSIBLE_AUTHORITY: crate::agent_authority::AgentAuthority =
        test_authority("send_payout", &IRREVERSIBLE_GRANT);

    /// An opted-in tool doc carrying (or not carrying) an authority.
    fn governed_doc(
        method: &'static str,
        op: &'static str,
        authority: Option<&'static crate::agent_authority::AgentAuthority>,
    ) -> ApiDoc {
        let mut d = doc(method, "/api/refunds", op);
        d.mcp_tool = true;
        d.agent_authority = authority;
        d
    }

    #[test]
    fn derive_tools_carries_the_handler_authority_onto_the_tool() {
        let tools = derive_tools(
            &[governed_doc(
                "POST",
                "draft_refund",
                Some(&COMPENSABLE_AUTHORITY),
            )],
            false,
            None,
        );
        assert_eq!(tools.len(), 1, "the opted-in route must derive a tool");
        let authority = tools[0]
            .agent_authority()
            .expect("a governed handler's tool must carry its authority envelope");
        assert_eq!(authority.grant.name, "RefundDrafter");
        assert_eq!(
            authority.grant.reversibility,
            crate::agent_authority::Reversibility::Compensable
        );
        assert_eq!(authority.action, "draft_refund");
    }

    #[test]
    fn derive_tools_leaves_an_ungoverned_tool_without_an_authority() {
        // `None` must stay `None`: it is the signal the manifest uses to list a
        // mutating tool under `ungoverned_tools`, so inventing one here would
        // hide exactly the gap that check exists to find.
        let tools = derive_tools(&[governed_doc("POST", "draft_refund", None)], false, None);
        assert_eq!(tools.len(), 1);
        assert!(
            tools[0].agent_authority().is_none(),
            "a handler with no #[agent_operable] derives an ungoverned tool"
        );
    }

    #[test]
    fn destructive_hint_follows_declared_reversibility() {
        let hint = |op, authority| {
            let tools = derive_tools(&[governed_doc("POST", op, authority)], false, None);
            tools[0].annotations().get("destructiveHint").cloned()
        };

        // A declared authority can *raise* the warning on a verb that says
        // nothing by itself.
        assert_eq!(
            hint("send_payout", Some(&IRREVERSIBLE_AUTHORITY)),
            Some(json!(true)),
            "an irreversible action is destructive"
        );
        assert_eq!(
            hint("draft_refund", Some(&COMPENSABLE_AUTHORITY)),
            Some(json!(true)),
            "a compensable action still needs a compensating step, so warn"
        );
        assert_eq!(
            hint("draft_note", Some(&REVERSIBLE_AUTHORITY)),
            Some(json!(false)),
            "a POST proved to be bounded writes only is explicitly NOT destructive"
        );
    }

    #[test]
    fn destructive_hint_falls_back_to_the_verb_rule_when_ungoverned() {
        // Nothing changes for the ungoverned majority: POST carries no hint and
        // DELETE stays flagged, exactly as before #1691.
        let post = derive_tools(&[governed_doc("POST", "draft_refund", None)], false, None);
        assert!(
            post[0].annotations().get("destructiveHint").is_none(),
            "an ungoverned POST keeps the verb rule's silence: {:?}",
            post[0].annotations()
        );

        let delete = derive_tools(
            &[governed_doc("DELETE", "delete_refund", None)],
            false,
            None,
        );
        assert_eq!(
            delete[0].annotations().get("destructiveHint"),
            Some(&json!(true)),
            "DELETE stays the destructive verb when no authority is declared"
        );
    }

    #[test]
    fn the_delete_verb_is_a_floor_a_reversible_grant_cannot_clear() {
        // `reversible` means the analyser proved the effect set is bounded
        // writes only — and `delete_by_id` IS a bounded write, so a hard row
        // delete reaches this shape. It does not mean the row can be put back;
        // nothing checks for soft-delete or versioning. Since an MCP client
        // skips its confirmation prompt on `destructiveHint: false`, the verb
        // stays a floor: the grant may add the warning, never remove it
        // (issue #1691 review, P2-1).
        let tools = derive_tools(
            &[governed_doc(
                "DELETE",
                "archive_note",
                Some(&REVERSIBLE_AUTHORITY),
            )],
            false,
            None,
        );
        assert_eq!(
            tools[0].annotations().get("destructiveHint"),
            Some(&json!(true)),
            "one unproved adjective in a grant must not clear a DELETE's warning: {:?}",
            tools[0].annotations()
        );
    }

    // ── Argument names are intersected with the tool's surface (#1691 P2-2) ──

    /// A tool with one path param plus a body, so all three name categories
    /// (path param, reserved key, unknown) are reachable.
    fn tool_with_path_param() -> McpTool {
        let mut t = tool("POST", "/api/refunds/{id}", true, false);
        t.path_params = vec!["id".to_owned()];
        t
    }

    #[test]
    fn argument_names_records_the_tools_own_surface_verbatim() {
        let names = argument_names(
            &tool_with_path_param(),
            &json!({ "body": {}, "id": "7", "query": {} }),
        );
        assert_eq!(names, "body,id,query", "sorted, and no unknown count");
    }

    #[test]
    fn argument_names_counts_unrecognised_keys_instead_of_quoting_them() {
        // `build_request` reads only `body`/`query`/the path params and ignores
        // everything else, and nothing rejects extra properties — so every other
        // key is caller-authored text that must never reach a durable row.
        let hostile = "\n2026-09-02T00:00:00Z INFO agent tool call actor=admin";
        let mut args = serde_json::Map::new();
        args.insert("body".to_owned(), json!({}));
        args.insert(hostile.to_owned(), json!(1));
        args.insert("ssn-123-45-6789".to_owned(), json!(2));
        let names = argument_names(&tool_with_path_param(), &Value::Object(args));
        assert_eq!(names, "body,+2 unknown");
        assert!(
            !names.contains('\n') && !names.contains("ssn-"),
            "no caller-chosen byte may appear: {names}"
        );
    }

    #[test]
    fn argument_names_of_an_all_unknown_call_is_only_a_count() {
        let names = argument_names(
            &tool_with_path_param(),
            &json!({ "\u{1f648}": 1, "../../etc": 2 }),
        );
        assert_eq!(names, "+2 unknown");
    }

    #[test]
    fn argument_names_addresses_a_catch_all_param_by_its_bare_name() {
        // `ApiDoc` surfaces `/files/{*rest}` as `*rest`; clients send `rest`,
        // and `build_request` strips the star to match. The audit view must
        // strip it the same way or a legitimate param reads as unknown.
        let mut t = tool("GET", "/files/{*rest}", false, false);
        t.path_params = vec!["*rest".to_owned()];
        assert_eq!(argument_names(&t, &json!({ "rest": "a/b" })), "rest");
    }

    #[test]
    fn argument_names_of_a_non_object_is_empty() {
        assert_eq!(argument_names(&tool_with_path_param(), &json!(null)), "");
    }

    #[test]
    fn render_effects_caps_the_list_and_marks_the_truncation() {
        use crate::agent_authority::{Effect, EffectKind, EffectProvenance};

        const fn effect(subject: &'static str) -> Effect {
            Effect {
                kind: EffectKind::Write,
                subject,
                location: "mcp.rs:0",
                provenance: EffectProvenance::Syntactic,
            }
        }
        // One over the cap, so the elision is exercised rather than the
        // boundary being silently the whole list.
        const EFFECTS: [Effect; MAX_AUDITED_EFFECTS + 1] =
            [effect("Refund"); MAX_AUDITED_EFFECTS + 1];

        let rendered = render_effects(&EFFECTS);
        assert_eq!(
            rendered.matches("write:Refund").count(),
            MAX_AUDITED_EFFECTS,
            "an oversized effect set is capped, not spilled into every row: {rendered}"
        );
        assert!(
            rendered.ends_with(",\u{2026}"),
            "the cap must be visible in the row, not silent: {rendered}"
        );
        assert_eq!(render_effects(&EFFECTS[..1]), "write:Refund");
        assert_eq!(render_effects(&[]), "");
    }

    #[test]
    fn only_a_completed_stream_and_an_intact_body_count_as_success() {
        // The disposition is the half of the verdict the status line cannot
        // supply: a streaming tool answers `200` before it has done anything,
        // and a buffered one can answer `200` and then fail to hand its body
        // over (issue #1691 review rounds 1 and 2).
        assert!(Disposition::Settled.is_success());
        assert!(Disposition::Stream(StreamState::Completed).is_success());
        assert!(!Disposition::Stream(StreamState::Aborted).is_success());
        assert!(!Disposition::Stream(StreamState::Errored).is_success());
        assert!(!Disposition::Buffered(BufferedFailure::Overflow).is_success());
        assert!(!Disposition::Buffered(BufferedFailure::BodyError).is_success());

        // Each failing ending names itself in exactly one metadata key, so a
        // sink can tell the three stream endings apart from a lost body.
        assert_eq!(
            Disposition::Stream(StreamState::Aborted).stream_state(),
            Some("aborted")
        );
        assert_eq!(Disposition::Stream(StreamState::Aborted).result(), None);
        assert_eq!(
            Disposition::Buffered(BufferedFailure::Overflow).result(),
            Some("body_overflow")
        );
        assert_eq!(
            Disposition::Buffered(BufferedFailure::BodyError).result(),
            Some("body_error")
        );
        assert_eq!(
            Disposition::Buffered(BufferedFailure::Overflow).stream_state(),
            None
        );
        assert_eq!(Disposition::Settled.stream_state(), None);
        assert_eq!(Disposition::Settled.result(), None);
    }

    #[tokio::test]
    async fn a_length_limit_anywhere_in_the_source_chain_is_an_overflow() {
        // `to_bytes` collects through `http_body_util::Limited`, which reports
        // the cap as a `LengthLimitError` *nested* inside the error it hands
        // back. Classifying on the outer type alone would record every overflow
        // as a generic `body_error` — so the error under test is produced by the
        // very call the buffered path makes, not by a hand-built stand-in.
        let overflow = axum::body::to_bytes(axum::body::Body::from(vec![0_u8; 32]), 8)
            .await
            .expect_err("a body past the cap must not collect");
        assert_eq!(
            BufferedFailure::classify(&overflow),
            BufferedFailure::Overflow
        );
        assert_eq!(BufferedFailure::Overflow.as_str(), "body_overflow");

        let other = axum::Error::new(std::io::Error::other("peer went away"));
        assert_eq!(
            BufferedFailure::classify(&other),
            BufferedFailure::BodyError
        );
        assert_eq!(BufferedFailure::BodyError.as_str(), "body_error");
    }

    #[test]
    fn read_only_hint_is_unaffected_by_the_authority() {
        // `readOnlyHint` is a statement about the HTTP verb, not about how hard
        // the effect is to undo — the two hints must not be conflated.
        let tools = derive_tools(
            &[governed_doc(
                "POST",
                "draft_refund",
                Some(&REVERSIBLE_AUTHORITY),
            )],
            false,
            None,
        );
        assert_eq!(tools[0].annotations()["readOnlyHint"], json!(false));
    }

    #[test]
    fn opted_in_202_is_skipped_not_exposed() {
        // 202 Accepted does not guarantee an empty body, so a schema-less 202
        // route stays behind the JSON-out gate even when opted in.
        let mut d = doc("POST", "/api/enqueue", "enqueue");
        d.response = None;
        d.success_status = 202;
        d.mcp_tool = true;
        assert!(!should_expose(&d, false));
        assert!(derive_tools(&[d], false, None).is_empty());
    }

    #[test]
    fn no_content_without_opt_in_stays_hidden() {
        let mut d = doc("DELETE", "/api/widgets/{id}", "widget_api_delete");
        d.response = None;
        d.success_status = 204;
        assert!(!should_expose(&d, false), "no opt-in => hidden");
    }

    #[test]
    fn no_content_under_hatch_pins_behavior() {
        // A read-only, deliberately body-less endpoint under the whole-API
        // hatch: 204 is a structural JSON-API signal (unlike an HTML route's
        // 200-with-body), so the hatch includes it.
        let mut d = doc("GET", "/api/ping", "ping");
        d.response = None;
        d.success_status = 204;
        assert!(should_expose(&d, true));
        assert!(!should_expose(&d, false), "still requires hatch or opt-in");
    }

    #[test]
    fn derive_tools_keeps_opted_in_no_content_route() {
        // The "opted in but no JSON response" warn/skip block in
        // `derive_tools` must not silently drop a 204 route that
        // `should_expose` accepts.
        let mut d = doc("DELETE", "/api/widgets/{id}", "widget_api_delete");
        d.response = None;
        d.success_status = 204;
        d.mcp_tool = true;
        let tools = derive_tools(&[d], false, None);
        assert_eq!(tools.len(), 1, "204 opt-in must derive a tool");
        assert_eq!(tools[0].name, "widget_api_delete");
        assert_eq!(tools[0].annotations["destructiveHint"], true);
    }

    #[test]
    fn streaming_tool_is_eligible_without_response_schema() {
        // A streaming tool returns `Sse` (no JSON response schema); the `stream`
        // flag exempts it from the JSON-out gate that excludes HTML routes.
        let mut d = doc("GET", "/api/search", "search");
        d.response = None;
        d.mcp_stream = true;
        // Still requires opt-in: `stream` alone (no `mcp`) is not exposed.
        assert!(
            !should_expose(&d, false),
            "stream without opt-in stays hidden"
        );
        d.mcp_tool = true;
        assert!(
            should_expose(&d, false),
            "opted-in streaming tool is exposed"
        );
        // Exclusion still wins.
        d.mcp_exclude = true;
        assert!(!should_expose(&d, false));
    }

    #[test]
    fn streaming_get_is_included_under_the_hatch() {
        // Under `expose_all`, a read-only streaming GET is auto-included even
        // without an explicit `mcp` tag (and despite having no response schema).
        let mut d = doc("GET", "/api/search", "search");
        d.response = None;
        d.mcp_stream = true;
        assert!(should_expose(&d, true));
        // A mutating streaming verb still needs an explicit opt-in.
        let mut w = doc("POST", "/api/search", "search2");
        w.response = None;
        w.mcp_stream = true;
        assert!(!should_expose(&w, true));
    }

    #[test]
    fn accept_header_gates_sse() {
        assert!(accept_includes_event_stream(
            "application/json, text/event-stream"
        ));
        assert!(accept_includes_event_stream("text/event-stream;q=1.0"));
        assert!(accept_includes_event_stream("text/*"));
        // A plain JSON client (or a generic `*/*`) does not opt in to SSE.
        assert!(!accept_includes_event_stream("application/json"));
        assert!(!accept_includes_event_stream("*/*"));
    }

    #[test]
    fn sse_parser_splits_frames_and_joins_data() {
        let mut p = SseWireParser::new();
        // A multi-data frame, an `event:`-typed frame, and a comment keep-alive.
        let mut events = p.push(b"data: line1\ndata: line2\n\n");
        events.extend(p.push(b": keep-alive\n\nevent: result\ndata: final\n\n"));
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].event, None);
        assert_eq!(events[0].data, "line1\nline2");
        assert_eq!(events[1].event.as_deref(), Some("result"));
        assert_eq!(events[1].data, "final");
    }

    #[test]
    fn sse_parser_handles_chunk_boundaries_mid_frame() {
        // A frame split across chunk boundaries must still parse once complete.
        let mut p = SseWireParser::new();
        assert!(p.push(b"data: hel").is_empty());
        assert!(p.push(b"lo\n").is_empty());
        let events = p.push(b"\n");
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].data, "hello");
    }

    #[test]
    fn progress_notification_plain_and_structured() {
        let token = json!("tok");
        // Plain text → message + running counter.
        let plain = progress_notification(&token, 2.0, "working");
        assert_eq!(plain["method"], "notifications/progress");
        assert_eq!(plain["params"]["progressToken"], "tok");
        assert_eq!(plain["params"]["progress"], 2.0);
        assert_eq!(plain["params"]["message"], "working");
        // Structured JSON with a numeric `progress` → forwarded verbatim.
        let structured = progress_notification(
            &token,
            99.0,
            r#"{"progress":50,"total":100,"message":"half"}"#,
        );
        assert_eq!(structured["params"]["progress"], 50);
        assert_eq!(structured["params"]["total"], 100);
        assert_eq!(structured["params"]["message"], "half");
    }

    #[test]
    fn collapse_sse_body_prefers_result_frames() {
        // No `result` frame: data joined.
        let joined = collapse_sse_body(b"data: a\n\ndata: b\n\n");
        assert_eq!(joined, "a\nb");
        // With a `result` frame: only the result content is kept.
        let result = collapse_sse_body(b"data: progress\n\nevent: result\ndata: done\n\n");
        assert_eq!(result, "done");
    }

    #[test]
    fn annotations_track_method() {
        assert_eq!(
            annotations_for("GET", "t", None)["readOnlyHint"],
            json!(true)
        );
        assert_eq!(
            annotations_for("POST", "t", None)["readOnlyHint"],
            json!(false)
        );
        assert_eq!(
            annotations_for("DELETE", "t", None)["destructiveHint"],
            json!(true)
        );
        assert!(
            annotations_for("POST", "t", None)
                .get("destructiveHint")
                .is_none()
        );
    }

    #[test]
    fn input_schema_includes_path_param_and_body() {
        let mut d = doc("POST", "/users/{id}", "create");
        d.path_params = &["id"];
        d.request_body = Some(SchemaEntry {
            name: "NewUser",
            kind: SchemaKind::Ref,
            identity: None,
        });
        let schema = build_input_schema(
            &d,
            &serde_json::Map::new(),
            &crate::openapi::SchemaComponentIndex::default(),
        );
        assert_eq!(schema["type"], "object");
        assert!(schema["properties"]["id"].is_object());
        assert!(schema["properties"]["body"].is_object());
        let required = schema["required"].as_array().unwrap();
        assert!(required.contains(&json!("id")));
        assert!(required.contains(&json!("body")));
    }

    #[test]
    fn detect_degradation_flags_opaque_body_and_query() {
        // Both `query` and `body` resolve to the bare object placeholder.
        let schema = json!({
            "type": "object",
            "properties": {
                "query": { "type": "object", "title": "Q" },
                "body": { "type": "object", "title": "B" },
            },
        });
        let degradations = detect_schema_degradations(&schema, true, true);
        assert!(degradations.contains(&SchemaDegradation::OpaqueQuery));
        assert!(degradations.contains(&SchemaDegradation::OpaqueBody));
    }

    #[test]
    fn detect_degradation_ignores_field_accurate_schemas() {
        // A real query object (with `properties`) and a real body: no warning.
        let schema = json!({
            "type": "object",
            "properties": {
                "query": {
                    "type": "object",
                    "properties": { "page": { "type": "integer" }, "tags": { "type": "array", "items": { "type": "string" } } },
                },
                "body": { "$ref": "#/$defs/Real" },
            },
            "$defs": { "Real": { "type": "object", "properties": { "a": { "type": "string" } } } },
        });
        assert!(detect_schema_degradations(&schema, true, true).is_empty());
    }

    #[test]
    fn detect_degradation_accepts_structured_query_fields() {
        // Nested objects, arrays of objects, `$ref`s and their nullable
        // (`oneOf [.., {"type":"null"}]`) forms are all round-trippable now that
        // `Query<T>` decodes the bracketed dialect `build_request` emits
        // (issue #1972), so none of them may be reported as a degradation.
        let schema = json!({
            "type": "object",
            "properties": {
                "query": {
                    "type": "object",
                    "properties": {
                        "filter": { "type": "object", "properties": { "min": { "type": "integer" } } },
                        "rows": { "type": "array", "items": { "type": "object", "properties": { "k": { "type": "string" } } } },
                        "ref_filter": { "$ref": "#/$defs/Filter" },
                        "maybe_filter": { "oneOf": [ { "$ref": "#/$defs/Filter" }, { "type": "null" } ] },
                        "maybe_rows": { "oneOf": [
                            { "type": "array", "items": { "$ref": "#/$defs/Filter" } },
                            { "type": "null" },
                        ] },
                    },
                },
            },
            "$defs": { "Filter": { "type": "object", "properties": { "min": { "type": "integer" } } } },
        });
        assert!(
            detect_schema_degradations(&schema, true, false).is_empty(),
            "structured query fields are honored, not degraded"
        );
    }

    #[test]
    fn an_actor_id_keeps_only_id_characters_and_is_capped() {
        assert_eq!(clean_actor("user-42").as_deref(), Some("user-42"));
        assert_eq!(clean_actor("a\nb\r\u{0}c").as_deref(), Some("abc"));
        assert_eq!(clean_actor("\n"), None);
        assert_eq!(
            clean_actor("ad\u{202E}min\u{200B}").as_deref(),
            Some("admin")
        );
        // Line separators and soft or joining marks are not control characters.
        assert_eq!(clean_actor("a\u{2028}b\u{2029}c").as_deref(), Some("abc"));
        assert_eq!(clean_actor("a\u{2060}b\u{00AD}c").as_deref(), Some("abc"));
        // Ordinary ids keep their punctuation.
        assert_eq!(
            clean_actor("agent:key_1.x@example.com").as_deref(),
            Some("agent:key_1.x@example.com")
        );
        assert_eq!(clean_actor(&"x".repeat(500)).map(|a| a.len()), Some(128));
    }

    #[test]
    fn encode_query_arg_renders_the_extractor_dialect() {
        let mut pairs = QueryPairs::new();
        encode_query_arg("page", &json!(2), 1, &mut pairs).expect("scalar");
        encode_query_arg("tags", &json!(["a", "b"]), 1, &mut pairs).expect("scalar array");
        encode_query_arg("filter", &json!({ "status": "open" }), 1, &mut pairs).expect("object");
        encode_query_arg("items", &json!([{ "sku": "A" }]), 1, &mut pairs).expect("object array");
        assert_eq!(
            pairs.pairs,
            vec![
                ("page".to_owned(), "2".to_owned()),
                ("tags".to_owned(), "a".to_owned()),
                ("tags".to_owned(), "b".to_owned()),
                ("filter[status]".to_owned(), "open".to_owned()),
                ("items[0][sku]".to_owned(), "A".to_owned()),
            ]
        );
    }

    #[test]
    fn encode_query_arg_omits_null_fields_rather_than_stringifying_them() {
        // A null argument is the documented "absent" marker: no pair, no error.
        let mut pairs = QueryPairs::new();
        encode_query_arg("page", &json!(null), 1, &mut pairs).expect("null");
        assert!(
            pairs.pairs.is_empty(),
            "a null argument renders no pair: {:?}",
            pairs.pairs
        );

        // The same holds for a null field alongside a carried one — only a
        // container that collapses ENTIRELY is refused (see the collapse test).
        let mut pairs = QueryPairs::new();
        encode_query_arg(
            "filter",
            &json!({ "status": null, "kind": "a" }),
            1,
            &mut pairs,
        )
        .expect("null field beside a carried one");
        assert_eq!(
            pairs.pairs,
            vec![("filter[kind]".to_owned(), "a".to_owned())]
        );
    }

    #[test]
    fn encode_query_arg_refuses_values_a_query_string_cannot_carry() {
        // Each of these would otherwise dispatch something the caller did not
        // ask for: a vanished field, a shortened sequence, or an invented
        // nesting level (issue #1972 review follow-ups).
        for (label, value) in [
            ("empty array", json!({ "tags": [] })),
            ("empty object", json!({ "filter": {} })),
            ("empty nested array", json!({ "matrix": [[1], []] })),
            ("null array element", json!({ "tags": ["a", null] })),
            (
                "null object-array element",
                json!({ "items": [null, { "sku": "A" }] }),
            ),
            ("bracket in field name", json!({ "filter": { "a[b]": 1 } })),
            ("empty field name", json!({ "filter": { "": 1 } })),
        ] {
            let mut pairs = QueryPairs::new();
            let Value::Object(fields) = &value else {
                unreachable!()
            };
            let result = fields
                .iter()
                .try_for_each(|(key, v)| encode_query_arg(key, v, 1, &mut pairs));
            assert!(
                result.is_err(),
                "{label} must be refused, not silently dropped"
            );
        }
    }

    #[test]
    fn encode_query_arg_refuses_containers_that_collapse_to_nothing() {
        // Codex P2: every field of an element being null emits no pair, so the
        // element would vanish and the decoder would compact the gap — the same
        // silent shortening a direct null element is already refused for.
        let mut pairs = QueryPairs::new();
        assert!(
            encode_query_arg(
                "items",
                &json!([{ "note": null }, { "note": "x" }]),
                1,
                &mut pairs
            )
            .is_err(),
            "an all-null element must not silently shorten the sequence"
        );

        // Same one level up, for an object-typed field.
        let mut pairs = QueryPairs::new();
        assert!(encode_query_arg("filter", &json!({ "note": null }), 1, &mut pairs).is_err());

        // A `null` FIELD is still the documented absent marker, not a collapse.
        let mut pairs = QueryPairs::new();
        encode_query_arg("filter", &json!({ "a": 1, "b": null }), 1, &mut pairs).expect("partial");
        assert_eq!(pairs.pairs, vec![("filter[a]".to_owned(), "1".to_owned())]);
    }

    #[test]
    fn top_level_query_keys_are_validated_like_nested_field_names() {
        // Codex P2: a dynamic query object can carry an arbitrary top-level
        // key, and `filter[x]` would otherwise reach the decoder as structure.
        assert!(!is_expressible_field_name("filter[x]"));
        assert!(!is_expressible_field_name(""));
        assert!(!is_expressible_field_name("a]b"));
        assert!(is_expressible_field_name("filter"));
        assert!(is_expressible_field_name("sort_by"));
    }

    #[test]
    fn encode_query_arg_bounds_its_expansion() {
        // A wide array cannot be turned into an unbounded pair list: expansion
        // stops at the dispatch limit instead of building a giant URI.
        let wide: Vec<Value> = (0..(MAX_QUERY_PAIRS * 2)).map(|i| json!(i)).collect();
        let mut pairs = QueryPairs::new();
        assert!(encode_query_arg("tags", &Value::Array(wide), 1, &mut pairs).is_err());

        // A single absurd key is refused before any child key is formatted.
        let mut pairs = QueryPairs::new();
        let huge = "k".repeat(MAX_QUERY_BYTES + 1);
        assert!(encode_query_arg(&huge, &json!({ "a": 1 }), 1, &mut pairs).is_err());
    }

    #[test]
    fn encode_query_arg_charges_null_leaves_for_the_traversal_they_cost() {
        // Codex P2: `null` emits no pair, so a container of them paid nothing
        // against the pair/byte limits while still forcing one formatted child
        // key per field — the all-null check only fires after the full walk.
        // The traversal budget now stops it early.
        let nulls: serde_json::Map<String, Value> = (0..(MAX_QUERY_NODES * 2))
            .map(|i| (format!("f{i}"), Value::Null))
            .collect();
        let mut pairs = QueryPairs::new();
        let err = encode_query_arg("root", &Value::Object(nulls), 1, &mut pairs)
            .expect_err("a traversal this wide must be refused");
        assert!(err.contains("traverse"), "{err}");
        assert!(
            pairs.nodes <= MAX_QUERY_NODES + 1,
            "traversal must stop at the bound, visited {}",
            pairs.nodes
        );

        // The budget is generous enough that ordinary nesting is unaffected.
        let mut pairs = QueryPairs::new();
        encode_query_arg(
            "filter",
            &json!({ "status": "open", "tag": null }),
            1,
            &mut pairs,
        )
        .expect("a small object still encodes");
    }

    #[test]
    fn encode_query_arg_refuses_an_all_numeric_keyed_object() {
        // Codex P2: every key digit-only decodes as a sequence, so an untyped
        // target would receive an array where the caller sent an object.
        let mut pairs = QueryPairs::new();
        let err = encode_query_arg("counts", &json!({ "0": 5, "1": 6 }), 1, &mut pairs)
            .expect_err("an all-numeric-keyed object is ambiguous on the wire");
        assert!(err.contains("all numeric"), "{err}");

        // One named key is enough to force map promotion on the way back in,
        // so the mixed shape stays expressible.
        let mut pairs = QueryPairs::new();
        encode_query_arg("counts", &json!({ "0": 5, "total": 6 }), 1, &mut pairs)
            .expect("a mixed-key object round-trips as a map");

        // The check is per-object, so it also catches a nested one.
        let mut pairs = QueryPairs::new();
        assert!(encode_query_arg("filter", &json!({ "by": { "7": "x" } }), 1, &mut pairs).is_err());

        // An empty field name still gets its own, more specific error.
        let mut pairs = QueryPairs::new();
        let err = encode_query_arg("counts", &json!({ "": 1 }), 1, &mut pairs)
            .expect_err("an empty field name is inexpressible");
        assert!(err.contains("may not be empty"), "{err}");
    }

    #[test]
    fn a_singleton_scalar_array_keeps_its_container_kind() {
        // Codex P2: one repeated key is indistinguishable from a scalar, so a
        // one-element array must use the explicit position instead.
        let mut pairs = QueryPairs::new();
        encode_query_arg("tags", &json!(["only"]), 1, &mut pairs).expect("encodes");
        assert_eq!(
            pairs.pairs,
            vec![("tags[0]".to_owned(), "only".to_owned())],
            "a singleton must pin its kind"
        );

        // Two or more still use the repeated-key (OpenAPI form/explode) shape.
        let mut pairs = QueryPairs::new();
        encode_query_arg("tags", &json!(["a", "b"]), 1, &mut pairs).expect("encodes");
        assert_eq!(
            pairs.pairs,
            vec![
                ("tags".to_owned(), "a".to_owned()),
                ("tags".to_owned(), "b".to_owned())
            ]
        );
    }

    #[test]
    fn the_numeric_object_check_ignores_fields_that_emit_nothing() {
        // Codex P2: a `null` field emits no pair, so it cannot disambiguate —
        // judging on declared keys let this reach the wire as bare `counts[0]=5`.
        let mut pairs = QueryPairs::new();
        let err = encode_query_arg("counts", &json!({ "0": 5, "kind": null }), 1, &mut pairs)
            .expect_err("the null field cannot disambiguate");
        assert!(err.contains("all numeric"), "{err}");

        // A named field that *does* emit still disambiguates, as before.
        let mut pairs = QueryPairs::new();
        encode_query_arg("counts", &json!({ "0": 5, "kind": "x" }), 1, &mut pairs)
            .expect("an emitting named key resolves the shape");

        // An all-null object keeps its own, more specific collapse error.
        let mut pairs = QueryPairs::new();
        let err = encode_query_arg("counts", &json!({ "0": null }), 1, &mut pairs)
            .expect_err("an all-null object carries no value");
        assert!(err.contains("carries no value"), "{err}");
    }

    #[test]
    fn encode_query_arg_rejects_nesting_past_the_decoder_cap() {
        // Build an object nested one level deeper than the decoder accepts, so
        // the encoder refuses instead of emitting keys the extractor rejects.
        let mut value = json!("leaf");
        for _ in 0..crate::query_string::MAX_DEPTH {
            value = json!({ "deeper": value });
        }
        let mut pairs = QueryPairs::new();
        assert!(encode_query_arg("root", &value, 1, &mut pairs).is_err());
    }

    #[test]
    fn replace_path_param_handles_regex_captures() {
        assert_eq!(replace_path_param("/u/{id}", "id", "7"), "/u/7");
        assert_eq!(replace_path_param("/u/{id:[0-9]+}", "id", "7"), "/u/7");
        assert_eq!(
            replace_path_param("/u/{id}/p/{pid}", "pid", "9"),
            "/u/{id}/p/9"
        );
    }

    fn tool(method: &str, path: &str, has_body: bool, has_query: bool) -> McpTool {
        McpTool {
            name: "t".to_owned(),
            description: None,
            input_schema: json!({}),
            annotations: json!({}),
            method: method.to_owned(),
            path_template: path.to_owned(),
            path_params: Vec::new(),
            has_body,
            has_query,
            streams: false,
            empty_body: false,
            task: false,
            agent_authority: None,
            core: false,
            tags: Vec::new(),
        }
    }

    #[test]
    fn build_request_rejects_missing_required_body() {
        let t = tool("POST", "/api/todos", true, false);
        let err =
            build_request(&t, &HeaderMap::new(), &json!({}), "x-csrf-token", None).unwrap_err();
        assert!(err.contains("body"), "got: {err}");
    }

    #[test]
    fn build_request_explodes_array_query_into_repeated_keys() {
        let t = tool("GET", "/api/search", false, true);
        let req = build_request(
            &t,
            &HeaderMap::new(),
            &json!({ "query": { "tags": ["a", "b"], "q": "x" } }),
            "x-csrf-token",
            None,
        )
        .expect("request builds");
        let query = req.uri().query().unwrap_or_default();
        assert!(query.contains("tags=a"), "got: {query}");
        assert!(query.contains("tags=b"), "got: {query}");
        assert!(query.contains("q=x"), "got: {query}");
        assert!(
            !query.contains("%5B"), // no JSON `[` — i.e. not `tags=["a","b"]`
            "array must explode, not serialize as JSON: {query}"
        );
    }

    #[test]
    fn build_request_forwards_authorization_and_cookie() {
        let t = tool("GET", "/secure", false, false);
        let mut headers = HeaderMap::new();
        headers.insert(header::AUTHORIZATION, "Bearer tok".parse().unwrap());
        headers.insert(header::COOKIE, "autumn.sid=abc".parse().unwrap());
        let req =
            build_request(&t, &headers, &json!({}), "x-csrf-token", None).expect("request builds");
        assert_eq!(
            req.headers().get(header::AUTHORIZATION).unwrap(),
            "Bearer tok"
        );
        assert_eq!(req.headers().get(header::COOKIE).unwrap(), "autumn.sid=abc");
    }

    #[test]
    fn build_request_forwards_csrf_token() {
        let t = tool("POST", "/api/todos", true, false);
        let mut headers = HeaderMap::new();
        headers.insert("x-csrf-token", "csrf123".parse().unwrap());
        let req = build_request(
            &t,
            &headers,
            &json!({ "body": { "x": 1 } }),
            "x-csrf-token",
            None,
        )
        .expect("request builds");
        assert_eq!(req.headers().get("x-csrf-token").unwrap(), "csrf123");
    }

    #[test]
    fn build_request_forwards_configured_csrf_header() {
        // Apps that customize security.csrf.token_header must have that header
        // forwarded, not a hard-coded `x-csrf-token`.
        let t = tool("POST", "/api/todos", true, false);
        let mut headers = HeaderMap::new();
        headers.insert("x-xsrf-token", "csrf123".parse().unwrap());
        let req = build_request(
            &t,
            &headers,
            &json!({ "body": { "x": 1 } }),
            "x-xsrf-token",
            None,
        )
        .expect("request builds");
        assert_eq!(req.headers().get("x-xsrf-token").unwrap(), "csrf123");
    }

    #[test]
    fn build_request_preserves_slashes_for_catch_all_param() {
        // A catch-all route `/files/{*path}`: the argument is addressed by the
        // bare name `path`, and its `/` separators survive into the replay URI.
        let mut t = tool("GET", "/files/{*path}", false, false);
        t.path_params = vec!["*path".to_owned()];
        let req = build_request(
            &t,
            &HeaderMap::new(),
            &json!({ "path": "a/b c/d.txt" }),
            "x-csrf-token",
            None,
        )
        .expect("request builds");
        // Slashes preserved as separators; the space in a segment is encoded.
        assert_eq!(req.uri().path(), "/files/a/b%20c/d.txt");
    }

    #[test]
    fn build_request_forwards_configured_tenant_header() {
        let t = tool("GET", "/api/todos", false, false);
        let mut headers = HeaderMap::new();
        headers.insert("x-tenant-id", "acme".parse().unwrap());
        // With header-based tenancy configured, the tenant header is forwarded.
        let req = build_request(
            &t,
            &headers,
            &json!({}),
            "x-csrf-token",
            Some("x-tenant-id"),
        )
        .expect("request builds");
        assert_eq!(req.headers().get("x-tenant-id").unwrap(), "acme");
        // Without a configured tenant header, it is not forwarded.
        let req =
            build_request(&t, &headers, &json!({}), "x-csrf-token", None).expect("request builds");
        assert!(req.headers().get("x-tenant-id").is_none());
    }

    #[test]
    fn build_request_rejects_non_object_query() {
        let t = tool("GET", "/api/search", false, true);
        // `query` advertised as an object: a non-object value is invalid params,
        // not silently dropped (which would replay with defaulted parameters).
        for bad in [
            json!({ "query": null }),
            json!({ "query": "all" }),
            json!({ "query": [1, 2] }),
        ] {
            let err = build_request(&t, &HeaderMap::new(), &bad, "x-csrf-token", None).unwrap_err();
            assert!(err.contains("query"), "got: {err}");
        }
        // An absent `query` is fine (the field is optional).
        assert!(build_request(&t, &HeaderMap::new(), &json!({}), "x-csrf-token", None).is_ok());
    }

    #[test]
    fn build_request_forwards_identity_and_idempotency_headers() {
        let t = tool("POST", "/api/todos", true, false);
        let mut headers = HeaderMap::new();
        headers.insert(header::HOST, "tenant1.example.com".parse().unwrap());
        headers.insert("x-forwarded-for", "203.0.113.7".parse().unwrap());
        headers.insert("x-forwarded-host", "tenant1.example.com".parse().unwrap());
        headers.insert("x-real-ip", "203.0.113.7".parse().unwrap());
        headers.insert("idempotency-key", "abc-123".parse().unwrap());
        let req = build_request(
            &t,
            &headers,
            &json!({ "body": { "x": 1 } }),
            "x-csrf-token",
            None,
        )
        .expect("request builds");
        // Host/forwarding headers carry subdomain-tenancy host + rate-limit IP.
        assert_eq!(
            req.headers().get(header::HOST).unwrap(),
            "tenant1.example.com"
        );
        assert_eq!(req.headers().get("x-forwarded-for").unwrap(), "203.0.113.7");
        assert_eq!(req.headers().get("x-real-ip").unwrap(), "203.0.113.7");
        // Idempotency-Key is preserved for safe retries of mutating tools.
        assert_eq!(req.headers().get("idempotency-key").unwrap(), "abc-123");
    }

    #[test]
    fn build_request_forwards_accept_language() {
        // The `Locale` extractor falls back to `Accept-Language`; forwarding it
        // keeps an MCP tool's localized result matching a direct HTTP call.
        let t = tool("GET", "/api/todos", false, false);
        let mut headers = HeaderMap::new();
        headers.insert("accept-language", "fr-CA,fr;q=0.9".parse().unwrap());
        let req =
            build_request(&t, &headers, &json!({}), "x-csrf-token", None).expect("request builds");
        assert_eq!(
            req.headers().get("accept-language").unwrap(),
            "fr-CA,fr;q=0.9"
        );
    }

    #[test]
    fn build_request_preserves_repeated_cookie_headers() {
        // `CsrfLayer` inspects *all* Cookie headers to detect cookie-tossing
        // (duplicate CSRF cookies); forwarding only the first would let a
        // replayed write slip past that check. Every value must be carried.
        let t = tool("POST", "/api/todos", true, false);
        let mut headers = HeaderMap::new();
        headers.append("cookie", "session=abc".parse().unwrap());
        headers.append("cookie", "csrf=dup1".parse().unwrap());
        headers.append("cookie", "csrf=dup2".parse().unwrap());
        let req = build_request(
            &t,
            &headers,
            &json!({ "body": { "x": 1 } }),
            "x-csrf-token",
            None,
        )
        .expect("request builds");
        let cookies: Vec<_> = req
            .headers()
            .get_all("cookie")
            .iter()
            .map(|v| v.to_str().unwrap().to_owned())
            .collect();
        assert_eq!(cookies, ["session=abc", "csrf=dup1", "csrf=dup2"]);
    }

    #[test]
    fn x402_headers_cross_the_replay_both_ways() {
        let t = tool("GET", "/api/report", false, false);
        let mut headers = HeaderMap::new();
        headers.insert("payment-signature", "eyJ4IjoxfQ==".parse().unwrap());
        let req =
            build_request(&t, &headers, &json!({}), "x-csrf-token", None).expect("request builds");
        assert_eq!(req.headers()["payment-signature"], "eyJ4IjoxfQ==");

        let response = Response::builder()
            .header(header::SET_COOKIE, "session=abc")
            .header("payment-response", "receipt")
            .header("payment-required", "challenge")
            .header("x-other", "kept inside")
            .body(Body::empty())
            .unwrap();
        let replayed: Vec<_> = Dispatched::inspect(&response)
            .replayed
            .into_iter()
            .map(|(name, value)| format!("{name}: {}", value.to_str().unwrap()))
            .collect();
        assert_eq!(
            replayed,
            [
                "set-cookie: session=abc",
                "payment-required: challenge",
                "payment-response: receipt"
            ]
        );
    }

    #[tokio::test]
    async fn a_failed_read_still_returns_the_payment_receipt() {
        let t = tool("GET", "/api/report", false, false);
        let body = Body::from_stream(futures::stream::iter([Err::<Bytes, _>(
            std::io::Error::other("boom"),
        )]));
        let response = Response::builder()
            .header("payment-response", "receipt")
            .body(body)
            .unwrap();
        let replayed = Dispatched::inspect(&response).replayed;
        let (resp, failure) = buffered_tool_response(
            &t,
            json!(1),
            StatusCode::OK,
            false,
            replayed,
            response,
            None,
        )
        .await;
        assert!(failure.is_some());
        assert_eq!(resp.headers()["payment-response"], "receipt");
        assert_eq!(resp.headers()[header::CACHE_CONTROL], "private, no-store");
        // A cross-origin browser client can read the receipt.
        assert_eq!(
            resp.headers()[header::ACCESS_CONTROL_EXPOSE_HEADERS],
            "PAYMENT-REQUIRED, PAYMENT-RESPONSE"
        );
    }

    /// Codex review (P2): a paid tool result keeps x402's `no-store`, on the
    /// buffered and the streamed response alike; an unpaid one is untouched.
    #[tokio::test]
    async fn a_paid_tool_result_is_not_cached() {
        let t = tool("GET", "/api/report", false, false);
        let response = Response::builder()
            .header("payment-response", "receipt")
            .body(Body::from("{}"))
            .unwrap();
        let replayed = Dispatched::inspect(&response).replayed;
        let (resp, _) = buffered_tool_response(
            &t,
            json!(1),
            StatusCode::OK,
            false,
            replayed,
            response,
            None,
        )
        .await;
        assert_eq!(resp.headers()[header::CACHE_CONTROL], "private, no-store");

        let mut headers = HeaderMap::new();
        headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
        apply_replayed(
            &mut headers,
            vec![(
                HeaderName::from_static("payment-required"),
                HeaderValue::from_static("challenge"),
            )],
        );
        assert_eq!(
            headers
                .get_all(header::CACHE_CONTROL)
                .iter()
                .collect::<Vec<_>>(),
            ["private, no-store"]
        );

        let response = Response::builder().body(Body::from("{}")).unwrap();
        let replayed = Dispatched::inspect(&response).replayed;
        let (resp, _) = buffered_tool_response(
            &t,
            json!(1),
            StatusCode::OK,
            false,
            replayed,
            response,
            None,
        )
        .await;
        assert!(resp.headers().get(header::CACHE_CONTROL).is_none());
    }

    /// A trusted-Host policy that trusts the given hosts (plus dev loopback,
    /// which `from_config` adds for non-production profiles).
    fn trusted(hosts: &[&str]) -> crate::router::TrustedHostPolicy {
        let mut config = crate::config::AutumnConfig::default();
        config.security.trusted_hosts.hosts = hosts.iter().map(|h| (*h).to_owned()).collect();
        crate::router::TrustedHostPolicy::from_config(&config)
    }

    fn server(allowed_origins: Vec<String>) -> McpServer {
        server_with_trusted(allowed_origins, &[])
    }

    fn server_with_trusted(allowed_origins: Vec<String>, hosts: &[&str]) -> McpServer {
        let cors = crate::config::CorsConfig {
            allowed_origins,
            ..crate::config::CorsConfig::default()
        };
        McpServer::new(
            Vec::new(),
            axum::Router::new(),
            McpWiring {
                cors,
                trusted_hosts: trusted(hosts),
                tenant_header: None,
                csrf_header: "x-csrf-token".to_owned(),
                envelope_rate_limited: false,
                envelope_load_shed: false,
                state: crate::AppState::for_test(),
                session_cookie: "autumn.sid".to_owned(),
                tasks: McpTaskConfig::default(),
                instructions: None,
                catalog: McpCatalog::Full,
            },
        )
    }

    #[test]
    fn origin_allowlist_enforced() {
        let s = server(vec!["https://ok.example".to_owned()]);
        assert!(s.origin_allowed("https://ok.example", None, None));
        assert!(!s.origin_allowed("https://evil.example", None, None));
        // Empty allowlist permits no cross-origin browser request.
        assert!(!server(Vec::new()).origin_allowed("https://any.example", None, None));
        // Wildcard permits any.
        assert!(server(vec!["*".to_owned()]).origin_allowed("https://any.example", None, None));
    }

    #[test]
    fn same_origin_allowed_without_cors_allowlist() {
        // An empty CORS allowlist (the default/production posture) must still
        // permit a browser MCP client served by this same app — provided the
        // host is trusted by the trusted-Host policy.
        let s = server_with_trusted(Vec::new(), &["app.example"]);
        // Host matches the Origin authority → allowed, scheme unknown.
        assert!(s.origin_allowed("https://app.example", Some("app.example"), None));
        // Scheme known and matching → allowed.
        assert!(s.origin_allowed("https://app.example", Some("app.example"), Some("https")));
        // Host with a port matches exactly (loopback is trusted in dev).
        assert!(s.origin_allowed(
            "http://localhost:8080",
            Some("localhost:8080"),
            Some("http")
        ));
        // A different host is still rejected (DNS-rebinding protection holds).
        assert!(!s.origin_allowed("https://evil.example", Some("app.example"), None));
        // Same host but a confidently-known mismatched scheme is rejected.
        assert!(!s.origin_allowed("http://app.example", Some("app.example"), Some("https")));
    }

    #[test]
    fn same_origin_normalizes_default_ports() {
        let s = server_with_trusted(Vec::new(), &["app.example"]);
        // Host carries the explicit default https port; Origin omits it.
        assert!(s.origin_allowed(
            "https://app.example",
            Some("app.example:443"),
            Some("https")
        ));
        // ...and the reverse: Origin carries the default port, Host omits it.
        assert!(s.origin_allowed(
            "https://app.example:443",
            Some("app.example"),
            Some("https")
        ));
        // Explicit default http port likewise normalizes.
        assert!(s.origin_allowed("http://app.example", Some("app.example:80"), Some("http")));
        // A non-default explicit port is NOT the same origin.
        assert!(!s.origin_allowed(
            "https://app.example",
            Some("app.example:8443"),
            Some("https")
        ));
        // The https default (443) must not be conflated with the http default.
        assert!(!s.origin_allowed("http://app.example:443", Some("app.example"), Some("http")));
    }

    #[test]
    fn same_origin_rejected_for_untrusted_host() {
        // DNS rebinding: Origin and Host both name the attacker's domain. The
        // authority matches, but the host is not trusted, so the same-origin
        // shortcut must not fire — and with no CORS allowlist, it is rejected.
        let s = server_with_trusted(Vec::new(), &["app.example"]);
        assert!(!s.origin_allowed(
            "http://attacker.example",
            Some("attacker.example"),
            Some("http")
        ));
        // An explicit cross-origin allowlist entry still works regardless.
        let s = server_with_trusted(vec!["http://attacker.example".to_owned()], &["app.example"]);
        assert!(s.origin_allowed(
            "http://attacker.example",
            Some("attacker.example"),
            Some("http")
        ));
    }

    #[tokio::test]
    async fn options_preflight_grants_only_allowlisted_origin() {
        let s = Arc::new(server_with_trusted(
            vec!["https://app.example".to_owned()],
            &[],
        ));

        // Allowlisted origin → preflight grants the CORS headers.
        let mut headers = HeaderMap::new();
        headers.insert(header::ORIGIN, "https://app.example".parse().unwrap());
        let resp = serve_mcp_options(axum::extract::Extension(s.clone()), headers).await;
        assert_eq!(resp.status(), StatusCode::NO_CONTENT);
        assert_eq!(
            resp.headers()
                .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
                .unwrap(),
            "https://app.example"
        );
        assert!(
            resp.headers()
                .get(header::ACCESS_CONTROL_ALLOW_METHODS)
                .is_some()
        );
        // The MCP transport headers must be allowed even though the default
        // CORS `allowed_headers` omits them, or the browser blocks the POST.
        let allow_headers = resp
            .headers()
            .get(header::ACCESS_CONTROL_ALLOW_HEADERS)
            .and_then(|v| v.to_str().ok())
            .unwrap()
            .to_ascii_lowercase();
        assert!(
            allow_headers.contains("mcp-protocol-version"),
            "allow-headers missing MCP-Protocol-Version: {allow_headers}"
        );
        // A paid tool call's retry carries the x402 payment.
        assert!(
            allow_headers.contains("payment-signature"),
            "allow-headers missing Payment-Signature: {allow_headers}"
        );

        // Non-allowlisted origin → no CORS grant (browser will block the POST).
        let mut headers = HeaderMap::new();
        headers.insert(header::ORIGIN, "https://evil.example".parse().unwrap());
        let resp = serve_mcp_options(axum::extract::Extension(s), headers).await;
        assert_eq!(resp.status(), StatusCode::NO_CONTENT);
        assert!(
            resp.headers()
                .get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
                .is_none()
        );
    }

    #[test]
    fn initialize_negotiates_supported_protocol_version() {
        let s = server(Vec::new());
        // A supported version is echoed back.
        let echoed = initialize_result(&s, &json!({ "protocolVersion": "2024-11-05" }));
        assert_eq!(echoed["protocolVersion"], "2024-11-05");
        // An unsupported version falls back to the server's newest.
        let fallback = initialize_result(&s, &json!({ "protocolVersion": "3999-01-01" }));
        assert_eq!(fallback["protocolVersion"], DEFAULT_PROTOCOL_VERSION);
    }
}