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
//! MCP Router - routes requests to tools, resources, and prompts
//!
//! The router implements Tower's `Service` trait, making it composable with
//! standard tower middleware.
use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
use std::sync::{Arc, Mutex, RwLock};
use std::task::{Context, Poll};
use tower_service::Service;
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
use crate::async_task::{MemoryTaskStore, TaskStore, TaskStoreError};
use crate::context::{
CancellationToken, ClientRequesterHandle, NotificationSender, RequestContext,
ServerNotification,
};
use crate::error::{Error, JsonRpcError, Result};
use crate::filter::{PromptFilter, ResourceFilter, ToolFilter};
use crate::prompt::Prompt;
use crate::protocol::*;
#[cfg(feature = "dynamic-tools")]
use crate::registry::{
DynamicPromptRegistry, DynamicPromptsInner, DynamicResourceRegistry,
DynamicResourceTemplateRegistry, DynamicResourceTemplatesInner, DynamicResourcesInner,
DynamicToolRegistry, DynamicToolsInner,
};
use crate::resource::{Resource, ResourceTemplate};
use crate::session::SessionState;
use crate::tool::Tool;
/// Type alias for completion handler function
pub(crate) type CompletionHandler = Arc<
dyn Fn(CompleteParams) -> Pin<Box<dyn Future<Output = Result<CompleteResult>> + Send>>
+ Send
+ Sync,
>;
/// Decode a pagination cursor into an offset.
///
/// Returns `Err` if the cursor is malformed.
fn decode_cursor(cursor: &str) -> Result<usize> {
let bytes = BASE64
.decode(cursor)
.map_err(|_| Error::JsonRpc(JsonRpcError::invalid_params("Invalid pagination cursor")))?;
let s = String::from_utf8(bytes)
.map_err(|_| Error::JsonRpc(JsonRpcError::invalid_params("Invalid pagination cursor")))?;
s.parse::<usize>()
.map_err(|_| Error::JsonRpc(JsonRpcError::invalid_params("Invalid pagination cursor")))
}
/// Encode an offset into an opaque pagination cursor.
fn encode_cursor(offset: usize) -> String {
BASE64.encode(offset.to_string())
}
/// Releases a live task's registry entry however its handler leaves.
///
/// The handler can return, panic, or be dropped. Unregistering only on the
/// return path left a panicking handler's entry installed, so a later
/// `tasks/cancel` found a handle nobody was reading and took the live path
/// instead of the store one (#1305).
struct LiveTaskRegistration {
router: McpRouter,
task_id: String,
}
impl Drop for LiveTaskRegistration {
fn drop(&mut self) {
self.router.unregister_live_task(&self.task_id);
}
}
/// Whether this request is using the final, stateless 2026-07-28 lifecycle.
///
/// Stable sessionful requests retain the crate's legacy task behavior; final
/// requests use extension negotiation and server-directed task creation.
#[cfg(feature = "stateless")]
fn is_final_protocol_request(extensions: &crate::context::Extensions) -> bool {
extensions
.get::<crate::stateless::StatelessRequestMeta>()
.and_then(|meta| meta.protocol_version.as_deref())
== Some(crate::protocol::PROTOCOL_VERSION_2026_07_28)
}
#[cfg(not(feature = "stateless"))]
fn is_final_protocol_request(_extensions: &crate::context::Extensions) -> bool {
false
}
/// Recover a readable message from a panic payload.
///
/// `panic!` with a literal yields `&str` and with a format yields `String`;
/// anything else is opaque and reported as such rather than guessed at.
fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
if let Some(text) = payload.downcast_ref::<&'static str>() {
(*text).to_string()
} else if let Some(text) = payload.downcast_ref::<String>() {
text.clone()
} else {
"panicked with a non-string payload".to_string()
}
}
#[derive(Clone)]
enum ClientPanicMessage {
Detailed,
Fixed(Arc<str>),
}
#[derive(Clone)]
enum ToolNameDisclosure {
Omit,
Original,
Fixed(Arc<str>),
}
impl ToolNameDisclosure {
fn value<'a>(&'a self, original: &'a str) -> Option<&'a str> {
match self {
Self::Omit => None,
Self::Original => Some(original),
Self::Fixed(name) => Some(name),
}
}
fn mode(&self) -> &'static str {
match self {
Self::Omit => "omitted",
Self::Original => "original",
Self::Fixed(_) => "fixed",
}
}
}
/// Controls what Tower discloses after isolating a panicking tool handler.
///
/// Construct a redacted policy with [`PanicPolicy::redacted`], then opt in to
/// individual disclosures only when they are safe for the application. Panic
/// payloads are never included in a custom policy's client response.
///
/// Rust's process-global panic hook runs before Tower catches an unwind. This
/// policy governs only Tower's client response and Tower-generated tracing
/// event; it cannot redact output produced by an application-installed panic
/// hook or by Rust's default panic hook.
#[derive(Clone)]
pub struct PanicPolicy {
client_message: ClientPanicMessage,
client_tool_name: ToolNameDisclosure,
log_tool_name: ToolNameDisclosure,
include_payload_in_logs: bool,
}
impl std::fmt::Debug for PanicPolicy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let client_message = match self.client_message {
ClientPanicMessage::Detailed => "detailed",
ClientPanicMessage::Fixed(_) => "fixed",
};
f.debug_struct("PanicPolicy")
.field("client_message", &client_message)
.field("client_tool_name", &self.client_tool_name.mode())
.field("log_tool_name", &self.log_tool_name.mode())
.field("include_payload_in_logs", &self.include_payload_in_logs)
.finish()
}
}
impl PanicPolicy {
/// Create a policy whose client response is fixed application-supplied
/// text and whose Tower tracing event contains neither the tool name nor
/// the panic payload.
pub fn redacted(client_message: impl Into<String>) -> Self {
Self {
client_message: ClientPanicMessage::Fixed(Arc::from(client_message.into())),
client_tool_name: ToolNameDisclosure::Omit,
log_tool_name: ToolNameDisclosure::Omit,
include_payload_in_logs: false,
}
}
fn detailed() -> Self {
Self {
client_message: ClientPanicMessage::Detailed,
client_tool_name: ToolNameDisclosure::Original,
log_tool_name: ToolNameDisclosure::Original,
include_payload_in_logs: true,
}
}
/// Include the registered tool name in the client-visible error.
///
/// With a redacted policy this changes the response from the exact fixed
/// message to `tool '<name>': <fixed message>`.
#[must_use]
pub fn include_tool_name_in_client_message(mut self, include: bool) -> Self {
self.client_tool_name = if include {
ToolNameDisclosure::Original
} else {
ToolNameDisclosure::Omit
};
self
}
/// Replace the registered tool name in the client-visible error with a
/// fixed application-selected label.
///
/// This is useful when the original catalog name is sensitive but a
/// stable category such as `provider tool` is still useful to callers.
#[must_use]
pub fn client_tool_name(mut self, name: impl Into<String>) -> Self {
self.client_tool_name = ToolNameDisclosure::Fixed(Arc::from(name.into()));
self
}
/// Include the registered tool name in Tower's panic tracing event.
#[must_use]
pub fn include_tool_name_in_logs(mut self, include: bool) -> Self {
self.log_tool_name = if include {
ToolNameDisclosure::Original
} else {
ToolNameDisclosure::Omit
};
self
}
/// Replace the registered tool name in Tower's panic tracing event with
/// a fixed application-selected label.
#[must_use]
pub fn log_tool_name(mut self, name: impl Into<String>) -> Self {
self.log_tool_name = ToolNameDisclosure::Fixed(Arc::from(name.into()));
self
}
/// Include the recovered panic payload in Tower's panic tracing event.
///
/// This switch never changes the client-visible error.
#[must_use]
pub fn include_payload_in_logs(mut self, include: bool) -> Self {
self.include_payload_in_logs = include;
self
}
fn client_message(&self, tool_name: &str, payload: Option<&str>) -> String {
match &self.client_message {
ClientPanicMessage::Detailed => format!(
"tool '{tool_name}' panicked: {}",
payload.unwrap_or("<redacted>")
),
ClientPanicMessage::Fixed(message) => match self.client_tool_name.value(tool_name) {
Some(name) => format!("tool '{name}': {message}"),
None => message.to_string(),
},
}
}
fn needs_payload(&self) -> bool {
matches!(self.client_message, ClientPanicMessage::Detailed) || self.include_payload_in_logs
}
/// The client-visible text for an internal failure that is not a caught
/// tool panic.
///
/// A transport that builds its own error response has no tool to name and
/// no panic payload to redact, so it cannot use `client_message`. The
/// operator's disclosure choice still applies: a policy installed to keep
/// internal text away from clients should not be bypassed because the
/// failure happened while framing a response rather than inside a handler.
///
/// The tool-name switches are deliberately not consulted. They select how
/// to name a tool, and there is no tool here to name.
///
/// Gated with its caller. Widen the gate when a second transport adopts
/// [`McpRouter::transport_internal_error`].
#[cfg(feature = "websocket")]
fn internal_error_message(&self, error: &dyn std::fmt::Display) -> String {
match &self.client_message {
ClientPanicMessage::Detailed => error.to_string(),
ClientPanicMessage::Fixed(message) => message.to_string(),
}
}
}
/// The Task operation whose failure is being exposed to a client.
///
/// A [`TaskErrorPolicy`] receives this alongside the typed failure so an
/// application can attach stable operation-specific data without parsing an
/// error message.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum TaskOperation {
/// Creating and preparing a Task from a task-augmented request.
Create,
/// Reading a Task through `tasks/get`.
Get,
/// Applying client input through `tasks/update`.
Update,
/// Requesting cancellation through `tasks/cancel`.
Cancel,
/// Persisting an input-required transition requested by a Task handler.
ParkInput,
/// Task-store work performed inside a live Task handler after creation.
Execute,
/// Reading durable state needed to resume a replayed Task handler.
Resume,
/// Persisting a terminal Task outcome after handler execution.
Finalize,
}
/// The typed reason a Task operation failed.
///
/// Store errors retain their original typed value for an explicitly installed
/// [`TaskErrorPolicy`]. Their display text may contain backend paths, queries,
/// or codec details and must not be copied into a client response without an
/// application-specific disclosure review. Tower's default policy never does
/// so.
#[non_exhaustive]
pub enum TaskFailure {
/// The Task ID is unknown or its retained tombstone was removed.
NotFound,
/// The Task is known to have expired and the caller owns it.
Expired,
/// The Task store returned an error.
Store(TaskStoreError),
/// Tower detected a safe, static Task-lifecycle invariant failure.
Internal(&'static str),
/// Client-supplied Task arguments were malformed.
InvalidArguments(&'static str),
/// A live Task handler returned an unclassified execution error.
///
/// The underlying error is deliberately neither logged nor exposed to the
/// policy: its display text is application-owned and can contain provider
/// details.
Handler,
}
impl std::fmt::Debug for TaskFailure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NotFound => f.write_str("NotFound"),
Self::Expired => f.write_str("Expired"),
Self::Store(error) => {
let kind = match error {
TaskStoreError::Encode(_) => "Encode",
TaskStoreError::Decode(_) => "Decode",
TaskStoreError::Backend(_) => "Backend",
TaskStoreError::InvalidTransition(_) => "InvalidTransition",
};
write!(f, "Store({kind})")
}
Self::Internal(message) => f.debug_tuple("Internal").field(message).finish(),
Self::InvalidArguments(message) => {
f.debug_tuple("InvalidArguments").field(message).finish()
}
Self::Handler => f.write_str("Handler"),
}
}
}
/// Typed input to a [`TaskErrorPolicy`].
///
/// The fields are intentionally private so Tower can add context without
/// breaking policy implementations. Inspect them through the accessors.
#[derive(Debug)]
#[non_exhaustive]
pub struct TaskErrorContext {
operation: TaskOperation,
task_id: Option<String>,
failure: TaskFailure,
}
impl TaskErrorContext {
fn new(operation: TaskOperation, task_id: Option<&str>, failure: TaskFailure) -> Self {
Self {
operation,
task_id: task_id.map(str::to_owned),
failure,
}
}
/// The Task operation that failed.
pub const fn operation(&self) -> TaskOperation {
self.operation
}
/// The Task ID, when one had been allocated or supplied.
pub fn task_id(&self) -> Option<&str> {
self.task_id.as_deref()
}
/// The typed failure.
pub const fn failure(&self) -> &TaskFailure {
&self.failure
}
}
type TaskErrorMapper = dyn Fn(&TaskErrorContext) -> JsonRpcError + Send + Sync + 'static;
/// Maps Task lifecycle failures to client-visible JSON-RPC errors.
///
/// The default preserves Tower's established `-32602` shapes for unknown and
/// expired Tasks. Store failures use `-32603` with fixed text, deliberately
/// omitting the store error's display string because it may disclose backend
/// details.
///
/// A custom policy can attach an application's structured error envelope. It
/// receives the original [`TaskStoreError`] by reference, so it must make its
/// own explicit disclosure decision rather than forwarding `Display` text.
#[derive(Clone)]
pub struct TaskErrorPolicy {
mapper: Arc<TaskErrorMapper>,
}
impl std::fmt::Debug for TaskErrorPolicy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TaskErrorPolicy").finish_non_exhaustive()
}
}
impl Default for TaskErrorPolicy {
fn default() -> Self {
Self::new(default_task_error)
}
}
impl TaskErrorPolicy {
/// Construct a Task error policy from a synchronous mapper.
///
/// The mapper runs only after Tower has authorized any distinction between
/// an expired Task and a missing one. An unauthorized Task is passed to the
/// mapper as [`TaskFailure::NotFound`], exactly like a never-issued ID. It
/// runs synchronously on the request or handler path, so it should be fast.
/// Tower catches a panic and substitutes a fixed redacted internal error.
/// Rust's process-global panic hook still runs before the unwind is caught.
pub fn new<F>(mapper: F) -> Self
where
F: Fn(&TaskErrorContext) -> JsonRpcError + Send + Sync + 'static,
{
Self {
mapper: Arc::new(mapper),
}
}
fn map(&self, context: &TaskErrorContext) -> JsonRpcError {
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (self.mapper)(context))) {
Ok(error) => error,
Err(_) => {
// The policy itself is application code. Record that it broke,
// but do not attach the Task ID, failure, or panic payload:
// this is the final redaction boundary.
tracing::error!(
target: "mcp::tasks",
"task error policy panicked; using the redacted fallback"
);
JsonRpcError::internal_error("Task error policy failed")
}
}
}
pub(crate) fn map_store_error(
&self,
operation: TaskOperation,
task_id: &str,
error: TaskStoreError,
) -> JsonRpcError {
self.map(&TaskErrorContext::new(
operation,
Some(task_id),
TaskFailure::Store(error),
))
}
pub(crate) fn map_internal_error(
&self,
operation: TaskOperation,
task_id: &str,
message: &'static str,
) -> JsonRpcError {
self.map(&TaskErrorContext::new(
operation,
Some(task_id),
TaskFailure::Internal(message),
))
}
}
fn default_task_error(context: &TaskErrorContext) -> JsonRpcError {
match context.failure() {
TaskFailure::NotFound => JsonRpcError::invalid_params(format!(
"Task not found: {}",
context.task_id().unwrap_or("<unknown>")
)),
TaskFailure::Expired => JsonRpcError::invalid_params(format!(
"Task expired: {}",
context.task_id().unwrap_or("<unknown>")
))
.with_data(serde_json::json!({ "reason": "task_expired" })),
TaskFailure::Store(_) => JsonRpcError::internal_error("Task store operation failed"),
TaskFailure::Internal(message) => JsonRpcError::internal_error(*message),
TaskFailure::InvalidArguments(message) => JsonRpcError::invalid_params(*message),
TaskFailure::Handler => JsonRpcError::internal_error("Task handler failed"),
}
}
/// The kind of capability a [`MergeConflict`] refers to.
///
/// Ordered so that [`McpRouter::conflicts`] reports tools before resources
/// before prompts, which reads more naturally than alphabetical order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum MergeConflictKind {
/// A tool name defined by both routers.
Tool,
/// A resource URI defined by both routers.
Resource,
/// A resource template pattern defined by both routers.
ResourceTemplate,
/// A prompt name defined by both routers.
Prompt,
}
impl MergeConflictKind {
/// The name of this kind as it appears in a conflict message.
pub fn as_str(&self) -> &'static str {
match self {
Self::Tool => "tool",
Self::Resource => "resource",
Self::ResourceTemplate => "resource template",
Self::Prompt => "prompt",
}
}
}
impl std::fmt::Display for MergeConflictKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
/// One capability defined by both routers in a [`McpRouter::try_merge`].
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MergeConflict {
/// Which kind of capability collided.
pub kind: MergeConflictKind,
/// The tool or prompt name, or the resource URI or template pattern.
pub name: String,
}
impl MergeConflict {
fn new(kind: MergeConflictKind, name: impl Into<String>) -> Self {
Self {
kind,
name: name.into(),
}
}
}
impl std::fmt::Display for MergeConflict {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} '{}'", self.kind, self.name)
}
}
/// The error returned by [`McpRouter::try_merge`].
///
/// Carries every conflicting name rather than the first, so a startup check
/// reports all the work at once.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MergeConflicts {
conflicts: Vec<MergeConflict>,
}
impl MergeConflicts {
/// The conflicting capabilities, ordered by kind and then name.
pub fn conflicts(&self) -> &[MergeConflict] {
&self.conflicts
}
/// Take ownership of the conflicting capabilities.
pub fn into_conflicts(self) -> Vec<MergeConflict> {
self.conflicts
}
}
impl std::fmt::Display for MergeConflicts {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "cannot merge routers: ")?;
for (index, conflict) in self.conflicts.iter().enumerate() {
if index > 0 {
f.write_str(", ")?;
}
write!(f, "{conflict}")?;
}
f.write_str(" defined by both")
}
}
impl std::error::Error for MergeConflicts {}
/// The authenticated principal for this request, if any.
///
/// Sourced from the OAuth `sub` claim that the HTTP and WebSocket transports
/// bridge into MCP extensions. Without the `oauth` feature there is no
/// principal, so tasks are unowned and behave as they did before ownership
/// existed.
#[cfg(feature = "oauth")]
fn request_principal(extensions: &crate::context::Extensions) -> Option<String> {
extensions
.get::<crate::oauth::token::TokenClaims>()
.and_then(|claims| claims.sub.clone())
}
#[cfg(not(feature = "oauth"))]
fn request_principal(_extensions: &crate::context::Extensions) -> Option<String> {
None
}
#[cfg(feature = "stateless")]
fn final_client_capabilities(
extensions: &crate::context::Extensions,
) -> Option<&ClientCapabilities> {
extensions
.get::<crate::stateless::StatelessRequestMeta>()
.and_then(|meta| meta.client_capabilities.as_ref())
}
#[cfg(not(feature = "stateless"))]
fn final_client_capabilities(
_extensions: &crate::context::Extensions,
) -> Option<&ClientCapabilities> {
None
}
/// Return whether `actual` contains every field and value in `required`.
///
/// Client capability objects are extensible, so extra advertised properties
/// must not cause a required-capability check to fail.
#[cfg(feature = "stateless")]
fn json_value_contains(actual: &serde_json::Value, required: &serde_json::Value) -> bool {
match (actual, required) {
(serde_json::Value::Object(actual), serde_json::Value::Object(required)) => {
required.iter().all(|(key, value)| {
actual
.get(key)
.is_some_and(|a| json_value_contains(a, value))
})
}
_ => actual == required,
}
}
#[cfg(feature = "stateless")]
fn client_capabilities_satisfy(actual: &ClientCapabilities, required: &ClientCapabilities) -> bool {
let actual = serde_json::to_value(actual).expect("ClientCapabilities is always serializable");
let mut required =
serde_json::to_value(required).expect("ClientCapabilities is always serializable");
// `roots.listChanged: false` means the optional notification capability
// was not declared; it is not a requirement that the caller also set the
// flag to false. Normalize it away before doing the structural subset
// comparison so `{roots:{listChanged:true}}` satisfies plain `{roots:{}}`.
if required.pointer("/roots/listChanged") == Some(&serde_json::Value::Bool(false))
&& let Some(roots) = required
.get_mut("roots")
.and_then(serde_json::Value::as_object_mut)
{
roots.remove("listChanged");
}
json_value_contains(&actual, &required)
}
/// Apply pagination to a collected list of items.
///
/// Returns the page of items and an optional `next_cursor`.
fn paginate<T>(
items: Vec<T>,
cursor: Option<&str>,
page_size: Option<usize>,
) -> Result<(Vec<T>, Option<String>)> {
let Some(page_size) = page_size else {
return Ok((items, None));
};
let offset = match cursor {
Some(c) => decode_cursor(c)?,
None => 0,
};
if offset >= items.len() {
return Ok((Vec::new(), None));
}
let end = (offset + page_size).min(items.len());
let next_cursor = if end < items.len() {
Some(encode_cursor(end))
} else {
None
};
let mut items = items;
let page = items.drain(offset..end).collect();
Ok((page, next_cursor))
}
/// MCP Router that dispatches requests to registered handlers
///
/// Implements `tower::Service<McpRequest>` for middleware composition.
///
/// # Example
///
/// ```rust
/// use tower_mcp::{McpRouter, ToolBuilder, CallToolResult};
/// use schemars::JsonSchema;
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, JsonSchema)]
/// struct Input { value: String }
///
/// let tool = ToolBuilder::new("echo")
/// .description("Echo input")
/// .handler(|i: Input| async move { Ok(CallToolResult::text(i.value)) })
/// .build();
///
/// let router = McpRouter::new()
/// .server_info("my-server", "1.0.0")
/// .tool(tool);
/// ```
#[derive(Clone)]
pub struct McpRouter {
inner: Arc<McpRouterInner>,
session: SessionState,
}
impl std::fmt::Debug for McpRouter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("McpRouter")
.field("server_name", &self.inner.server_name)
.field("server_version", &self.inner.server_version)
.field("tools_count", &self.inner.tools.len())
.field("resources_count", &self.inner.resources.len())
.field("prompts_count", &self.inner.prompts.len())
.field("session_phase", &self.session.phase())
.finish()
}
}
/// Configuration for auto-generated instructions
#[derive(Clone, Debug)]
struct AutoInstructionsConfig {
prefix: Option<String>,
suffix: Option<String>,
}
#[cfg(all(feature = "http", feature = "stateless"))]
type ModernNotificationSink = Arc<dyn Fn(&ServerNotification) -> bool + Send + Sync + 'static>;
#[cfg(feature = "dynamic-tools")]
type PromptInitializer = Arc<dyn Fn() -> Result<()> + Send + Sync + 'static>;
/// Inner configuration that is shared across clones
#[derive(Clone)]
struct McpRouterInner {
server_name: String,
server_version: String,
/// Human-readable title for the server
server_title: Option<String>,
/// Description of the server
server_description: Option<String>,
/// Icons for the server
server_icons: Option<Vec<ToolIcon>>,
/// URL of the server's website
server_website_url: Option<String>,
instructions: Option<String>,
/// How to convert a panicking tool handler into an error result rather
/// than letting it unwind out of the service (#1230, #1306).
panic_policy: Option<PanicPolicy>,
/// Root-owned mapping for client-visible Task lifecycle failures.
task_error_policy: TaskErrorPolicy,
auto_instructions: Option<AutoInstructionsConfig>,
tools: HashMap<String, Arc<Tool>>,
resources: HashMap<String, Arc<Resource>>,
/// Resource templates for dynamic resource matching (keyed by uri_template)
resource_templates: Vec<Arc<ResourceTemplate>>,
prompts: HashMap<String, Arc<Prompt>>,
/// Whether to advertise `resources.subscribe`. Defaults to true, which
/// is what this router has always advertised when resources exist (#1261).
advertise_resource_subscriptions: bool,
/// Explicit override for whether to advertise `tools.listChanged`.
/// `None` derives from whether a notification channel is attached, which
/// is what this router has always advertised (#1338).
advertise_tools_list_changed: Option<bool>,
/// Explicit override for whether to advertise `prompts.listChanged`.
/// `None` derives from whether a notification channel is attached, which
/// is what this router has always advertised (#1338).
advertise_prompts_list_changed: Option<bool>,
/// Explicit override for whether to advertise `resources.listChanged`.
/// `None` derives from whether a notification channel is attached, which
/// is what this router has always advertised (#1338).
advertise_resources_list_changed: Option<bool>,
/// Explicit override for whether to advertise the `logging` capability.
/// `None` derives from whether a notification channel is attached, which
/// is what this router has always advertised (#1338).
advertise_mcp_logging: Option<bool>,
/// Live tasks currently running, keyed by task id (#1246).
///
/// A live handler parks inside its own future rather than returning, so
/// the router needs a handle to wake it when `tasks/update` commits and
/// to signal it when `tasks/cancel` arrives.
live_tasks: Arc<Mutex<HashMap<String, Arc<crate::tool::LiveTask>>>>,
/// In-flight requests for cancellation tracking (shared across clones).
///
/// Keyed by request id for lookup, but each id holds one entry per
/// *dispatch*. A client should not reuse an id that is still in flight,
/// but when one does, the twins have to coexist: keyed by id alone the
/// second registration evicted the first and the first became
/// uncancellable (#1270).
in_flight: Arc<RwLock<HashMap<RequestId, Vec<InFlightDispatch>>>>,
/// Source of the per-dispatch ids in `in_flight`, shared across clones.
next_dispatch: Arc<AtomicU64>,
/// Channel for sending notifications to connected clients
notification_tx: Option<NotificationSender>,
/// Transport-lifetime sink for final HTTP subscription notifications.
///
/// The lock is shared across router clones so an application-owned clone
/// can publish after the transport attaches its subscription registry.
#[cfg(all(feature = "http", feature = "stateless"))]
modern_notification_sink: Arc<RwLock<Option<ModernNotificationSink>>>,
#[cfg(feature = "stateless")]
subscription_observer:
Arc<RwLock<Option<Arc<dyn crate::transport::subscriptions::SubscriptionObserver>>>>,
/// Handle for sending requests to the client (for sampling, etc.)
client_requester: Option<ClientRequesterHandle>,
/// Task store for async operations
task_store: Arc<dyn TaskStore>,
/// Subscribed resource URIs
subscriptions: Arc<RwLock<HashSet<String>>>,
/// Handler for completion requests
completion_handler: Option<CompletionHandler>,
/// Filter for tools based on session state
tool_filter: Option<ToolFilter>,
/// Filter for resources based on session state
resource_filter: Option<ResourceFilter>,
/// Filter for prompts based on session state
prompt_filter: Option<PromptFilter>,
/// Router-level extensions (for state and middleware data)
extensions: Arc<crate::context::Extensions>,
/// Locally supported MCP protocol extensions and their server settings.
protocol_extensions: HashMap<String, serde_json::Value>,
/// Minimum log level for filtering outgoing log notifications (set by client via logging/setLevel)
min_log_level: Arc<RwLock<LogLevel>>,
/// Page size for list method pagination (None = return all results)
page_size: Option<usize>,
/// TTL hint for list responses in milliseconds (SEP-2549).
/// When set, the value is returned as `ttlMs` in tools/list, resources/list,
/// and prompts/list responses so clients can cache the list.
list_ttl_ms: Option<u64>,
/// Default TTL hint for resources/read responses in milliseconds
/// (SEP-2549). Applied only when the resource handler did not set its
/// own `ttl_ms` on the result.
read_ttl_ms: Option<u64>,
/// Cache scope for SEP-2549 hints on list and read responses. When a
/// TTL is emitted and no scope is configured, `private` is used: it is
/// the conservative choice (never shared across authorization
/// contexts).
cache_scope: Option<CacheScope>,
/// Deprecation info for the logging capability (SEP-2577).
/// When set, included in the `logging` capability in the initialize result.
logging_deprecated: Option<tower_mcp_types::protocol::DeprecationInfo>,
/// Names of tools that are currently disabled (hidden from list/call).
disabled_tools: Arc<RwLock<HashSet<String>>>,
/// URIs of resources that are currently disabled (hidden from list/read).
disabled_resources: Arc<RwLock<HashSet<String>>>,
/// Names of prompts that are currently disabled (hidden from list/get).
disabled_prompts: Arc<RwLock<HashSet<String>>>,
/// Dynamic tools registry for runtime tool (de)registration
#[cfg(feature = "dynamic-tools")]
dynamic_tools: Option<Arc<DynamicToolsInner>>,
/// Dynamic prompts registry for runtime prompt (de)registration
#[cfg(feature = "dynamic-tools")]
dynamic_prompts: Option<Arc<DynamicPromptsInner>>,
/// Lazily populates the dynamic prompt registry before list/get access.
#[cfg(feature = "dynamic-tools")]
prompt_initializer: Option<PromptInitializer>,
/// Dynamic resources registry for runtime resource (de)registration
#[cfg(feature = "dynamic-tools")]
dynamic_resources: Option<Arc<DynamicResourcesInner>>,
/// Dynamic resource templates registry for runtime template (de)registration
#[cfg(feature = "dynamic-tools")]
dynamic_resource_templates: Option<Arc<DynamicResourceTemplatesInner>>,
}
impl McpRouterInner {
/// Generate instructions text from registered tools, resources, and prompts.
fn generate_instructions(&self, config: &AutoInstructionsConfig) -> String {
let mut parts = Vec::new();
if let Some(prefix) = &config.prefix {
parts.push(prefix.clone());
}
// Tools section
if !self.tools.is_empty() {
let mut lines = vec!["## Tools".to_string(), String::new()];
let mut tools: Vec<_> = self.tools.values().collect();
tools.sort_by(|a, b| a.name.cmp(&b.name));
for tool in tools {
let desc = tool.description.as_deref().unwrap_or("No description");
let tags = annotation_tags(tool.annotations.as_ref());
if tags.is_empty() {
lines.push(format!("- **{}**: {}", tool.name, desc));
} else {
lines.push(format!("- **{}**: {} [{}]", tool.name, desc, tags));
}
}
parts.push(lines.join("\n"));
}
// Resources section
if !self.resources.is_empty() || !self.resource_templates.is_empty() {
let mut lines = vec!["## Resources".to_string(), String::new()];
let mut resources: Vec<_> = self.resources.values().collect();
resources.sort_by(|a, b| a.uri.cmp(&b.uri));
for resource in resources {
let desc = resource.description.as_deref().unwrap_or("No description");
lines.push(format!("- **{}**: {}", resource.uri, desc));
}
let mut templates: Vec<_> = self.resource_templates.iter().collect();
templates.sort_by(|a, b| a.uri_template.cmp(&b.uri_template));
for template in templates {
let desc = template.description.as_deref().unwrap_or("No description");
lines.push(format!("- **{}**: {}", template.uri_template, desc));
}
parts.push(lines.join("\n"));
}
// Prompts section
if !self.prompts.is_empty() {
let mut lines = vec!["## Prompts".to_string(), String::new()];
let mut prompts: Vec<_> = self.prompts.values().collect();
prompts.sort_by(|a, b| a.name.cmp(&b.name));
for prompt in prompts {
let desc = prompt.description.as_deref().unwrap_or("No description");
lines.push(format!("- **{}**: {}", prompt.name, desc));
}
parts.push(lines.join("\n"));
}
if let Some(suffix) = &config.suffix {
parts.push(suffix.clone());
}
parts.join("\n\n")
}
}
/// Build annotation tags like "read-only, idempotent" from tool annotations.
///
/// Only includes tags that differ from the MCP spec defaults
/// (read-only=false, idempotent=false). The destructive and open-world
/// hints are omitted because they match the default assumptions.
fn annotation_tags(annotations: Option<&crate::protocol::ToolAnnotations>) -> String {
let Some(ann) = annotations else {
return String::new();
};
let mut tags = Vec::new();
if ann.is_read_only() {
tags.push("read-only");
}
if ann.is_idempotent() {
tags.push("idempotent");
}
tags.join(", ")
}
impl McpRouter {
/// Create a new MCP router
pub fn new() -> Self {
Self {
inner: Arc::new(McpRouterInner {
server_name: "tower-mcp".to_string(),
server_version: env!("CARGO_PKG_VERSION").to_string(),
server_title: None,
server_description: None,
server_icons: None,
server_website_url: None,
instructions: None,
panic_policy: None,
task_error_policy: TaskErrorPolicy::default(),
auto_instructions: None,
tools: HashMap::new(),
resources: HashMap::new(),
resource_templates: Vec::new(),
prompts: HashMap::new(),
advertise_resource_subscriptions: true,
advertise_tools_list_changed: None,
advertise_prompts_list_changed: None,
advertise_resources_list_changed: None,
advertise_mcp_logging: None,
live_tasks: Arc::new(Mutex::new(HashMap::new())),
in_flight: Arc::new(RwLock::new(HashMap::new())),
next_dispatch: Arc::new(AtomicU64::new(0)),
notification_tx: None,
#[cfg(all(feature = "http", feature = "stateless"))]
modern_notification_sink: Arc::new(RwLock::new(None)),
#[cfg(feature = "stateless")]
subscription_observer: Arc::new(RwLock::new(None)),
client_requester: None,
task_store: Arc::new(MemoryTaskStore::new()),
subscriptions: Arc::new(RwLock::new(HashSet::new())),
extensions: Arc::new(crate::context::Extensions::new()),
protocol_extensions: HashMap::new(),
completion_handler: None,
tool_filter: None,
resource_filter: None,
prompt_filter: None,
min_log_level: Arc::new(RwLock::new(LogLevel::Debug)),
page_size: None,
list_ttl_ms: None,
read_ttl_ms: None,
cache_scope: None,
logging_deprecated: None,
disabled_tools: Arc::new(RwLock::new(HashSet::new())),
disabled_resources: Arc::new(RwLock::new(HashSet::new())),
disabled_prompts: Arc::new(RwLock::new(HashSet::new())),
#[cfg(feature = "dynamic-tools")]
dynamic_tools: None,
#[cfg(feature = "dynamic-tools")]
dynamic_prompts: None,
#[cfg(feature = "dynamic-tools")]
prompt_initializer: None,
#[cfg(feature = "dynamic-tools")]
dynamic_resources: None,
#[cfg(feature = "dynamic-tools")]
dynamic_resource_templates: None,
}),
session: SessionState::new(),
}
}
/// Create a clone with fresh session state.
///
/// Use this when creating a new logical session (e.g., per HTTP connection).
/// The router configuration (tools, resources, prompts) is shared, but the
/// session state (phase, extensions) is independent.
///
/// This is typically called by transports when establishing a new client session.
pub fn with_fresh_session(&self) -> Self {
Self {
inner: self.inner.clone(),
session: SessionState::new(),
}
}
/// Build a map of tool names to their annotations.
///
/// The returned [`ToolAnnotationsMap`] includes annotations from all
/// currently registered tools (both static and dynamic). Tools without
/// annotations are omitted from the map.
///
/// This is used internally by transports to inject annotations into
/// request extensions, but can also be called directly for custom
/// middleware setups.
pub fn tool_annotations_map(&self) -> ToolAnnotationsMap {
let disabled = self.inner.disabled_tools.read().unwrap();
let mut map = HashMap::new();
for (name, tool) in &self.inner.tools {
if disabled.contains(name) {
continue;
}
if let Some(annotations) = &tool.annotations {
map.insert(name.clone(), annotations.clone());
}
}
#[cfg(feature = "dynamic-tools")]
if let Some(dynamic) = &self.inner.dynamic_tools {
for tool in dynamic.list() {
if disabled.contains(&tool.name) {
continue;
}
// Static tools take precedence
if !map.contains_key(&tool.name)
&& let Some(ref annotations) = tool.annotations
{
map.insert(tool.name.clone(), annotations.clone());
}
}
}
ToolAnnotationsMap { map: Arc::new(map) }
}
/// Configure a pluggable [`TaskStore`] for async task state.
///
/// The default is an in-process [`MemoryTaskStore`]. Supply an external
/// store (Redis, Postgres, etc.) to share task state across server
/// instances behind a load balancer, so `tasks/get` works regardless of
/// which instance created the task (SEP-2663).
///
/// # Example
///
/// ```rust
/// use std::sync::Arc;
/// use tower_mcp::McpRouter;
/// use tower_mcp::async_task::{MemoryTaskStore, TaskStore};
///
/// let store: Arc<dyn TaskStore> = Arc::new(MemoryTaskStore::new());
/// let router = McpRouter::new().task_store(store);
/// ```
pub fn task_store(mut self, store: Arc<dyn TaskStore>) -> Self {
Arc::make_mut(&mut self.inner).task_store = store;
self
}
/// Set the root router's client-visible Task error policy.
///
/// The policy applies to task creation, `tasks/get`, `tasks/update`,
/// `tasks/cancel`, and failures while parking, executing, resuming, or
/// finalizing a handler. Like [`McpRouter::catch_panics_with`], it is root
/// configuration: merging or nesting another router imports that router's
/// capabilities but not its policy, so the receiving router governs the
/// combined catalog.
///
/// Tower's default preserves the established missing/expired response
/// shapes and redacts every [`TaskStoreError`] to a fixed internal error.
#[must_use]
pub fn task_error_policy(mut self, policy: TaskErrorPolicy) -> Self {
Arc::make_mut(&mut self.inner).task_error_policy = policy;
self
}
/// Enable dynamic tool registration and return a registry handle.
///
/// The returned [`DynamicToolRegistry`] can be used to add and remove tools
/// at runtime. Dynamic tools are merged with static tools when handling
/// `tools/list` and `tools/call` requests. Static tools take precedence
/// over dynamic tools when names collide.
///
/// # Example
///
/// ```rust
/// use tower_mcp::{McpRouter, ToolBuilder, CallToolResult};
/// use schemars::JsonSchema;
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, JsonSchema)]
/// struct Input { value: String }
///
/// let (router, registry) = McpRouter::new()
/// .server_info("my-server", "1.0.0")
/// .with_dynamic_tools();
///
/// // Register a tool at runtime
/// let tool = ToolBuilder::new("echo")
/// .description("Echo input")
/// .handler(|i: Input| async move { Ok(CallToolResult::text(&i.value)) })
/// .build();
///
/// registry.register(tool);
/// ```
#[cfg(feature = "dynamic-tools")]
pub fn with_dynamic_tools(mut self) -> (Self, DynamicToolRegistry) {
let inner_dyn = Arc::new(DynamicToolsInner::new());
Arc::make_mut(&mut self.inner).dynamic_tools = Some(inner_dyn.clone());
(self, DynamicToolRegistry::new(inner_dyn))
}
/// Enable dynamic prompt registration and return a registry handle.
///
/// The returned [`DynamicPromptRegistry`] can be used to add and remove
/// prompts at runtime. Dynamic prompts are merged with static prompts
/// when handling `prompts/list` and `prompts/get` requests. Static
/// prompts take precedence over dynamic prompts when names collide.
///
/// # Example
///
/// ```rust
/// use tower_mcp::{McpRouter, PromptBuilder};
///
/// let (router, registry) = McpRouter::new()
/// .server_info("my-server", "1.0.0")
/// .with_dynamic_prompts();
///
/// let prompt = PromptBuilder::new("greet")
/// .description("Greet someone")
/// .user_message("Hello!");
///
/// registry.register(prompt);
/// ```
#[cfg(feature = "dynamic-tools")]
pub fn with_dynamic_prompts(mut self) -> (Self, DynamicPromptRegistry) {
let inner_dyn = Arc::new(DynamicPromptsInner::new());
Arc::make_mut(&mut self.inner).dynamic_prompts = Some(inner_dyn.clone());
(self, DynamicPromptRegistry::new(inner_dyn))
}
/// Run an initializer before each `prompts/list` or `prompts/get` access.
///
/// This supports prompt definitions backed by an application-owned lazy
/// catalog. The initializer should populate the registry returned by
/// [`Self::with_dynamic_prompts`] and implement its own caching.
#[cfg(feature = "dynamic-tools")]
pub fn dynamic_prompt_initializer<F>(mut self, initializer: F) -> Self
where
F: Fn() -> Result<()> + Send + Sync + 'static,
{
Arc::make_mut(&mut self.inner).prompt_initializer = Some(Arc::new(initializer));
self
}
/// Enable dynamic resource registration and return a registry handle.
///
/// The returned [`DynamicResourceRegistry`] can be used to add and remove
/// resources at runtime. Dynamic resources are merged with static resources
/// when handling `resources/list` and `resources/read` requests. Static
/// resources take precedence over dynamic resources when URIs collide.
///
/// # Example
///
/// ```rust
/// use tower_mcp::{McpRouter, ResourceBuilder};
///
/// let (router, registry) = McpRouter::new()
/// .server_info("my-server", "1.0.0")
/// .with_dynamic_resources();
///
/// let resource = ResourceBuilder::new("file:///data.json")
/// .name("Data")
/// .text(r#"{"key": "value"}"#);
///
/// registry.register(resource);
/// ```
#[cfg(feature = "dynamic-tools")]
pub fn with_dynamic_resources(mut self) -> (Self, DynamicResourceRegistry) {
let inner_dyn = Arc::new(DynamicResourcesInner::new());
Arc::make_mut(&mut self.inner).dynamic_resources = Some(inner_dyn.clone());
(self, DynamicResourceRegistry::new(inner_dyn))
}
/// Enable dynamic resource template registration and return a registry handle.
///
/// The returned [`DynamicResourceTemplateRegistry`] can be used to add and
/// remove resource templates at runtime. Dynamic templates are checked
/// after static templates when handling `resources/read` requests.
///
/// # Example
///
/// ```rust,ignore
/// use tower_mcp::{McpRouter, ResourceTemplateBuilder};
///
/// let (router, registry) = McpRouter::new()
/// .server_info("my-server", "1.0.0")
/// .with_dynamic_resource_templates();
///
/// let template = ResourceTemplateBuilder::new("db://tables/{table}")
/// .name("Database Table")
/// .handler(|uri, vars| async move { /* ... */ });
///
/// registry.register(template);
/// ```
#[cfg(feature = "dynamic-tools")]
pub fn with_dynamic_resource_templates(mut self) -> (Self, DynamicResourceTemplateRegistry) {
let inner_dyn = Arc::new(DynamicResourceTemplatesInner::new());
Arc::make_mut(&mut self.inner).dynamic_resource_templates = Some(inner_dyn.clone());
(self, DynamicResourceTemplateRegistry::new(inner_dyn))
}
/// Set the notification sender without registering it with the shared
/// dynamic registries.
///
/// Used by transports for per-request (sessionless) notification
/// capture: the dynamic registries are long-lived and shared across
/// router clones, so registering one sender per request would
/// accumulate senders without bound.
#[cfg(feature = "stateless")]
#[cfg(feature = "http")]
pub(crate) fn with_request_notification_sender(mut self, tx: NotificationSender) -> Self {
Arc::make_mut(&mut self.inner).notification_tx = Some(tx);
self
}
/// Set the notification sender for progress reporting
///
/// This is typically called by the transport layer to receive notifications.
pub fn with_notification_sender(mut self, tx: NotificationSender) -> Self {
let inner = Arc::make_mut(&mut self.inner);
// Also register the sender with dynamic registries so they can
// broadcast list-changed notifications to this session.
#[cfg(feature = "dynamic-tools")]
if let Some(ref dynamic_tools) = inner.dynamic_tools {
dynamic_tools.add_notification_sender(tx.clone());
}
#[cfg(feature = "dynamic-tools")]
if let Some(ref dynamic_prompts) = inner.dynamic_prompts {
dynamic_prompts.add_notification_sender(tx.clone());
}
#[cfg(feature = "dynamic-tools")]
if let Some(ref dynamic_resources) = inner.dynamic_resources {
dynamic_resources.add_notification_sender(tx.clone());
}
#[cfg(feature = "dynamic-tools")]
if let Some(ref dynamic_resource_templates) = inner.dynamic_resource_templates {
dynamic_resource_templates.add_notification_sender(tx.clone());
}
inner.notification_tx = Some(tx);
self
}
/// Observe the terminal half of `subscriptions/listen` streams.
///
/// Every transport built from this router reports stream closes (reason
/// and duration) through the observer. The request half of the boundary
/// is ordinary `Service<RouterRequest>` middleware; see
/// [`SubscriptionObserver`](crate::transport::subscriptions::SubscriptionObserver) for how the two compose.
#[cfg(feature = "stateless")]
pub fn with_subscription_observer(
self,
observer: Arc<dyn crate::transport::subscriptions::SubscriptionObserver>,
) -> Self {
if let Ok(mut slot) = self.inner.subscription_observer.write() {
*slot = Some(observer);
}
self
}
/// The attached close observer, if any.
#[cfg(feature = "stateless")]
pub(crate) fn subscription_observer(
&self,
) -> Option<Arc<dyn crate::transport::subscriptions::SubscriptionObserver>> {
self.inner
.subscription_observer
.read()
.ok()
.and_then(|slot| slot.clone())
}
/// Attach the transport-lifetime final subscription notification path.
#[cfg(all(feature = "http", feature = "stateless"))]
pub(crate) fn attach_modern_notification_sink(&self, sink: ModernNotificationSink) {
if let Ok(mut active) = self.inner.modern_notification_sink.write() {
*active = Some(sink);
}
}
/// Get the notification sender (if configured)
pub fn notification_sender(&self) -> Option<&NotificationSender> {
self.inner.notification_tx.as_ref()
}
/// Set the client requester for server-to-client requests (sampling, etc.)
///
/// This is typically called by bidirectional transports (WebSocket, stdio)
/// to enable tool handlers to send requests to the client.
pub fn with_client_requester(mut self, requester: ClientRequesterHandle) -> Self {
Arc::make_mut(&mut self.inner).client_requester = Some(requester);
self
}
/// Get the client requester (if configured)
pub fn client_requester(&self) -> Option<&ClientRequesterHandle> {
self.inner.client_requester.as_ref()
}
/// Add router-level state that handlers can access via the `Extension<T>` extractor.
///
/// This is the recommended way to share state across all tools, resources, and prompts
/// in a router. The state is available to handlers via the [`crate::extract::Extension`]
/// extractor.
///
/// # Example
///
/// ```rust
/// use std::sync::Arc;
/// use tower_mcp::{McpRouter, ToolBuilder, CallToolResult};
/// use tower_mcp::extract::{Extension, Json};
/// use schemars::JsonSchema;
/// use serde::Deserialize;
///
/// #[derive(Clone)]
/// struct AppState {
/// db_url: String,
/// }
///
/// #[derive(Deserialize, JsonSchema)]
/// struct QueryInput {
/// sql: String,
/// }
///
/// let state = Arc::new(AppState { db_url: "postgres://...".into() });
///
/// // Tool extracts state via Extension<T>
/// let query_tool = ToolBuilder::new("query")
/// .description("Run a database query")
/// .extractor_handler(
/// (),
/// |Extension(state): Extension<Arc<AppState>>, Json(input): Json<QueryInput>| async move {
/// Ok(CallToolResult::text(format!("Query on {}: {}", state.db_url, input.sql)))
/// },
/// )
/// .build();
///
/// let router = McpRouter::new()
/// .with_state(state) // State is now available to all handlers
/// .tool(query_tool);
/// ```
pub fn with_state<T: Clone + Send + Sync + 'static>(mut self, state: T) -> Self {
let inner = Arc::make_mut(&mut self.inner);
Arc::make_mut(&mut inner.extensions).insert(state);
self
}
/// Add an extension value that handlers can access via the `Extension<T>` extractor.
///
/// This is a more general form of `with_state()` for when you need multiple
/// typed values available to handlers.
pub fn with_extension<T: Clone + Send + Sync + 'static>(self, value: T) -> Self {
self.with_state(value)
}
/// Advertise one validated MCP protocol extension.
///
/// This is separate from [`with_extension`](Self::with_extension), which
/// stores process-local Rust values for handlers. Protocol extensions are
/// advertised on the wire and become active only when the client declares
/// the same identifier.
pub fn with_protocol_extension(mut self, extension: crate::ExtensionDeclaration) -> Self {
let (identifier, settings) = extension.into_parts();
Arc::make_mut(&mut self.inner)
.protocol_extensions
.insert(identifier, settings);
self
}
/// Get the router's extensions.
pub fn extensions(&self) -> &crate::context::Extensions {
&self.inner.extensions
}
/// Create a request context for tracking a request
///
/// This registers the request for cancellation tracking and sets up
/// progress reporting, client requests, and router extensions if configured.
pub fn create_context(
&self,
request_id: RequestId,
progress_token: Option<ProgressToken>,
) -> RequestContext {
self.create_context_with_extensions(request_id, progress_token, &Extensions::new())
}
/// Internal: build a `RequestContext` and additionally merge per-request
/// extensions on top of the router's extensions. Used by [`Service::call`]
/// to thread `RouterRequest.extensions` (e.g. SEP-2575 per-request
/// `_meta`) through to handlers.
pub(crate) fn create_context_with_extensions(
&self,
request_id: RequestId,
progress_token: Option<ProgressToken>,
per_request: &Extensions,
) -> RequestContext {
let ctx = RequestContext::new(request_id.clone());
// Set up progress token if provided
let ctx = if let Some(token) = progress_token {
ctx.with_progress_token(token)
} else {
ctx
};
// Set up notification sender if configured
let ctx = if let Some(tx) = &self.inner.notification_tx {
ctx.with_notification_sender(tx.clone())
} else {
ctx
};
// Start with router-level extensions, then layer per-request extensions
// on top so they win on type collision. with_state() data stays
// visible; per-request meta (SEP-2575) is now reachable too.
let mut merged = (*self.inner.extensions).clone();
merged.merge(per_request);
let negotiated_extensions = if is_final_protocol_request(per_request) {
let server_capabilities =
self.capabilities_for_protocol(Some(crate::protocol::PROTOCOL_VERSION_2026_07_28));
final_client_capabilities(per_request)
.map(|client_capabilities| {
crate::NegotiatedExtensions::from_capabilities(
client_capabilities,
&server_capabilities,
)
})
.unwrap_or_default()
} else {
self.session
.get::<crate::NegotiatedExtensions>()
.unwrap_or_default()
};
merged.insert(negotiated_extensions);
// The final protocol does not permit servers to initiate JSON-RPC
// requests. Legacy transports may provide a requester scoped to the
// originating request; prefer it over a transport-wide fallback so
// restricted requests stay on their associated response channel.
let final_lifecycle = is_final_protocol_request(per_request);
let ctx = ctx.with_final_lifecycle(final_lifecycle);
let ctx = if !final_lifecycle
&& let Some(requester) = merged
.get::<ClientRequesterHandle>()
.cloned()
.or_else(|| self.inner.client_requester.clone())
{
ctx.with_client_requester(requester)
} else {
ctx
};
// Adopt a transport-provided cancellation token (e.g. HTTP stateless
// client disconnect) so `ctx.is_cancelled()` / `ctx.cancelled()` and
// in-flight tracking observe the transport's signal.
let ctx = if let Some(token) = merged.get::<CancellationToken>() {
ctx.with_cancellation_token(token.clone())
} else {
ctx
};
let ctx = ctx.with_extensions(Arc::new(merged));
// Set up log level filtering
let ctx = ctx.with_min_log_level(self.inner.min_log_level.clone());
// Register for cancellation tracking. `Service::call` mints the
// dispatch id and threads it through the extensions so the guard it
// holds and this registration name the same entry; a caller driving
// the router directly gets a fresh one.
let dispatch = per_request
.get::<DispatchId>()
.copied()
.unwrap_or_else(|| self.next_dispatch());
self.register_in_flight(request_id, dispatch, ctx.cancellation_token());
ctx
}
/// Allocate a dispatch id, unique for the lifetime of this router.
fn next_dispatch(&self) -> DispatchId {
DispatchId(
self.inner
.next_dispatch
.fetch_add(1, AtomicOrdering::Relaxed),
)
}
/// Track one dispatch for cancellation.
///
/// Appends rather than overwrites: a client that reuses an id which is
/// still in flight gets both requests tracked, so cancelling the id can
/// still reach both (#1270).
fn register_in_flight(
&self,
request_id: RequestId,
dispatch: DispatchId,
token: CancellationToken,
) {
if let Ok(mut in_flight) = self.inner.in_flight.write() {
in_flight
.entry(request_id)
.or_default()
.push(InFlightDispatch { dispatch, token });
}
}
/// Stop tracking one dispatch, leaving any twin under the same id alone.
fn complete_dispatch(&self, request_id: &RequestId, dispatch: DispatchId) {
if let Ok(mut in_flight) = self.inner.in_flight.write()
&& let Some(entries) = in_flight.get_mut(request_id)
{
entries.retain(|entry| entry.dispatch != dispatch);
if entries.is_empty() {
in_flight.remove(request_id);
}
}
}
/// Remove a request from tracking (called when request completes).
///
/// Untracks *every* dispatch under `request_id`, which is the only
/// granularity this signature offers. Requests dispatched through
/// [`Service::call`] do not need it: each holds a guard that untracks its
/// own dispatch when the future completes, is dropped, or unwinds. It
/// remains for callers driving [`McpRouter::create_context`] and request
/// handling themselves.
pub fn complete_request(&self, request_id: &RequestId) {
if let Ok(mut in_flight) = self.inner.in_flight.write() {
in_flight.remove(request_id);
}
}
/// Cancel a tracked request.
///
/// Cancels every dispatch still running under `request_id`. The id is the
/// only handle a client has, so a client that reused one in flight gets
/// both stopped rather than an arbitrary one.
fn cancel_request(&self, request_id: &RequestId) -> bool {
let Ok(in_flight) = self.inner.in_flight.read() else {
return false;
};
let Some(entries) = in_flight.get(request_id) else {
return false;
};
for entry in entries {
entry.token.cancel();
}
!entries.is_empty()
}
/// Whether to advertise `resources.subscribe` when resources exist.
///
/// Defaults to `true`, which is what this router has always advertised as
/// soon as any resource or template is registered. Pass `false` for a
/// server that exposes read-only resources and no update stream, so it
/// does not promise a subscription it will not honour (#1261).
///
/// This affects advertisement only. `resources/subscribe` continues to be
/// routed either way, so a client that ignores the capability and calls it
/// anyway behaves as before.
///
/// The 2026-07-28 revision has no `resources/subscribe` method at all, so
/// the capability is never advertised on that lifecycle regardless of this
/// setting.
///
/// ```rust
/// use tower_mcp::{McpRouter, ResourceBuilder};
///
/// let router = McpRouter::new()
/// .server_info("read-only", "1.0.0")
/// .resource(ResourceBuilder::new("mem://one").name("one").text("hi"))
/// .resource_subscriptions(false);
/// ```
pub fn resource_subscriptions(mut self, advertise: bool) -> Self {
Arc::make_mut(&mut self.inner).advertise_resource_subscriptions = advertise;
self
}
/// Whether to advertise `tools.listChanged`.
///
/// Defaults to whether a notification channel is attached to this
/// router, which is what it has always advertised: choosing a transport
/// that installs the channel (for example `StdioTransport::new`)
/// promised `tools/list_changed` traffic even for a server that never
/// sends it. Pass `true` or `false` to declare the flag independently of
/// that channel (#1338).
///
/// This affects advertisement only. Notifications are still routed
/// through the channel exactly as before; this only changes what
/// `initialize` reports.
///
/// An explicit call here always wins over the notification-channel
/// default, including under `StdioTransport::without_server_notifications`
/// (#1257), which leaves the channel unattached. That method is the
/// all-or-nothing switch; this builder is the per-flag refinement
/// underneath it, so setting `tools_list_changed(true)` still advertises
/// the flag even though the transport will never emit it.
///
/// ```rust
/// use tower_mcp::McpRouter;
///
/// let router = McpRouter::new()
/// .server_info("my-server", "1.0.0")
/// .tools_list_changed(true);
/// ```
pub fn tools_list_changed(mut self, advertise: bool) -> Self {
Arc::make_mut(&mut self.inner).advertise_tools_list_changed = Some(advertise);
self
}
/// Whether to advertise `prompts.listChanged`.
///
/// Defaults to whether a notification channel is attached to this
/// router, which is what it has always advertised: choosing a transport
/// that installs the channel (for example `StdioTransport::new`)
/// promised `prompts/list_changed` traffic even for a server that never
/// sends it. Pass `true` or `false` to declare the flag independently of
/// that channel (#1338).
///
/// This affects advertisement only. Notifications are still routed
/// through the channel exactly as before; this only changes what
/// `initialize` reports.
///
/// An explicit call here always wins over the notification-channel
/// default, including under `StdioTransport::without_server_notifications`
/// (#1257), which leaves the channel unattached. That method is the
/// all-or-nothing switch; this builder is the per-flag refinement
/// underneath it, so setting `prompts_list_changed(true)` still
/// advertises the flag even though the transport will never emit it.
///
/// ```rust
/// use tower_mcp::McpRouter;
///
/// let router = McpRouter::new()
/// .server_info("my-server", "1.0.0")
/// .prompts_list_changed(false);
/// ```
pub fn prompts_list_changed(mut self, advertise: bool) -> Self {
Arc::make_mut(&mut self.inner).advertise_prompts_list_changed = Some(advertise);
self
}
/// Whether to advertise `resources.listChanged`.
///
/// Defaults to whether a notification channel is attached to this
/// router, which is what it has always advertised: choosing a transport
/// that installs the channel (for example `StdioTransport::new`)
/// promised `resources/list_changed` traffic even for a server that
/// never sends it. Pass `true` or `false` to declare the flag
/// independently of that channel (#1338).
///
/// This affects advertisement only. Notifications are still routed
/// through the channel exactly as before; this only changes what
/// `initialize` reports. It is independent of
/// [`Self::resource_subscriptions`], which governs `resources.subscribe`
/// rather than `resources.listChanged`.
///
/// An explicit call here always wins over the notification-channel
/// default, including under `StdioTransport::without_server_notifications`
/// (#1257), which leaves the channel unattached. That method is the
/// all-or-nothing switch; this builder is the per-flag refinement
/// underneath it, so setting `resources_list_changed(true)` still
/// advertises the flag even though the transport will never emit it.
///
/// ```rust
/// use tower_mcp::McpRouter;
///
/// let router = McpRouter::new()
/// .server_info("my-server", "1.0.0")
/// .resources_list_changed(false);
/// ```
pub fn resources_list_changed(mut self, advertise: bool) -> Self {
Arc::make_mut(&mut self.inner).advertise_resources_list_changed = Some(advertise);
self
}
/// Whether to advertise the `logging` capability (MCP logging, i.e.
/// `notifications/message`).
///
/// Defaults to whether a notification channel is attached to this
/// router, which is what it has always advertised: choosing a transport
/// that installs the channel (for example `StdioTransport::new`)
/// promised MCP logging even for a server that logs elsewhere, such as
/// stderr or OTLP. Pass `true` or `false` to declare the flag
/// independently of that channel (#1338).
///
/// This affects advertisement only. [`McpRouter::log`] and its
/// convenience methods still route through the channel exactly as
/// before; this only changes what `initialize` reports.
///
/// An explicit call here always wins over the notification-channel
/// default, including under `StdioTransport::without_server_notifications`
/// (#1257), which leaves the channel unattached. That method is the
/// all-or-nothing switch; this builder is the per-flag refinement
/// underneath it, so setting `mcp_logging(true)` still advertises the
/// flag even though the transport will never emit it.
///
/// ```rust
/// use tower_mcp::McpRouter;
///
/// let router = McpRouter::new()
/// .server_info("my-server", "1.0.0")
/// .mcp_logging(false);
/// ```
pub fn mcp_logging(mut self, advertise: bool) -> Self {
Arc::make_mut(&mut self.inner).advertise_mcp_logging = Some(advertise);
self
}
/// Set server info
pub fn server_info(mut self, name: impl Into<String>, version: impl Into<String>) -> Self {
let inner = Arc::make_mut(&mut self.inner);
inner.server_name = name.into();
inner.server_version = version.into();
self
}
/// Set the page size for list method pagination.
///
/// When set, list methods (`tools/list`, `resources/list`, etc.) will return
/// at most `page_size` items per response, with a `next_cursor` for fetching
/// subsequent pages. When `None` (the default), all items are returned in a
/// single response.
pub fn page_size(mut self, size: usize) -> Self {
Arc::make_mut(&mut self.inner).page_size = Some(size);
self
}
/// Set a TTL hint on list responses (tools/list, resources/list, prompts/list).
///
/// When set, the `ttlMs` field is included in list responses so clients can
/// cache the list for up to this many milliseconds before re-fetching.
/// Implements SEP-2549.
pub fn list_ttl(mut self, ms: u64) -> Self {
Arc::make_mut(&mut self.inner).list_ttl_ms = Some(ms);
self
}
/// Set a default TTL hint on resources/read responses (SEP-2549).
///
/// Applied only when the resource handler did not set its own `ttl_ms`
/// on the [`ReadResourceResult`]. When any TTL is emitted without a
/// configured [`cache_scope`](Self::cache_scope), the scope defaults to
/// `private`.
pub fn read_ttl(mut self, ms: u64) -> Self {
Arc::make_mut(&mut self.inner).read_ttl_ms = Some(ms);
self
}
/// Set the SEP-2549 cache scope emitted alongside TTL hints on list and
/// resources/read responses.
///
/// `CacheScope::Public` allows any client, gateway, or proxy to reuse
/// the cached result across authorization contexts; `CacheScope::Private`
/// restricts reuse to the same authorization context. When a TTL is
/// emitted and no scope is configured, `private` is used as the
/// conservative default.
pub fn cache_scope(mut self, scope: CacheScope) -> Self {
Arc::make_mut(&mut self.inner).cache_scope = Some(scope);
self
}
/// Mark the logging capability as deprecated in the server's initialize result.
///
/// When set, the `deprecated` object is included in the `logging` capability
/// in the `initialize` response, signalling to clients that logging notifications
/// are being phased out. Implements SEP-2577.
pub fn logging_deprecated(mut self, info: tower_mcp_types::protocol::DeprecationInfo) -> Self {
Arc::make_mut(&mut self.inner).logging_deprecated = Some(info);
self
}
/// Set instructions for LLMs describing how to use this server
pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
Arc::make_mut(&mut self.inner).instructions = Some(instructions.into());
self
}
/// Convert a panicking tool handler into an error result instead of
/// letting it unwind out of the service.
///
/// Without this, a panic in one handler ends the whole server over stdio
/// and kills the connection task over HTTP. A bug in one tool should fail
/// that call, not disconnect every client on the process, which is what
/// makes this worth having on a long-running shared server.
///
/// Off by default, deliberately. A panic is an invariant violation, and
/// converting one into a tidy error result hides a bug that the author
/// probably wants to see. Opting in is a statement that availability
/// matters more than failing fast, which is true for a shared server and
/// often false for a local one.
///
/// For ordinary and replayed handlers, the caught panic becomes a
/// `CallToolResult` with `is_error: true` carrying the panic message. A
/// live Task handler instead reaches `failed` with the same detailed
/// message. Both are logged at error level with the tool name so the panic
/// is not silently swallowed.
///
/// A panic that unwinds is caught; one that aborts the process (a
/// double panic, or `panic = "abort"`) cannot be, by construction.
pub fn catch_panics(mut self) -> Self {
Arc::make_mut(&mut self.inner).panic_policy = Some(PanicPolicy::detailed());
self
}
/// Convert a panicking tool handler into an error result using an
/// application-selected disclosure policy.
///
/// [`PanicPolicy::redacted`] returns fixed client text and omits both the
/// tool name and panic payload from Tower's tracing event by default.
/// Unlike [`McpRouter::catch_panics`], a custom policy never includes the
/// panic payload in the client response.
///
/// The policy applies to ordinary calls and both replayed and live Task
/// handlers registered on this router. Router-level configuration is not
/// imported when another router is merged or nested, so the receiving
/// router's policy governs the combined catalog.
///
/// Rust's process-global panic hook runs before the unwind is caught, so
/// this controls Tower's client response and tracing event only. It does
/// not suppress application or default panic-hook output.
///
/// A panic that aborts the process (a double panic, or
/// `panic = "abort"`) cannot be caught.
pub fn catch_panics_with(mut self, policy: PanicPolicy) -> Self {
Arc::make_mut(&mut self.inner).panic_policy = Some(policy);
self
}
/// Auto-generate instructions from registered tool, resource, and prompt descriptions.
///
/// The instructions are generated lazily at initialization time, so this can be
/// called at any point in the builder chain regardless of when tools, resources,
/// and prompts are registered.
///
/// If both `instructions()` and `auto_instructions()` are set, the auto-generated
/// instructions take precedence.
///
/// # Example
///
/// ```rust
/// use tower_mcp::{McpRouter, ToolBuilder, CallToolResult};
/// use schemars::JsonSchema;
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, JsonSchema)]
/// struct QueryInput { sql: String }
///
/// let query_tool = ToolBuilder::new("query")
/// .description("Execute a read-only SQL query")
/// .read_only()
/// .handler(|input: QueryInput| async move {
/// Ok(CallToolResult::text("result"))
/// })
/// .build();
///
/// let router = McpRouter::new()
/// .auto_instructions()
/// .tool(query_tool);
/// ```
pub fn auto_instructions(mut self) -> Self {
Arc::make_mut(&mut self.inner).auto_instructions = Some(AutoInstructionsConfig {
prefix: None,
suffix: None,
});
self
}
/// Auto-generate instructions with custom prefix and/or suffix text.
///
/// The prefix is prepended and suffix appended to the generated instructions.
/// See [`auto_instructions`](Self::auto_instructions) for details.
///
/// # Example
///
/// ```rust
/// use tower_mcp::McpRouter;
///
/// let router = McpRouter::new()
/// .auto_instructions_with(
/// Some("This server provides database tools."),
/// Some("Use 'query' for read operations and 'insert' for writes."),
/// );
/// ```
pub fn auto_instructions_with(
mut self,
prefix: Option<impl Into<String>>,
suffix: Option<impl Into<String>>,
) -> Self {
Arc::make_mut(&mut self.inner).auto_instructions = Some(AutoInstructionsConfig {
prefix: prefix.map(Into::into),
suffix: suffix.map(Into::into),
});
self
}
/// Set a human-readable title for the server
pub fn server_title(mut self, title: impl Into<String>) -> Self {
Arc::make_mut(&mut self.inner).server_title = Some(title.into());
self
}
/// Set the server description
pub fn server_description(mut self, description: impl Into<String>) -> Self {
Arc::make_mut(&mut self.inner).server_description = Some(description.into());
self
}
/// Set icons for the server
pub fn server_icons(mut self, icons: Vec<ToolIcon>) -> Self {
Arc::make_mut(&mut self.inner).server_icons = Some(icons);
self
}
/// Set the server's website URL
pub fn server_website_url(mut self, url: impl Into<String>) -> Self {
Arc::make_mut(&mut self.inner).server_website_url = Some(url.into());
self
}
/// Register a tool
pub fn tool(mut self, tool: Tool) -> Self {
Arc::make_mut(&mut self.inner)
.tools
.insert(tool.name.clone(), Arc::new(tool));
self
}
/// Conditionally register a tool.
///
/// Registers the tool only if `condition` is `true`. This keeps fluent
/// builder chains intact when tools are conditionally enabled.
///
/// # Example
///
/// ```rust
/// use tower_mcp::{McpRouter, ToolBuilder, CallToolResult};
/// use schemars::JsonSchema;
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, JsonSchema)]
/// struct Input { value: String }
///
/// let enable_admin = false;
///
/// let admin_tool = ToolBuilder::new("admin")
/// .description("Admin tool")
/// .handler(|i: Input| async move { Ok(CallToolResult::text(&i.value)) })
/// .build();
///
/// let router = McpRouter::new()
/// .tool_if(enable_admin, admin_tool);
/// ```
pub fn tool_if(self, condition: bool, tool: Tool) -> Self {
if condition { self.tool(tool) } else { self }
}
/// Register a resource
pub fn resource(mut self, resource: Resource) -> Self {
Arc::make_mut(&mut self.inner)
.resources
.insert(resource.uri.clone(), Arc::new(resource));
self
}
/// Conditionally register a resource.
///
/// Registers the resource only if `condition` is `true`.
///
/// # Example
///
/// ```rust
/// use tower_mcp::{McpRouter, ResourceBuilder};
///
/// let enable_config = false;
///
/// let config = ResourceBuilder::new("config://system")
/// .name("config")
/// .text("secret=xxx");
///
/// let router = McpRouter::new()
/// .resource_if(enable_config, config);
/// ```
pub fn resource_if(self, condition: bool, resource: Resource) -> Self {
if condition {
self.resource(resource)
} else {
self
}
}
/// Register a resource template
///
/// Resource templates allow dynamic resources to be matched by URI pattern.
/// When a client requests a resource URI that doesn't match any static
/// resource, the router tries to match it against registered templates.
///
/// # Example
///
/// ```rust
/// use tower_mcp::{McpRouter, ResourceTemplateBuilder};
/// use tower_mcp::protocol::{ReadResourceResult, ResourceContent};
/// use std::collections::HashMap;
///
/// let template = ResourceTemplateBuilder::new("file:///{path}")
/// .name("Project Files")
/// .handler(|uri: String, vars: HashMap<String, String>| async move {
/// let path = vars.get("path").unwrap_or(&String::new()).clone();
/// Ok(ReadResourceResult {
/// contents: vec![ResourceContent {
/// uri,
/// mime_type: Some("text/plain".to_string()),
/// text: Some(format!("Contents of {}", path)),
/// blob: None,
/// meta: None,
/// }],
/// meta: None,
/// ..Default::default()
/// })
/// });
///
/// let router = McpRouter::new()
/// .resource_template(template);
/// ```
pub fn resource_template(mut self, template: ResourceTemplate) -> Self {
Arc::make_mut(&mut self.inner)
.resource_templates
.push(Arc::new(template));
self
}
/// Register a prompt
pub fn prompt(mut self, prompt: Prompt) -> Self {
Arc::make_mut(&mut self.inner)
.prompts
.insert(prompt.name.clone(), Arc::new(prompt));
self
}
/// Conditionally register a prompt.
///
/// Registers the prompt only if `condition` is `true`.
///
/// # Example
///
/// ```rust
/// use tower_mcp::{McpRouter, PromptBuilder};
///
/// let enable_debug = false;
///
/// let debug_prompt = PromptBuilder::new("debug")
/// .description("Debug prompt")
/// .user_message("Debug mode enabled");
///
/// let router = McpRouter::new()
/// .prompt_if(enable_debug, debug_prompt);
/// ```
pub fn prompt_if(self, condition: bool, prompt: Prompt) -> Self {
if condition { self.prompt(prompt) } else { self }
}
/// Register multiple tools at once.
///
/// # Example
///
/// ```rust
/// use tower_mcp::{McpRouter, ToolBuilder, CallToolResult};
/// use schemars::JsonSchema;
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, JsonSchema)]
/// struct Input { value: String }
///
/// let tools = vec![
/// ToolBuilder::new("a")
/// .description("Tool A")
/// .handler(|i: Input| async move { Ok(CallToolResult::text(&i.value)) })
/// .build(),
/// ToolBuilder::new("b")
/// .description("Tool B")
/// .handler(|i: Input| async move { Ok(CallToolResult::text(&i.value)) })
/// .build(),
/// ];
///
/// let router = McpRouter::new().tools(tools);
/// ```
pub fn tools(self, tools: impl IntoIterator<Item = Tool>) -> Self {
tools
.into_iter()
.fold(self, |router, tool| router.tool(tool))
}
/// Conditionally register multiple tools at once.
///
/// Registers all tools only if `condition` is `true`.
pub fn tools_if(self, condition: bool, tools: impl IntoIterator<Item = Tool>) -> Self {
if condition { self.tools(tools) } else { self }
}
/// Register multiple resources at once.
///
/// # Example
///
/// ```rust
/// use tower_mcp::{McpRouter, ResourceBuilder};
///
/// let resources = vec![
/// ResourceBuilder::new("file:///a.txt")
/// .name("File A")
/// .text("contents a"),
/// ResourceBuilder::new("file:///b.txt")
/// .name("File B")
/// .text("contents b"),
/// ];
///
/// let router = McpRouter::new().resources(resources);
/// ```
pub fn resources(self, resources: impl IntoIterator<Item = Resource>) -> Self {
resources
.into_iter()
.fold(self, |router, resource| router.resource(resource))
}
/// Conditionally register multiple resources at once.
///
/// Registers all resources only if `condition` is `true`.
pub fn resources_if(
self,
condition: bool,
resources: impl IntoIterator<Item = Resource>,
) -> Self {
if condition {
self.resources(resources)
} else {
self
}
}
/// Register multiple prompts at once.
///
/// # Example
///
/// ```rust
/// use tower_mcp::{McpRouter, PromptBuilder};
///
/// let prompts = vec![
/// PromptBuilder::new("greet")
/// .description("Greet someone")
/// .user_message("Hello!"),
/// PromptBuilder::new("farewell")
/// .description("Say goodbye")
/// .user_message("Goodbye!"),
/// ];
///
/// let router = McpRouter::new().prompts(prompts);
/// ```
pub fn prompts(self, prompts: impl IntoIterator<Item = Prompt>) -> Self {
prompts
.into_iter()
.fold(self, |router, prompt| router.prompt(prompt))
}
/// Conditionally register multiple prompts at once.
///
/// Registers all prompts only if `condition` is `true`.
pub fn prompts_if(self, condition: bool, prompts: impl IntoIterator<Item = Prompt>) -> Self {
if condition {
self.prompts(prompts)
} else {
self
}
}
/// Merge another router's capabilities into this one.
///
/// This combines all tools, resources, resource templates, and prompts from
/// the other router into this router. Uses "last wins" semantics for conflicts,
/// meaning if both routers have a tool/resource/prompt with the same name,
/// the one from `other` will replace the one in `self`.
///
/// Server info, instructions, filters, and other router-level configuration
/// are NOT merged - only the root router's settings are used.
///
/// # Example
///
/// ```rust
/// use tower_mcp::{McpRouter, ToolBuilder, CallToolResult, ResourceBuilder};
/// use schemars::JsonSchema;
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, JsonSchema)]
/// struct Input { value: String }
///
/// // Create a router with database tools
/// let db_tools = McpRouter::new()
/// .tool(
/// ToolBuilder::new("query")
/// .description("Query the database")
/// .handler(|i: Input| async move { Ok(CallToolResult::text(&i.value)) })
/// .build()
/// );
///
/// // Create a router with API tools
/// let api_tools = McpRouter::new()
/// .tool(
/// ToolBuilder::new("fetch")
/// .description("Fetch from API")
/// .handler(|i: Input| async move { Ok(CallToolResult::text(&i.value)) })
/// .build()
/// );
///
/// // Merge them together
/// let router = McpRouter::new()
/// .server_info("combined", "1.0")
/// .merge(db_tools)
/// .merge(api_tools);
/// ```
pub fn merge(mut self, other: McpRouter) -> Self {
let inner = Arc::make_mut(&mut self.inner);
let other_inner = other.inner;
// Merge tools (last wins)
for (name, tool) in &other_inner.tools {
inner.tools.insert(name.clone(), tool.clone());
}
// Merge resources (last wins)
for (uri, resource) in &other_inner.resources {
inner.resources.insert(uri.clone(), resource.clone());
}
// Merge resource templates (append - no deduplication since templates
// can have complex matching behavior)
for template in &other_inner.resource_templates {
inner.resource_templates.push(template.clone());
}
// Merge prompts (last wins)
for (name, prompt) in &other_inner.prompts {
inner.prompts.insert(name.clone(), prompt.clone());
}
// Merge protocol extension declarations (last wins).
for (identifier, settings) in &other_inner.protocol_extensions {
inner
.protocol_extensions
.insert(identifier.clone(), settings.clone());
}
self
}
/// Report the names both this router and `other` define.
///
/// [`merge`](Self::merge) resolves a collision by letting the incoming
/// router win, which is a reasonable default but leaves no trace that an
/// implementation was dropped. A host that composes a router it does not
/// own can call this first and fail at startup, which is the cheapest
/// moment to catch the clash (#1232).
///
/// Results are ordered by kind and then name, so they are stable enough
/// to assert on and to print.
///
/// Protocol extension declarations are deliberately excluded. Two routers
/// both declaring the same extension is ordinary composition rather than
/// a collision, since a declaration carries no implementation to lose.
///
/// # Example
///
/// ```rust
/// use tower_mcp::{McpRouter, ToolBuilder, CallToolResult};
/// use schemars::JsonSchema;
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, JsonSchema)]
/// struct Input { value: String }
///
/// fn router_with(name: &str) -> McpRouter {
/// McpRouter::new().tool(
/// ToolBuilder::new(name)
/// .description("example")
/// .handler(|i: Input| async move { Ok(CallToolResult::text(&i.value)) })
/// .build(),
/// )
/// }
///
/// let host = router_with("get_task");
/// let library = router_with("get_task");
/// let clashes = host.conflicts(&library);
/// assert_eq!(clashes.len(), 1);
/// assert_eq!(clashes[0].name, "get_task");
/// ```
pub fn conflicts(&self, other: &McpRouter) -> Vec<MergeConflict> {
let mut found = Vec::new();
for name in other.inner.tools.keys() {
if self.inner.tools.contains_key(name) {
found.push(MergeConflict::new(MergeConflictKind::Tool, name));
}
}
for uri in other.inner.resources.keys() {
if self.inner.resources.contains_key(uri) {
found.push(MergeConflict::new(MergeConflictKind::Resource, uri));
}
}
// Templates are stored as a list rather than a map because matching
// is pattern-based, so identity here is the template string itself.
for template in &other.inner.resource_templates {
if self
.inner
.resource_templates
.iter()
.any(|existing| existing.uri_template == template.uri_template)
{
found.push(MergeConflict::new(
MergeConflictKind::ResourceTemplate,
&template.uri_template,
));
}
}
for name in other.inner.prompts.keys() {
if self.inner.prompts.contains_key(name) {
found.push(MergeConflict::new(MergeConflictKind::Prompt, name));
}
}
// `tools`, `resources`, and `prompts` are hash maps, so without this
// the order would vary between runs.
found.sort_by(|a, b| (a.kind, &a.name).cmp(&(b.kind, &b.name)));
found
}
/// Merge another router, failing if either defines a name the other does.
///
/// This is [`merge`](Self::merge) with the collision reported instead of
/// resolved. Use it when a silently dropped tool would surface later as a
/// capability that behaves unexpectedly rather than as an error, which is
/// the usual case when a host merges in a router from a library that
/// cannot know what the host already registered.
///
/// Callers who want the incoming router to win keep using
/// [`merge`](Self::merge). To inspect without consuming either router,
/// use [`conflicts`](Self::conflicts).
///
/// # Errors
///
/// Returns every conflicting name, not just the first, so a startup
/// failure names all the work to be done.
///
/// # Example
///
/// ```rust
/// use tower_mcp::{McpRouter, ToolBuilder, CallToolResult};
/// use schemars::JsonSchema;
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, JsonSchema)]
/// struct Input { value: String }
///
/// fn router_with(name: &str) -> McpRouter {
/// McpRouter::new().tool(
/// ToolBuilder::new(name)
/// .description("example")
/// .handler(|i: Input| async move { Ok(CallToolResult::text(&i.value)) })
/// .build(),
/// )
/// }
///
/// // Distinct names merge.
/// let combined = router_with("query").try_merge(router_with("fetch"));
/// assert!(combined.is_ok());
///
/// // A shared name is reported rather than dropped.
/// let clash = router_with("get_task").try_merge(router_with("get_task"));
/// let error = clash.unwrap_err();
/// assert_eq!(error.conflicts().len(), 1);
/// ```
pub fn try_merge(self, other: McpRouter) -> std::result::Result<Self, MergeConflicts> {
let conflicts = self.conflicts(&other);
if conflicts.is_empty() {
Ok(self.merge(other))
} else {
Err(MergeConflicts { conflicts })
}
}
/// Nest another router's capabilities under a prefix.
///
/// This is similar to `merge()`, but all tool names from the nested router
/// are prefixed with the given string and a dot separator. For example,
/// nesting with prefix "db" will turn a tool named "query" into "db.query".
///
/// Resources, resource templates, and prompts are merged without modification
/// since they use URIs rather than simple names for identification.
///
/// # Example
///
/// ```rust
/// use tower_mcp::{McpRouter, ToolBuilder, CallToolResult};
/// use schemars::JsonSchema;
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, JsonSchema)]
/// struct Input { value: String }
///
/// // Create a router with database tools
/// let db_tools = McpRouter::new()
/// .tool(
/// ToolBuilder::new("query")
/// .description("Query the database")
/// .handler(|i: Input| async move { Ok(CallToolResult::text(&i.value)) })
/// .build()
/// )
/// .tool(
/// ToolBuilder::new("insert")
/// .description("Insert into database")
/// .handler(|i: Input| async move { Ok(CallToolResult::text(&i.value)) })
/// .build()
/// );
///
/// // Nest under "db" prefix - tools become "db.query" and "db.insert"
/// let router = McpRouter::new()
/// .server_info("combined", "1.0")
/// .nest("db", db_tools);
/// ```
pub fn nest(mut self, prefix: impl Into<String>, other: McpRouter) -> Self {
let prefix = prefix.into();
let inner = Arc::make_mut(&mut self.inner);
let other_inner = other.inner;
// Nest tools with prefix
for tool in other_inner.tools.values() {
let prefixed_tool = tool.with_name_prefix(&prefix);
inner
.tools
.insert(prefixed_tool.name.clone(), Arc::new(prefixed_tool));
}
// Merge resources (no prefix - URIs are already namespaced)
for (uri, resource) in &other_inner.resources {
inner.resources.insert(uri.clone(), resource.clone());
}
// Merge resource templates (no prefix)
for template in &other_inner.resource_templates {
inner.resource_templates.push(template.clone());
}
// Merge prompts (no prefix - could be added in future if needed)
for (name, prompt) in &other_inner.prompts {
inner.prompts.insert(name.clone(), prompt.clone());
}
// Protocol extensions are server-wide declarations and are not
// namespace-prefixed. Nested declarations use last-write-wins.
for (identifier, settings) in &other_inner.protocol_extensions {
inner
.protocol_extensions
.insert(identifier.clone(), settings.clone());
}
self
}
/// Register a completion handler for `completion/complete` requests.
///
/// The handler receives `CompleteParams` containing the reference (prompt or resource)
/// and the argument being completed, and should return completion suggestions.
///
/// # Example
///
/// ```rust
/// use tower_mcp::{McpRouter, CompleteResult};
/// use tower_mcp::protocol::{CompleteParams, CompletionReference};
///
/// let router = McpRouter::new()
/// .completion_handler(|params: CompleteParams| async move {
/// // Provide completions based on the reference and argument
/// match params.reference {
/// CompletionReference::Prompt { name } => {
/// // Return prompt argument completions
/// Ok(CompleteResult::new(vec!["option1".to_string(), "option2".to_string()]))
/// }
/// CompletionReference::Resource { uri } => {
/// // Return resource URI completions
/// Ok(CompleteResult::new(vec![]))
/// }
/// _ => Ok(CompleteResult::new(vec![])),
/// }
/// });
/// ```
pub fn completion_handler<F, Fut>(mut self, handler: F) -> Self
where
F: Fn(CompleteParams) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<CompleteResult>> + Send + 'static,
{
Arc::make_mut(&mut self.inner).completion_handler =
Some(Arc::new(move |params| Box::pin(handler(params))));
self
}
/// Set a filter for tools based on session state.
///
/// The filter determines which tools are visible to each session. Tools that
/// don't pass the filter will not appear in `tools/list` responses and will
/// return an error if called directly.
///
/// # Example
///
/// ```rust
/// use tower_mcp::{McpRouter, ToolBuilder, CallToolResult, CapabilityFilter, Tool, Filterable};
/// use schemars::JsonSchema;
/// use serde::Deserialize;
///
/// #[derive(Debug, Deserialize, JsonSchema)]
/// struct Input { value: String }
///
/// let public_tool = ToolBuilder::new("public")
/// .description("Available to everyone")
/// .handler(|i: Input| async move { Ok(CallToolResult::text(&i.value)) })
/// .build();
///
/// let admin_tool = ToolBuilder::new("admin")
/// .description("Admin only")
/// .handler(|i: Input| async move { Ok(CallToolResult::text(&i.value)) })
/// .build();
///
/// let router = McpRouter::new()
/// .tool(public_tool)
/// .tool(admin_tool)
/// .tool_filter(CapabilityFilter::new(|_session, tool: &Tool| {
/// // In real code, check session.extensions() for auth claims
/// tool.name() != "admin"
/// }));
/// ```
pub fn tool_filter(mut self, filter: ToolFilter) -> Self {
Arc::make_mut(&mut self.inner).tool_filter = Some(filter);
self
}
/// Set a filter for resources based on session state.
///
/// The filter receives the current session state and each resource, returning
/// `true` if the resource should be visible to this session. Resources that
/// don't pass the filter will not appear in `resources/list` responses and will
/// return an error if read directly.
///
/// # Example
///
/// ```rust
/// use tower_mcp::{McpRouter, ResourceBuilder, ReadResourceResult, CapabilityFilter, Resource, Filterable};
///
/// let public_resource = ResourceBuilder::new("file:///public.txt")
/// .name("Public File")
/// .description("Available to everyone")
/// .text("public content");
///
/// let secret_resource = ResourceBuilder::new("file:///secret.txt")
/// .name("Secret File")
/// .description("Admin only")
/// .text("secret content");
///
/// let router = McpRouter::new()
/// .resource(public_resource)
/// .resource(secret_resource)
/// .resource_filter(CapabilityFilter::new(|_session, resource: &Resource| {
/// // In real code, check session.extensions() for auth claims
/// !resource.name().contains("Secret")
/// }));
/// ```
pub fn resource_filter(mut self, filter: ResourceFilter) -> Self {
Arc::make_mut(&mut self.inner).resource_filter = Some(filter);
self
}
/// Set a filter for prompts based on session state.
///
/// The filter receives the current session state and each prompt, returning
/// `true` if the prompt should be visible to this session. Prompts that
/// don't pass the filter will not appear in `prompts/list` responses and will
/// return an error if accessed directly.
///
/// # Example
///
/// ```rust
/// use tower_mcp::{McpRouter, PromptBuilder, CapabilityFilter, Prompt, Filterable};
///
/// let public_prompt = PromptBuilder::new("greeting")
/// .description("A friendly greeting")
/// .user_message("Hello!");
///
/// let admin_prompt = PromptBuilder::new("system_debug")
/// .description("Admin debugging prompt")
/// .user_message("Debug info");
///
/// let router = McpRouter::new()
/// .prompt(public_prompt)
/// .prompt(admin_prompt)
/// .prompt_filter(CapabilityFilter::new(|_session, prompt: &Prompt| {
/// // In real code, check session.extensions() for auth claims
/// !prompt.name().contains("system")
/// }));
/// ```
pub fn prompt_filter(mut self, filter: PromptFilter) -> Self {
Arc::make_mut(&mut self.inner).prompt_filter = Some(filter);
self
}
/// Get access to the session state
pub fn session(&self) -> &SessionState {
&self.session
}
/// Disable a tool by name. Disabled tools are hidden from `tools/list`
/// and return a method-not-found error from `tools/call`, but the tool
/// definition stays attached to the router and can be flipped back on
/// with [`enable_tool`](Self::enable_tool).
///
/// State is shared across all clones produced by
/// [`with_fresh_session`](Self::with_fresh_session), so flipping it once
/// affects every connected session at the next request boundary. Call
/// [`notify_tools_list_changed`](Self::notify_tools_list_changed) to nudge
/// clients to re-fetch.
pub fn disable_tool(&self, name: impl Into<String>) {
let mut set = self.inner.disabled_tools.write().unwrap();
set.insert(name.into());
}
/// Re-enable a previously disabled tool. No-op if the tool was not
/// disabled.
pub fn enable_tool(&self, name: &str) {
let mut set = self.inner.disabled_tools.write().unwrap();
set.remove(name);
}
/// Returns `true` if the named tool is currently enabled (i.e. not in
/// the disabled set). Returns `true` even for unknown tool names; this
/// only reports disable state, not registration.
pub fn is_tool_enabled(&self, name: &str) -> bool {
!self.inner.disabled_tools.read().unwrap().contains(name)
}
/// Disable a resource by URI. Disabled resources are hidden from
/// `resources/list` and return a not-found error from `resources/read`.
pub fn disable_resource(&self, uri: impl Into<String>) {
let mut set = self.inner.disabled_resources.write().unwrap();
set.insert(uri.into());
}
/// Re-enable a previously disabled resource.
pub fn enable_resource(&self, uri: &str) {
let mut set = self.inner.disabled_resources.write().unwrap();
set.remove(uri);
}
/// Returns `true` if the resource at this URI is currently enabled.
pub fn is_resource_enabled(&self, uri: &str) -> bool {
!self.inner.disabled_resources.read().unwrap().contains(uri)
}
/// Disable a prompt by name. Disabled prompts are hidden from
/// `prompts/list` and return a method-not-found error from `prompts/get`.
pub fn disable_prompt(&self, name: impl Into<String>) {
let mut set = self.inner.disabled_prompts.write().unwrap();
set.insert(name.into());
}
/// Re-enable a previously disabled prompt.
pub fn enable_prompt(&self, name: &str) {
let mut set = self.inner.disabled_prompts.write().unwrap();
set.remove(name);
}
/// Returns `true` if the named prompt is currently enabled.
pub fn is_prompt_enabled(&self, name: &str) -> bool {
!self.inner.disabled_prompts.read().unwrap().contains(name)
}
/// Get server capabilities based on registered handlers
/// The server's identity, as configured via `.server_info()` and the
/// related `.server_title()` / `.server_description()` / etc. builders.
///
/// Shared by the `initialize` and `server/discover` handlers, and by the
/// 2026-07-28 stateless HTTP dispatch (SEP-2575's "servers SHOULD
/// identify themselves in each result's `_meta`") since that path calls
/// in from outside this module and has no other way to read identity
/// off a router wrapped behind arbitrary `.layer()` middleware.
pub(crate) fn implementation(&self) -> Implementation {
Implementation {
name: self.inner.server_name.clone(),
version: self.inner.server_version.clone(),
title: self.inner.server_title.clone(),
description: self.inner.server_description.clone(),
icons: self.inner.server_icons.clone(),
website_url: self.inner.server_website_url.clone(),
meta: None,
}
}
/// Return a snapshot of a registered tool's input schema.
///
/// HTTP transport validation uses this before dispatch to enforce
/// SEP-2243 `x-mcp-header` mappings. Static tools take precedence over
/// dynamic tools, matching `tools/list` and `tools/call`.
#[cfg(feature = "http")]
pub(crate) fn tool_input_schema(&self, name: &str) -> Option<serde_json::Value> {
if let Some(tool) = self.inner.tools.get(name) {
return Some(tool.input_schema.clone());
}
#[cfg(feature = "dynamic-tools")]
if let Some(tool) = self
.inner
.dynamic_tools
.as_ref()
.and_then(|tools| tools.get(name))
{
return Some(tool.input_schema.clone());
}
None
}
fn capabilities(&self) -> ServerCapabilities {
let has_resources =
!self.inner.resources.is_empty() || !self.inner.resource_templates.is_empty();
let has_notifications = self.inner.notification_tx.is_some();
// Each of these defaults to `has_notifications`, which is what this
// router has always advertised as soon as a transport attached a
// notification channel. An explicit builder call
// (`tools_list_changed`, `prompts_list_changed`,
// `resources_list_changed`, `mcp_logging`) overrides that default in
// either direction, independently of the channel (#1338).
let tools_list_changed = self
.inner
.advertise_tools_list_changed
.unwrap_or(has_notifications);
let prompts_list_changed = self
.inner
.advertise_prompts_list_changed
.unwrap_or(has_notifications);
let resources_list_changed = self
.inner
.advertise_resources_list_changed
.unwrap_or(has_notifications);
let mcp_logging = self
.inner
.advertise_mcp_logging
.unwrap_or(has_notifications);
#[cfg(feature = "dynamic-tools")]
let has_dynamic_tools = self.inner.dynamic_tools.is_some();
#[cfg(not(feature = "dynamic-tools"))]
let has_dynamic_tools = false;
#[cfg(feature = "dynamic-tools")]
let has_dynamic_prompts = self.inner.dynamic_prompts.is_some();
#[cfg(not(feature = "dynamic-tools"))]
let has_dynamic_prompts = false;
#[cfg(feature = "dynamic-tools")]
let has_dynamic_resources = self.inner.dynamic_resources.is_some()
|| self.inner.dynamic_resource_templates.is_some();
#[cfg(not(feature = "dynamic-tools"))]
let has_dynamic_resources = false;
ServerCapabilities {
tools: if self.inner.tools.is_empty() && !has_dynamic_tools {
None
} else {
Some(ToolsCapability {
list_changed: tools_list_changed,
})
},
resources: if has_resources || has_dynamic_resources {
Some(ResourcesCapability {
subscribe: self.inner.advertise_resource_subscriptions,
list_changed: resources_list_changed,
})
} else {
None
},
prompts: if self.inner.prompts.is_empty() && !has_dynamic_prompts {
None
} else {
Some(PromptsCapability {
list_changed: prompts_list_changed,
})
},
// Advertised when a notification channel is configured, unless
// overridden by `mcp_logging` (#1338).
logging: if mcp_logging {
Some(LoggingCapability {
deprecated: self.inner.logging_deprecated.clone(),
})
} else {
None
},
// Tasks capability is advertised if any tool supports tasks.
// SEP-2663 moves the declaration to `capabilities.extensions`
// under the reverse-DNS key `io.modelcontextprotocol/tasks`; we
// continue to set the legacy top-level `tasks` field for back-compat
// with 2025-11-25 clients that key off it.
tasks: {
let has_task_support = self
.inner
.tools
.values()
.any(|t| !matches!(t.task_support, TaskSupportMode::Forbidden));
if has_task_support {
Some(TasksCapability {
// `list` is intentionally not advertised: final
// SEP-2663 removes `tasks/list` and this router
// answers MethodNotFound for it.
list: None,
cancel: Some(TasksCancelCapability {}),
requests: Some(TasksRequestsCapability {
tools: Some(TasksToolsRequestsCapability {
call: Some(TasksToolsCallCapability {}),
}),
}),
})
} else {
None
}
},
// Completions capability when a handler is registered
completions: if self.inner.completion_handler.is_some() {
Some(CompletionsCapability::default())
} else {
None
},
experimental: None,
extensions: {
let mut map = self.inner.protocol_extensions.clone();
let has_task_support = self
.inner
.tools
.values()
.any(|t| !matches!(t.task_support, TaskSupportMode::Forbidden));
if has_task_support {
map.insert(
tower_mcp_types::protocol::TASKS_EXTENSION_ID.to_string(),
serde_json::json!({}),
);
}
(!map.is_empty()).then_some(map)
},
}
}
/// Return the capability surface appropriate for a protocol version.
///
/// `capabilities.tasks` is the legacy 2025-11-25 shape and is never
/// advertised on the final path. The final extension is advertised only
/// when the server opted in via [`McpRouter::with_tasks`]; merely
/// registering task-capable tools does not advertise it, so a server that
/// has not opted in presents no Tasks surface to a 2026-07-28 client.
fn capabilities_for_protocol(&self, protocol_version: Option<&str>) -> ServerCapabilities {
let mut capabilities = self.capabilities();
if protocol_version == Some(crate::protocol::PROTOCOL_VERSION_2026_07_28) {
capabilities.tasks = None;
// `resources/subscribe` and `resources/unsubscribe` are not part
// of this revision, and the inspector already classifies them as
// unavailable here. Advertising the capability would promise a
// method the same build refuses to route (#1261).
if let Some(resources) = capabilities.resources.as_mut() {
resources.subscribe = false;
}
if !self.final_tasks_enabled()
&& let Some(extensions) = capabilities.extensions.as_mut()
{
extensions.remove(tower_mcp_types::protocol::TASKS_EXTENSION_ID);
if extensions.is_empty() {
capabilities.extensions = None;
}
}
}
capabilities
}
/// Whether this server opted into the final Tasks extension.
///
/// Distinct from the synthesized advertisement in [`Self::capabilities`],
/// which reflects registered tools rather than an explicit choice.
pub(crate) fn final_tasks_enabled(&self) -> bool {
self.inner
.protocol_extensions
.contains_key(tower_mcp_types::protocol::TASKS_EXTENSION_ID)
}
/// Invoke a tool, optionally converting a panic into an error result.
///
/// Enabled by [`McpRouter::catch_panics`] or
/// [`McpRouter::catch_panics_with`]. Without either this is a direct call
/// and a panic unwinds as before, which is the default because a panic is
/// an invariant violation and hiding one is not always a favour.
async fn invoke_tool(
&self,
tool: &crate::tool::Tool,
ctx: RequestContext,
arguments: serde_json::Value,
tool_name: &str,
) -> Result<crate::protocol::RequestOutcome<CallToolResult>> {
let Some(policy) = &self.inner.panic_policy else {
return tool.call_outcome_with_context(ctx, arguments).await;
};
use futures::FutureExt;
// AssertUnwindSafe: the future may hold &mut across the await, which
// Rust cannot prove safe to observe post-unwind. Any state a panicking
// handler leaves behind belongs to that handler; the router's own
// state is not mutated by this call.
let called = std::panic::AssertUnwindSafe(async move {
tool.call_outcome_with_context(ctx, arguments).await
})
.catch_unwind()
.await;
match called {
Ok(outcome) => outcome,
Err(payload) => {
let message = self.handle_caught_panic(policy, tool_name, None, &*payload);
Ok(crate::protocol::RequestOutcome::Complete(
CallToolResult::error(message),
))
}
}
}
/// Apply the selected disclosure policy to a caught handler panic.
///
/// Payload recovery is intentionally conditional: the fully redacted
/// path never downcasts, clones, or formats the panic payload.
fn handle_caught_panic(
&self,
policy: &PanicPolicy,
tool_name: &str,
task_id: Option<&str>,
payload: &(dyn std::any::Any + Send),
) -> String {
let payload = policy.needs_payload().then(|| panic_message(payload));
let logged_tool = policy.log_tool_name.value(tool_name);
let logged_payload = policy
.include_payload_in_logs
.then(|| payload.as_deref().unwrap_or("<redacted>"));
Self::log_caught_panic(logged_tool, logged_payload, task_id);
policy.client_message(tool_name, payload.as_deref())
}
/// Build the JSON-RPC error a transport sends for an internal failure of
/// its own, honouring the configured disclosure policy.
///
/// A transport that hand-builds an error response is outside every path
/// that consults [`PanicPolicy`], so before this existed it sent the
/// error's `Display` text whatever the operator had configured (#1354).
/// Routing the two websocket sites through one helper rather than
/// widening the panic path is what keeps the next transport from
/// reintroducing the gap: the previous round of this, #1335, fixed one of
/// a pair of near-identical sites and left the other to drift.
///
/// With no policy installed the error's text is returned unchanged, which
/// is both the behaviour these paths already had and the stance the crate
/// takes elsewhere: a panic is not caught at all until `catch_panics` asks
/// for it.
///
/// Gated on `websocket` because that is where the two sites are. Widen the
/// gate rather than duplicating the decision when another transport needs
/// it, which is the whole point of it being one helper.
#[cfg(feature = "websocket")]
pub(crate) fn transport_internal_error(&self, error: &dyn std::fmt::Display) -> JsonRpcError {
match &self.inner.panic_policy {
Some(policy) => JsonRpcError::internal_error(policy.internal_error_message(error)),
None => JsonRpcError::internal_error(error.to_string()),
}
}
fn log_caught_panic(tool_name: Option<&str>, payload: Option<&str>, task_id: Option<&str>) {
match (tool_name, payload, task_id) {
(Some(tool_name), Some(payload), Some(task_id)) => tracing::error!(
target: "mcp::tools",
tool = %tool_name,
panic = %payload,
task_id = %task_id,
"tool handler panicked; returning an error result"
),
(Some(tool_name), Some(payload), None) => tracing::error!(
target: "mcp::tools",
tool = %tool_name,
panic = %payload,
"tool handler panicked; returning an error result"
),
(Some(tool_name), None, Some(task_id)) => tracing::error!(
target: "mcp::tools",
tool = %tool_name,
task_id = %task_id,
"tool handler panicked; returning an error result"
),
(Some(tool_name), None, None) => tracing::error!(
target: "mcp::tools",
tool = %tool_name,
"tool handler panicked; returning an error result"
),
(None, Some(payload), Some(task_id)) => tracing::error!(
target: "mcp::tools",
panic = %payload,
task_id = %task_id,
"tool handler panicked; returning an error result"
),
(None, Some(payload), None) => tracing::error!(
target: "mcp::tools",
panic = %payload,
"tool handler panicked; returning an error result"
),
(None, None, Some(task_id)) => tracing::error!(
target: "mcp::tools",
task_id = %task_id,
"tool handler panicked; returning an error result"
),
(None, None, None) => tracing::error!(
target: "mcp::tools",
"tool handler panicked; returning an error result"
),
}
}
/// Effective SEP-2549 cache scope to emit alongside a TTL hint.
///
/// Returns the configured scope, or `private` (the conservative choice)
/// when a TTL is being emitted without an explicit scope. Returns `None`
/// when no TTL is emitted and no scope is configured, so responses
/// without hints stay hint-free.
fn effective_cache_scope(&self, ttl_ms: Option<u64>) -> Option<CacheScope> {
self.inner
.cache_scope
.or_else(|| ttl_ms.map(|_| CacheScope::Private))
}
/// Fill in SEP-2549 caching hints on a resources/read result.
///
/// Handler-set values win; the router-level `read_ttl` and `cache_scope`
/// configuration only fills fields the handler left unset.
fn apply_read_cache_hints(&self, mut result: ReadResourceResult) -> ReadResourceResult {
if result.ttl_ms.is_none() {
result.ttl_ms = self.inner.read_ttl_ms;
}
if result.cache_scope.is_none() {
result.cache_scope = self.effective_cache_scope(result.ttl_ms);
}
result
}
/// Handle an MCP request
async fn handle(
&self,
request_id: RequestId,
request: McpRequest,
extensions: Extensions,
) -> Result<McpResponse> {
// Enforce session state - reject requests before initialization
let method = request.method_name();
if !is_final_protocol_request(&extensions) && !self.session.is_request_allowed(method) {
tracing::warn!(
method = %method,
phase = ?self.session.phase(),
"Request rejected: session not initialized"
);
return Err(Error::JsonRpc(JsonRpcError::invalid_request(format!(
"Session not initialized. Only 'initialize' and 'ping' are allowed before initialization. Got: {}",
method
))));
}
match request {
McpRequest::Initialize(params) => {
tracing::info!(
client = %params.client_info.name,
version = %params.client_info.version,
"Client initializing"
);
// HTTP and other configurable transports inject their exact
// runtime allow-list. Direct router use retains the stable
// default policy.
let protocol_support = extensions.get::<crate::ProtocolSupport>();
let requested_is_legacy = crate::protocol::SUPPORTED_PROTOCOL_VERSIONS
.contains(¶ms.protocol_version.as_str());
let requested_is_supported = requested_is_legacy
&& protocol_support
.is_none_or(|support| support.contains(¶ms.protocol_version));
let protocol_version = if requested_is_supported {
params.protocol_version
} else {
match protocol_support {
None => crate::protocol::LATEST_PROTOCOL_VERSION.to_string(),
Some(support) => support
.versions()
.iter()
.find(|version| {
crate::protocol::SUPPORTED_PROTOCOL_VERSIONS
.contains(&version.as_str())
})
.cloned()
.ok_or_else(|| {
Error::JsonRpc(JsonRpcError::unsupported_protocol_version(
params.protocol_version,
support.versions().iter().map(String::as_str),
))
})?,
}
};
// Transition session state to Initializing
self.session.mark_initializing();
let capabilities = self.capabilities_for_protocol(Some(&protocol_version));
self.session.insert(params.capabilities.clone());
self.session
.insert(crate::NegotiatedExtensions::from_capabilities(
¶ms.capabilities,
&capabilities,
));
Ok(McpResponse::Initialize(InitializeResult {
protocol_version,
capabilities,
server_info: self.implementation(),
instructions: if let Some(config) = &self.inner.auto_instructions {
Some(self.inner.generate_instructions(config))
} else {
self.inner.instructions.clone()
},
meta: None,
}))
}
McpRequest::Discover(_) => {
// SEP-2575 server/discover -- stateless capability advertisement.
// Unlike initialize, this does NOT transition session state and
// does not require a session at all. Returns the same capability
// surface plus the full set of protocol versions we can speak,
// so clients can pick one and signal it via MCP-Protocol-Version
// on subsequent requests.
tracing::debug!("Stateless server/discover request");
let server_info = self.implementation();
let supported_versions = extensions.get::<crate::ProtocolSupport>().map_or_else(
|| {
crate::protocol::SUPPORTED_PROTOCOL_VERSIONS
.iter()
.map(|version| (*version).to_string())
.collect()
},
|support| support.versions().to_vec(),
);
// server/discover is itself the entry point for the final
// stateless lifecycle, so its advertised surface must be safe
// even when this router is invoked directly without transport
// metadata.
let capabilities = self
.capabilities_for_protocol(Some(crate::protocol::PROTOCOL_VERSION_2026_07_28));
Ok(McpResponse::Discover(DiscoverResult {
supported_versions,
capabilities,
ttl_ms: None,
cache_scope: None,
instructions: if let Some(config) = &self.inner.auto_instructions {
Some(self.inner.generate_instructions(config))
} else {
self.inner.instructions.clone()
},
meta: Some(crate::protocol::ResultMeta {
server_info: Some(server_info),
}),
}))
}
McpRequest::ListTools(params) => {
let final_protocol = is_final_protocol_request(&extensions);
let final_tasks_negotiated = final_protocol
&& self.final_tasks_enabled()
&& client_declares_tasks(&extensions);
let filter = self.inner.tool_filter.as_ref();
let disabled = self.inner.disabled_tools.read().unwrap().clone();
let is_visible = |t: &Tool| {
!disabled.contains(&t.name)
&& !(final_protocol
&& matches!(t.task_support, TaskSupportMode::Required)
&& !final_tasks_negotiated)
&& filter
.map(|f| f.is_visible(&self.session, t))
.unwrap_or(true)
};
let definition = |t: &Tool| {
let mut definition = t.definition();
if final_protocol {
definition.execution = None;
}
definition
};
// Collect static tools
let mut tools: Vec<ToolDefinition> = self
.inner
.tools
.values()
.filter(|t| is_visible(t))
.map(|t| definition(t))
.collect();
// Merge dynamic tools (static tools win on name collision)
#[cfg(feature = "dynamic-tools")]
if let Some(ref dynamic) = self.inner.dynamic_tools {
let static_names: HashSet<String> =
tools.iter().map(|t| t.name.clone()).collect();
for t in dynamic.list() {
if !static_names.contains(&t.name) && is_visible(&t) {
tools.push(definition(&t));
}
}
}
tools.sort_by(|a, b| a.name.cmp(&b.name));
let (tools, next_cursor) =
paginate(tools, params.cursor.as_deref(), self.inner.page_size)?;
Ok(McpResponse::ListTools(ListToolsResult {
tools,
next_cursor,
ttl_ms: self.inner.list_ttl_ms,
cache_scope: self.effective_cache_scope(self.inner.list_ttl_ms),
meta: None,
}))
}
McpRequest::CallTool(params) => {
// Disabled tools are reported as if they don't exist.
if self
.inner
.disabled_tools
.read()
.unwrap()
.contains(¶ms.name)
{
tracing::info!(
target: "mcp::tools",
tool = %params.name,
status = "disabled",
"tool call completed"
);
return Err(Error::JsonRpc(JsonRpcError::method_not_found(¶ms.name)));
}
// Look up static tools first, then dynamic
let tool = self.inner.tools.get(¶ms.name).cloned();
#[cfg(feature = "dynamic-tools")]
let tool = tool.or_else(|| {
self.inner
.dynamic_tools
.as_ref()
.and_then(|d| d.get(¶ms.name))
});
let tool = match tool {
Some(t) => t,
None => {
tracing::info!(
target: "mcp::tools",
tool = %params.name,
status = "not_found",
"tool call completed"
);
return Err(Error::JsonRpc(JsonRpcError::method_not_found(¶ms.name)));
}
};
// Check tool filter if configured
if let Some(filter) = &self.inner.tool_filter
&& !filter.is_visible(&self.session, &tool)
{
tracing::info!(
target: "mcp::tools",
tool = %params.name,
status = "denied",
"tool call completed"
);
return Err(filter.denial_error(¶ms.name));
}
// Task creation is client-directed on the legacy protocol and
// server-directed on the final protocol. `Some(None)` means
// create a task using the server-selected TTL.
let final_protocol = is_final_protocol_request(&extensions);
let task_ttl = if final_protocol {
if params.task.is_some() {
return Err(Error::JsonRpc(JsonRpcError::invalid_params(
"The final Tasks extension does not allow a 'task' request parameter",
)));
}
let server_enabled = self.final_tasks_enabled();
let tasks_negotiated = server_enabled && client_declares_tasks(&extensions);
match tool.task_support {
TaskSupportMode::Required if !server_enabled => {
// Match tools/list: a final-only task tool is not
// part of this server's surface until it opts in.
return Err(Error::JsonRpc(JsonRpcError::method_not_found(
¶ms.name,
)));
}
TaskSupportMode::Required if !tasks_negotiated => {
return Err(Error::JsonRpc(
JsonRpcError::missing_required_client_capability(
tasks_client_capabilities(),
),
));
}
TaskSupportMode::Required | TaskSupportMode::Optional
if tasks_negotiated =>
{
Some(None)
}
_ => None,
}
} else {
match (¶ms.task, tool.task_support) {
(Some(_), TaskSupportMode::Forbidden) => {
return Err(Error::JsonRpc(JsonRpcError::invalid_params(format!(
"Tool '{}' does not support async tasks",
params.name
))));
}
(None, TaskSupportMode::Required) => {
return Err(Error::JsonRpc(JsonRpcError::invalid_params(format!(
"Tool '{}' requires async task execution (include 'task' in params)",
params.name
))));
}
(Some(task), _) => Some(task.ttl),
(None, _) => None,
}
};
// Final 2026-07-28 requests declare client capabilities on
// every request. Reject a tool before any handler work begins
// when its declared requirement is not present.
#[cfg(feature = "stateless")]
if let Some(required) = tool.required_client_capabilities()
&& let Some(meta) = extensions.get::<crate::stateless::StatelessRequestMeta>()
&& meta.protocol_version.as_deref()
== Some(crate::protocol::PROTOCOL_VERSION_2026_07_28)
&& !meta
.client_capabilities
.as_ref()
.is_some_and(|actual| client_capabilities_satisfy(actual, required))
{
return Err(Error::JsonRpc(
JsonRpcError::missing_required_client_capability(required.clone()),
));
}
if let Some(task_ttl) = task_ttl {
// Create the task
let (task_id, cancellation_token) = self
.inner
.task_store
.create_task(
¶ms.name,
// A live task is never replayed, so its arguments
// are not needed and are deliberately not
// persisted. That is how a server keeps prompts or
// credentials out of durable task storage (#1246).
if tool.live_handler.is_some() {
serde_json::Value::Null
} else {
params.arguments.clone()
},
task_ttl,
request_principal(&extensions),
)
.await
.map_err(|error| {
self.task_store_error(TaskOperation::Create, None, error)
})?;
tracing::info!(task_id = %task_id, tool = %params.name, "Created async task");
// Create a context for the async task execution
let progress_token = params.meta.and_then(|m| m.progress_token);
let ctx = self.create_context_with_extensions(
request_id,
progress_token,
&extensions,
);
let task_store = self.inner.task_store.clone();
let task_context = crate::tool::TaskContext::new(task_id.clone());
let mut ctx = ctx;
ctx.extensions_mut().insert(task_context.clone());
let preparation = match tool
.prepare_task(task_context, params.arguments.clone())
.await
{
Ok(preparation) => preparation,
Err(error) => {
discard_unprepared_task(&task_store, &task_id).await;
return Err(error);
}
};
if let Some(meta) = preparation.meta {
let value = serde_json::Value::Object(meta);
if let Err(error) = crate::protocol::validate_meta_object(&value) {
discard_unprepared_task(&task_store, &task_id).await;
return Err(Error::invalid_params(format!(
"Invalid task metadata: {error}"
)));
}
let persisted = match task_store.set_task_meta(&task_id, value).await {
Ok(persisted) => persisted,
Err(error) => {
discard_unprepared_task(&task_store, &task_id).await;
return Err(self.task_store_error(
TaskOperation::Create,
Some(&task_id),
error,
));
}
};
if !persisted {
discard_unprepared_task(&task_store, &task_id).await;
return Err(self.task_error(
TaskOperation::Create,
Some(&task_id),
TaskFailure::Internal(
"Task store could not persist preparation metadata",
),
));
}
}
ctx.extensions_mut().merge(&preparation.extensions);
// Spawn the task execution in the background
let tool = tool.clone();
let arguments = params.arguments;
let task_id_clone = task_id.clone();
let tool_name = params.name.clone();
let notifier = self.clone();
tokio::spawn(async move {
// A live handler owns its execution: it parks inside
// its own future rather than returning, so it is never
// replayed and nothing else writes its terminal state
// (#1246).
if let Some(live_handler) = tool.live_handler.clone() {
let handle = std::sync::Arc::new(crate::tool::LiveTask {
store: task_store.clone(),
error_policy: notifier.inner.task_error_policy.clone(),
input_ready: tokio::sync::Notify::new(),
cancelled: crate::context::CancellationToken::new(),
});
// Register before inspecting the store token, not
// after. A `tasks/cancel` landing between the two
// used to find no live handle, take the store path,
// terminalize, and acknowledge, after which the
// handle was registered uncancelled and the handler
// ran on against an already-cancelled task (#1294).
//
// In this order a cancel before registration is
// caught by the check below, and one after it
// signals the handle directly. There is no ordering
// left where cancellation selects the store path
// while live execution is running and cannot see it.
notifier.register_live_task(&task_id_clone, handle.clone());
// Released on drop, so the entry goes whether the
// handler returns, panics, or is dropped (#1305).
let registration = LiveTaskRegistration {
router: notifier.clone(),
task_id: task_id_clone.clone(),
};
if cancellation_token.is_cancelled() {
handle.cancelled.cancel();
}
let live_ctx =
crate::tool::TaskContext::with_live(task_id_clone.clone(), handle);
let start = std::time::Instant::now();
// The replay paths get their panic boundary from
// `invoke_tool`; the live branch calls the handler
// directly and had none, so a panic unwound before
// any terminal state was written and left the task
// at `working` forever (#1305).
let outcome = if let Some(policy) = ¬ifier.inner.panic_policy {
use futures::FutureExt;
let called = std::panic::AssertUnwindSafe(async move {
live_handler.call(ctx, live_ctx, arguments).await
})
.catch_unwind()
.await;
match called {
Ok(outcome) => outcome,
Err(payload) => {
let message = notifier.handle_caught_panic(
policy,
&tool_name,
Some(&task_id_clone),
&*payload,
);
// A panic is an execution failure, not
// a tool reporting a domain error, so
// it fails the task rather than
// completing it with `isError`.
Ok(crate::tool::TaskOutcome::Failed(
JsonRpcError::internal_error(message),
))
}
}
} else {
live_handler.call(ctx, live_ctx, arguments).await
};
let duration_ms = start.elapsed().as_secs_f64() * 1000.0;
let applied = match outcome {
Ok(crate::tool::TaskOutcome::Completed(result)) => notifier
.complete_task_or_fail(&task_id_clone, result)
.await
.then_some("completed"),
Ok(crate::tool::TaskOutcome::Failed(error)) => notifier
.record_task_failure(&task_id_clone, error)
.await
.then_some("failed"),
Ok(crate::tool::TaskOutcome::Cancelled { message }) => notifier
.record_task_cancellation(&task_id_clone, message.as_deref())
.await
.then_some("cancelled"),
// Propagating the cancellation error is the
// ordinary way a live handler unwinds, so it
// ends the task cancelled rather than failed.
Err(crate::error::Error::TaskCancelled) => notifier
.record_task_cancellation(
&task_id_clone,
Some("handler observed cancellation"),
)
.await
.then_some("cancelled"),
// An unclassified error is an execution
// failure the handler declined to describe.
Err(Error::JsonRpc(error)) => notifier
.record_task_failure(&task_id_clone, error)
.await
.then_some("failed"),
Err(_error) => {
tracing::warn!(
task_id = %task_id_clone,
"live task handler returned an unclassified error"
);
let error = notifier.task_json_rpc_error(
TaskOperation::Execute,
Some(&task_id_clone),
TaskFailure::Handler,
);
notifier
.record_task_failure(&task_id_clone, error)
.await
.then_some("failed")
}
};
// The terminal write must win before unregistering
// (#1294), but the dead handle must not remain
// visible through logging or notification awaits.
// If the write failed, a later cancellation can
// now take the store path instead of signalling a
// handler that has already returned (#1305).
drop(registration);
match applied {
Some(status) => tracing::info!(
target: "mcp::tools",
tool = %tool_name,
task_id = %task_id_clone,
duration_ms,
status,
"live task finished"
),
None => tracing::warn!(
task_id = %task_id_clone,
"failed to record live task outcome"
),
}
notifier.notify_task_state(&task_id_clone).await;
return;
}
// Check for cancellation before starting
if cancellation_token.is_cancelled() {
tracing::debug!(task_id = %task_id_clone, "Task cancelled before execution");
notifier.notify_task_state(&task_id_clone).await;
return;
}
// Execute the tool.
//
// The outcome-aware call preserves an input-required
// return, which parks the task until the client
// answers with `tasks/update` and the router resumes
// it (#1208).
let start = std::time::Instant::now();
let outcome = notifier
.invoke_tool(&tool, ctx, arguments, &tool_name)
.await;
let duration_ms = start.elapsed().as_secs_f64() * 1000.0;
let result = match outcome {
Ok(crate::protocol::RequestOutcome::Complete(result)) => result,
Ok(crate::protocol::RequestOutcome::InputRequired(input_required)) => {
notifier
.park_task_for_input(&task_id_clone, input_required)
.await;
return;
}
// Preserved from the previous call path: a handler
// error becomes an `isError` result, which
// completes the task rather than failing it.
Err(error) => CallToolResult::error(error.to_string()),
};
if cancellation_token.is_cancelled() {
tracing::debug!(task_id = %task_id_clone, "Task cancelled during execution");
notifier.notify_task_state(&task_id_clone).await;
} else {
// A tool result carrying `isError: true` completes
// the task: the tool ran and produced a domain
// error. SEP-2663 reserves `failed` for execution
// failures, which surface as a JSON-RPC error.
let status = if result.is_error { "error" } else { "success" };
let error_msg = result
.is_error
.then(|| result.first_text().unwrap_or("Tool execution failed"))
.map(str::to_string);
if notifier.complete_task_or_fail(&task_id_clone, result).await {
tracing::info!(
target: "mcp::tools",
tool = %tool_name,
task_id = %task_id_clone,
duration_ms,
status,
error = error_msg.as_deref().unwrap_or_default(),
"tool call completed"
);
}
notifier.notify_task_state(&task_id_clone).await;
}
});
let task = self
.inner
.task_store
.get_task(&task_id)
.await
.map_err(|error| {
self.task_store_error(TaskOperation::Create, Some(&task_id), error)
})?
.ok_or_else(|| {
self.task_error(
TaskOperation::Create,
Some(&task_id),
TaskFailure::Internal("Failed to retrieve created task"),
)
})?;
// The final wire is flat with `resultType: "task"`; the
// legacy shape nests a `task` compatibility mirror. Pick
// by protocol version rather than emitting a hybrid.
if is_final_protocol_request(&extensions) {
let mut metadata = crate::tasks::TaskMetadata::new(
task.task_id.clone(),
task.created_at.clone(),
task.last_updated_at.clone(),
task.ttl,
);
metadata.status_message = task.status_message.clone();
metadata.poll_interval_ms = task.poll_interval;
let mut result = crate::tasks::CreateTaskResult::new(
crate::tasks::Task::new(metadata, task.status),
);
result.meta = task.meta.and_then(|value| value.as_object().cloned());
return Ok(McpResponse::FinalCreateTask(result));
}
Ok(McpResponse::CreateTask(CreateTaskResult::new(task)))
} else {
// Extract progress token from request metadata
let progress_token = params.meta.and_then(|m| m.progress_token);
let ctx = self.create_context_with_extensions(
request_id,
progress_token,
&extensions,
);
#[cfg(feature = "stateless")]
let ctx = {
let mut ctx = ctx;
ctx.extensions_mut().insert(crate::mrtr::MrtrRequest::new(
params.input_responses,
params.request_state,
));
ctx
};
let start = std::time::Instant::now();
let outcome = self
.invoke_tool(&tool, ctx, params.arguments, ¶ms.name)
.await?;
let duration_ms = start.elapsed().as_secs_f64() * 1000.0;
match outcome {
RequestOutcome::Complete(result) => {
let status = if result.is_error { "error" } else { "success" };
tracing::info!(
target: "mcp::tools",
tool = %params.name,
duration_ms,
status,
"tool call completed"
);
Ok(McpResponse::CallTool(result))
}
RequestOutcome::InputRequired(result) => {
#[cfg(feature = "stateless")]
{
validate_input_required_result(&extensions, &result)?;
tracing::info!(
target: "mcp::tools",
tool = %params.name,
duration_ms,
status = "input_required",
"tool call requires client input"
);
Ok(McpResponse::InputRequired(result))
}
#[cfg(not(feature = "stateless"))]
{
let _ = result;
Err(Error::invalid_params(
"InputRequiredResult support was not compiled",
))
}
}
}
}
}
McpRequest::ListResources(params) => {
let disabled = self.inner.disabled_resources.read().unwrap().clone();
let is_visible = |r: &Resource| -> bool {
!disabled.contains(&r.uri)
&& self
.inner
.resource_filter
.as_ref()
.map(|f| f.is_visible(&self.session, r))
.unwrap_or(true)
};
let mut resources: Vec<ResourceDefinition> = self
.inner
.resources
.values()
.filter(|r| is_visible(r))
.map(|r| r.definition())
.collect();
// Merge dynamic resources (static resources win on URI collision)
#[cfg(feature = "dynamic-tools")]
if let Some(ref dynamic) = self.inner.dynamic_resources {
let static_uris: HashSet<String> =
resources.iter().map(|r| r.uri.clone()).collect();
for r in dynamic.list() {
if !static_uris.contains(&r.uri) && is_visible(&r) {
resources.push(r.definition());
}
}
}
resources.sort_by(|a, b| a.uri.cmp(&b.uri));
let (resources, next_cursor) =
paginate(resources, params.cursor.as_deref(), self.inner.page_size)?;
Ok(McpResponse::ListResources(ListResourcesResult {
resources,
next_cursor,
ttl_ms: self.inner.list_ttl_ms,
cache_scope: self.effective_cache_scope(self.inner.list_ttl_ms),
meta: None,
}))
}
McpRequest::ListResourceTemplates(params) => {
let mut resource_templates: Vec<ResourceTemplateDefinition> = self
.inner
.resource_templates
.iter()
.map(|t| t.definition())
.collect();
// Merge dynamic resource templates (static win on collision)
#[cfg(feature = "dynamic-tools")]
if let Some(ref dynamic) = self.inner.dynamic_resource_templates {
let static_patterns: HashSet<String> = resource_templates
.iter()
.map(|t| t.uri_template.clone())
.collect();
for t in dynamic.list() {
if !static_patterns.contains(&t.uri_template) {
resource_templates.push(t.definition());
}
}
}
resource_templates.sort_by(|a, b| a.uri_template.cmp(&b.uri_template));
let (resource_templates, next_cursor) = paginate(
resource_templates,
params.cursor.as_deref(),
self.inner.page_size,
)?;
Ok(McpResponse::ListResourceTemplates(
ListResourceTemplatesResult {
resource_templates,
next_cursor,
ttl_ms: self.inner.list_ttl_ms,
cache_scope: self.effective_cache_scope(self.inner.list_ttl_ms),
meta: None,
},
))
}
McpRequest::ReadResource(params) => {
// Disabled resources are reported as if they don't exist.
if self
.inner
.disabled_resources
.read()
.unwrap()
.contains(¶ms.uri)
{
return Err(Error::JsonRpc(JsonRpcError::resource_not_found(
¶ms.uri,
)));
}
// First, try to find a static resource
if let Some(resource) = self.inner.resources.get(¶ms.uri) {
// Check resource filter if configured
if let Some(filter) = &self.inner.resource_filter
&& !filter.is_visible(&self.session, resource)
{
return Err(filter.denial_error(¶ms.uri));
}
tracing::debug!(uri = %params.uri, "Reading static resource");
let ctx = self.create_context_with_extensions(request_id, None, &extensions);
#[cfg(feature = "stateless")]
let ctx = {
let mut ctx = ctx;
ctx.extensions_mut().insert(crate::mrtr::MrtrRequest::new(
params.input_responses.clone(),
params.request_state.clone(),
));
ctx
};
return match resource.read_outcome_with_context(ctx).await? {
RequestOutcome::Complete(result) => Ok(McpResponse::ReadResource(
self.apply_read_cache_hints(result),
)),
RequestOutcome::InputRequired(result) => {
#[cfg(feature = "stateless")]
{
validate_input_required_result(&extensions, &result)?;
Ok(McpResponse::InputRequired(result))
}
#[cfg(not(feature = "stateless"))]
{
let _ = result;
Err(Error::invalid_params(
"InputRequiredResult support was not compiled",
))
}
}
};
}
// Try dynamic resources
#[cfg(feature = "dynamic-tools")]
#[allow(clippy::collapsible_if)]
if let Some(ref dynamic) = self.inner.dynamic_resources {
if let Some(resource) = dynamic.get(¶ms.uri) {
if let Some(filter) = &self.inner.resource_filter
&& !filter.is_visible(&self.session, &resource)
{
return Err(filter.denial_error(¶ms.uri));
}
tracing::debug!(uri = %params.uri, "Reading dynamic resource");
let ctx =
self.create_context_with_extensions(request_id, None, &extensions);
#[cfg(feature = "stateless")]
let ctx = {
let mut ctx = ctx;
ctx.extensions_mut().insert(crate::mrtr::MrtrRequest::new(
params.input_responses.clone(),
params.request_state.clone(),
));
ctx
};
return match resource.read_outcome_with_context(ctx).await? {
RequestOutcome::Complete(result) => Ok(McpResponse::ReadResource(
self.apply_read_cache_hints(result),
)),
RequestOutcome::InputRequired(result) => {
#[cfg(feature = "stateless")]
{
validate_input_required_result(&extensions, &result)?;
Ok(McpResponse::InputRequired(result))
}
#[cfg(not(feature = "stateless"))]
{
let _ = result;
Err(Error::invalid_params(
"InputRequiredResult support was not compiled",
))
}
}
};
}
}
// Try static templates
for template in &self.inner.resource_templates {
if let Some(variables) = template.match_uri(¶ms.uri) {
tracing::debug!(
uri = %params.uri,
template = %template.uri_template,
"Reading resource via template"
);
let ctx =
self.create_context_with_extensions(request_id, None, &extensions);
#[cfg(feature = "stateless")]
let ctx = {
let mut ctx = ctx;
ctx.extensions_mut().insert(crate::mrtr::MrtrRequest::new(
params.input_responses.clone(),
params.request_state.clone(),
));
ctx
};
return match template
.read_outcome_with_context(ctx, ¶ms.uri, variables)
.await?
{
RequestOutcome::Complete(result) => Ok(McpResponse::ReadResource(
self.apply_read_cache_hints(result),
)),
RequestOutcome::InputRequired(result) => {
#[cfg(feature = "stateless")]
{
validate_input_required_result(&extensions, &result)?;
Ok(McpResponse::InputRequired(result))
}
#[cfg(not(feature = "stateless"))]
{
let _ = result;
Err(Error::invalid_params(
"InputRequiredResult support was not compiled",
))
}
}
};
}
}
// Try dynamic templates
#[cfg(feature = "dynamic-tools")]
#[allow(clippy::collapsible_if)]
if let Some(ref dynamic) = self.inner.dynamic_resource_templates {
if let Some((template, variables)) = dynamic.match_uri(¶ms.uri) {
tracing::debug!(
uri = %params.uri,
template = %template.uri_template,
"Reading resource via dynamic template"
);
let ctx =
self.create_context_with_extensions(request_id, None, &extensions);
#[cfg(feature = "stateless")]
let ctx = {
let mut ctx = ctx;
ctx.extensions_mut().insert(crate::mrtr::MrtrRequest::new(
params.input_responses.clone(),
params.request_state.clone(),
));
ctx
};
return match template
.read_outcome_with_context(ctx, ¶ms.uri, variables)
.await?
{
RequestOutcome::Complete(result) => Ok(McpResponse::ReadResource(
self.apply_read_cache_hints(result),
)),
RequestOutcome::InputRequired(result) => {
#[cfg(feature = "stateless")]
{
validate_input_required_result(&extensions, &result)?;
Ok(McpResponse::InputRequired(result))
}
#[cfg(not(feature = "stateless"))]
{
let _ = result;
Err(Error::invalid_params(
"InputRequiredResult support was not compiled",
))
}
}
};
}
}
// No match found
Err(Error::JsonRpc(JsonRpcError::resource_not_found(
¶ms.uri,
)))
}
McpRequest::SubscribeResource(params) => {
// Verify the resource exists
if !self.inner.resources.contains_key(¶ms.uri) {
return Err(Error::JsonRpc(JsonRpcError::resource_not_found(
¶ms.uri,
)));
}
tracing::debug!(uri = %params.uri, "Subscribing to resource");
self.subscribe(¶ms.uri);
Ok(McpResponse::SubscribeResource(EmptyResult {}))
}
McpRequest::UnsubscribeResource(params) => {
// Verify the resource exists
if !self.inner.resources.contains_key(¶ms.uri) {
return Err(Error::JsonRpc(JsonRpcError::resource_not_found(
¶ms.uri,
)));
}
tracing::debug!(uri = %params.uri, "Unsubscribing from resource");
self.unsubscribe(¶ms.uri);
Ok(McpResponse::UnsubscribeResource(EmptyResult {}))
}
McpRequest::ListPrompts(params) => {
#[cfg(feature = "dynamic-tools")]
if let Some(initializer) = &self.inner.prompt_initializer {
initializer()?;
}
let disabled = self.inner.disabled_prompts.read().unwrap().clone();
let is_visible = |p: &Prompt| -> bool {
!disabled.contains(&p.name)
&& self
.inner
.prompt_filter
.as_ref()
.map(|f| f.is_visible(&self.session, p))
.unwrap_or(true)
};
let mut prompts: Vec<PromptDefinition> = self
.inner
.prompts
.values()
.filter(|p| is_visible(p))
.map(|p| p.definition())
.collect();
// Merge dynamic prompts (static prompts win on name collision)
#[cfg(feature = "dynamic-tools")]
if let Some(ref dynamic) = self.inner.dynamic_prompts {
let static_names: HashSet<String> =
prompts.iter().map(|p| p.name.clone()).collect();
for p in dynamic.list() {
if !static_names.contains(&p.name) && is_visible(&p) {
prompts.push(p.definition());
}
}
}
prompts.sort_by(|a, b| a.name.cmp(&b.name));
let (prompts, next_cursor) =
paginate(prompts, params.cursor.as_deref(), self.inner.page_size)?;
Ok(McpResponse::ListPrompts(ListPromptsResult {
prompts,
next_cursor,
ttl_ms: self.inner.list_ttl_ms,
cache_scope: self.effective_cache_scope(self.inner.list_ttl_ms),
meta: None,
}))
}
McpRequest::GetPrompt(params) => {
#[cfg(feature = "dynamic-tools")]
if let Some(initializer) = &self.inner.prompt_initializer {
initializer()?;
}
// Disabled prompts are reported as if they don't exist.
if self
.inner
.disabled_prompts
.read()
.unwrap()
.contains(¶ms.name)
{
return Err(Error::JsonRpc(JsonRpcError::method_not_found(&format!(
"Prompt not found: {}",
params.name
))));
}
// Look up static prompts first, then dynamic
let prompt = self.inner.prompts.get(¶ms.name).cloned();
#[cfg(feature = "dynamic-tools")]
let prompt = prompt.or_else(|| {
self.inner
.dynamic_prompts
.as_ref()
.and_then(|d| d.get(¶ms.name))
});
let prompt = prompt.ok_or_else(|| {
Error::JsonRpc(JsonRpcError::method_not_found(&format!(
"Prompt not found: {}",
params.name
)))
})?;
// Check prompt filter if configured
if let Some(filter) = &self.inner.prompt_filter
&& !filter.is_visible(&self.session, &prompt)
{
return Err(filter.denial_error(¶ms.name));
}
// Before dispatch, so every path shares one check: layered and
// unlayered, ordinary and MRTR. A handler never sees a request
// missing an argument it declared required (#1281).
let missing =
crate::prompt::missing_required_arguments(&prompt.arguments, ¶ms.arguments);
if !missing.is_empty() {
return Err(Error::JsonRpc(crate::prompt::missing_arguments_error(
¶ms.name,
&missing,
)));
}
tracing::debug!(name = %params.name, "Getting prompt");
let ctx = self.create_context_with_extensions(request_id, None, &extensions);
#[cfg(feature = "stateless")]
let ctx = {
let mut ctx = ctx;
ctx.extensions_mut().insert(crate::mrtr::MrtrRequest::new(
params.input_responses,
params.request_state,
));
ctx
};
let outcome = prompt
.get_outcome_with_context(ctx, params.arguments)
.await?;
match outcome {
RequestOutcome::Complete(result) => Ok(McpResponse::GetPrompt(result)),
RequestOutcome::InputRequired(result) => {
#[cfg(feature = "stateless")]
{
validate_input_required_result(&extensions, &result)?;
Ok(McpResponse::InputRequired(result))
}
#[cfg(not(feature = "stateless"))]
{
let _ = result;
Err(Error::invalid_params(
"InputRequiredResult support was not compiled",
))
}
}
}
}
McpRequest::Ping => Ok(McpResponse::Pong(EmptyResult {})),
McpRequest::GetTaskInfo(params) => {
if is_final_protocol_request(&extensions) {
self.require_negotiated_tasks(&extensions, "tasks/get")?;
self.authorize_task(TaskOperation::Get, ¶ms.task_id, &extensions)
.await?;
return self.final_get_task(¶ms.task_id, &extensions).await;
}
self.authorize_task(TaskOperation::Get, ¶ms.task_id, &extensions)
.await?;
// SEP-2663 DetailedTask: `tasks/get` carries the
// status-discriminated payload inline. `completed` includes
// the result the synchronous request would have returned;
// `failed` includes the JSON-RPC error. This replaced the
// removed blocking `tasks/result` method as the way clients
// retrieve a task's outcome.
let Some((mut task, result, error)) = self
.inner
.task_store
.get_task_result(¶ms.task_id)
.await
.map_err(|error| {
self.task_store_error(TaskOperation::Get, Some(¶ms.task_id), error)
})?
else {
// Present when it was authorized, absent now, so it
// expired in between (#1249).
return Err(self
.classify_absent_task(TaskOperation::Get, ¶ms.task_id, &extensions)
.await);
};
match task.status {
TaskStatus::Completed => task.result = result,
TaskStatus::Failed => {
// The store preserves the structured error, so the
// original code and data survive to the client instead
// of being flattened into an internal-error message.
task.error = Some(
error.unwrap_or_else(|| JsonRpcError::internal_error("Task failed")),
);
}
_ => {}
}
Ok(McpResponse::GetTaskInfo(task))
}
McpRequest::UpdateTask(params) => {
if is_final_protocol_request(&extensions) {
self.require_negotiated_tasks(&extensions, "tasks/update")?;
self.authorize_task(TaskOperation::Update, ¶ms.task_id, &extensions)
.await?;
// Partial responses are the normal case: the store
// consumes what matches an outstanding request and ignores
// unknown, already-answered, and superseded keys.
let Some(applied) = self
.inner
.task_store
.apply_input_responses(
¶ms.task_id,
decode_input_responses(self, ¶ms.task_id, ¶ms.input_responses)?,
)
.await
.map_err(|error| {
self.task_store_error(
TaskOperation::Update,
Some(¶ms.task_id),
error,
)
})?
else {
// Nothing left to apply. A task the store still knows
// and has not expired is a late or duplicate update,
// so it gets the ordinary empty acknowledgement, which
// makes a client retry idempotent (#1249).
let presence = self
.task_presence(TaskOperation::Update, ¶ms.task_id)
.await?;
return match presence {
crate::async_task::TaskPresence::Present { .. } => Ok(
McpResponse::FinalTaskAck(crate::tasks::TaskAcknowledgement::new()),
),
absent => Err(self.classify_absent_presence(
TaskOperation::Update,
¶ms.task_id,
&extensions,
absent,
)),
};
};
// Answering the last outstanding request resumes the task,
// so the status a subscriber sees changes here even though
// the ack itself is empty.
self.notify_task_state(¶ms.task_id).await;
// The client answered everything outstanding, so re-invoke
// the handler with the accumulated responses (#1208). A
// partial answer leaves the task parked for the rest.
//
// `is_complete` is also true when nothing was outstanding
// in the first place, so on its own it would resume a task
// that never parked. Requiring this update to have answered
// something is what distinguishes a real
// `input_required -> working` transition from a stray,
// duplicate, or already-satisfied update, either of which
// would otherwise start a second handler alongside the one
// still running (#1246).
if !applied.accepted.is_empty() && applied.is_complete() {
// A live handler is parked inside its own future and
// must be woken, not replayed. Waking only after the
// store has committed is what guarantees it cannot
// observe an answer that was not recorded (#1246).
if !self.wake_live_task(¶ms.task_id) {
self.resume_task(¶ms.task_id).await;
}
}
return Ok(McpResponse::FinalTaskAck(
crate::tasks::TaskAcknowledgement::new(),
));
}
self.authorize_task(TaskOperation::Update, ¶ms.task_id, &extensions)
.await?;
// Input responses reach the store on this path exactly as they
// do on the final path above. The spec allowance for ignoring
// `inputResponses` covers keys that are not outstanding, not
// every key, so dropping them wholesale left a server whose
// store models input requests with a working flow on
// 2026-07-28 and a silent stall on 2025-11-25 (#1188).
let Some(applied) = self
.inner
.task_store
.apply_input_responses(
¶ms.task_id,
decode_input_responses(self, ¶ms.task_id, ¶ms.input_responses)?,
)
.await
.map_err(|error| {
self.task_store_error(TaskOperation::Update, Some(¶ms.task_id), error)
})?
else {
// Nothing left to apply. A task the store still knows and
// has not expired is a late or duplicate update, so it
// gets the ordinary empty acknowledgement, which makes a
// client retry idempotent rather than a not-found (#1249).
let presence = self
.task_presence(TaskOperation::Update, ¶ms.task_id)
.await?;
return match presence {
crate::async_task::TaskPresence::Present { .. } => {
Ok(McpResponse::UpdateTask(EmptyResult {}))
}
absent => Err(self.classify_absent_presence(
TaskOperation::Update,
¶ms.task_id,
&extensions,
absent,
)),
};
};
// A final-protocol subscriber watching this task should see it
// resume regardless of which lifecycle the updating client
// used. Self-guards when the extension is not enabled.
self.notify_task_state(¶ms.task_id).await;
// A live task parks inside its own future, so answering its
// input on this lifecycle has to wake it just as the final
// path does, or it waits forever (#1246). Waking only after
// the store has committed is what guarantees the handler
// cannot observe an unrecorded answer.
if !applied.accepted.is_empty() && applied.is_complete() {
self.wake_live_task(¶ms.task_id);
}
Ok(McpResponse::UpdateTask(EmptyResult {}))
}
McpRequest::CancelTask(params) => {
if is_final_protocol_request(&extensions) {
self.require_negotiated_tasks(&extensions, "tasks/cancel")?;
self.authorize_task(TaskOperation::Cancel, ¶ms.task_id, &extensions)
.await?;
// A live task is signalled and left non-terminal: its
// handler owns the teardown and reports when it actually
// stopped, so completion can still legitimately win the
// race. SEP-2663 describes cancellation as eventually
// consistent, which is exactly this (#1246).
if self.signal_live_cancellation(¶ms.task_id) {
self.notify_task_state(¶ms.task_id).await;
return Ok(McpResponse::FinalTaskAck(
crate::tasks::TaskAcknowledgement::new(),
));
}
// The final ack does not require a terminal transition:
// cancelling an already-terminal task is acknowledged, and
// the observable status is polled via `tasks/get`.
let cancelled = self
.inner
.task_store
.cancel_task(¶ms.task_id, params.reason.as_deref())
.await
.map_err(|error| {
self.task_store_error(
TaskOperation::Cancel,
Some(¶ms.task_id),
error,
)
})?;
if cancelled.is_none() {
return Err(self
.classify_absent_task(
TaskOperation::Cancel,
¶ms.task_id,
&extensions,
)
.await);
}
self.notify_task_state(¶ms.task_id).await;
return Ok(McpResponse::FinalTaskAck(
crate::tasks::TaskAcknowledgement::new(),
));
}
self.authorize_task(TaskOperation::Cancel, ¶ms.task_id, &extensions)
.await?;
// Same reasoning as the final path: a live task owns its own
// teardown, so it is signalled and left non-terminal (#1246).
if self.signal_live_cancellation(¶ms.task_id) {
self.notify_task_state(¶ms.task_id).await;
return Ok(McpResponse::CancelTask(EmptyResult {}));
}
// First check if the task exists and is not already terminal
let Some(current) = self
.inner
.task_store
.get_task(¶ms.task_id)
.await
.map_err(|error| {
self.task_store_error(TaskOperation::Cancel, Some(¶ms.task_id), error)
})?
else {
return Err(self
.classify_absent_task(TaskOperation::Cancel, ¶ms.task_id, &extensions)
.await);
};
if current.status.is_terminal() {
return Err(Error::JsonRpc(JsonRpcError::invalid_params(format!(
"Task {} is already in terminal state: {}",
params.task_id, current.status
))));
}
let cancelled = self
.inner
.task_store
.cancel_task(¶ms.task_id, params.reason.as_deref())
.await
.map_err(|error| {
self.task_store_error(TaskOperation::Cancel, Some(¶ms.task_id), error)
})?;
if cancelled.is_none() {
return Err(self
.classify_absent_task(TaskOperation::Cancel, ¶ms.task_id, &extensions)
.await);
}
// SEP-2663 (final): the cancel acknowledgment MUST be an empty
// result. The observable status is polled via `tasks/get` and
// may remain non-terminal after this ack.
Ok(McpResponse::CancelTask(EmptyResult {}))
}
McpRequest::SetLoggingLevel(params) => {
tracing::debug!(level = ?params.level, "Client set logging level");
if let Ok(mut level) = self.inner.min_log_level.write() {
*level = params.level;
}
Ok(McpResponse::SetLoggingLevel(EmptyResult {}))
}
McpRequest::Complete(params) => {
tracing::debug!(
reference = ?params.reference,
argument = %params.argument.name,
"Completion request"
);
// Delegate to registered completion handler if available
if let Some(ref handler) = self.inner.completion_handler {
let result = handler(params).await?;
Ok(McpResponse::Complete(result))
} else {
// No completion handler registered, return empty completions
Ok(McpResponse::Complete(CompleteResult::new(vec![])))
}
}
#[cfg(feature = "stateless")]
McpRequest::SubscriptionsListen(params) => {
// The stream itself is transport-owned: transports dispatch
// the request here before upgrading the connection, so
// `Service<RouterRequest>` middleware observes accepted and
// rejected listens and the validation lives in one place
// (#1182). The response is consumed by the transport, never
// written to the wire.
if !is_final_protocol_request(&extensions) {
// A legacy peer gets exactly what the old catch-all
// produced for this method.
return Err(Error::JsonRpc(JsonRpcError::method_not_found(
"subscriptions/listen",
)));
}
let Some(requested) = params.notifications else {
return Err(Error::JsonRpc(JsonRpcError::invalid_params(
"subscriptions/listen requires a notifications filter",
)));
};
// SEP-2663: task status notifications require the declared
// extension, the same answer the three task methods give.
if requested.task_ids.is_some() && !client_declares_tasks(&extensions) {
return Err(Error::JsonRpc(
JsonRpcError::missing_required_client_capability(
tasks_client_capabilities(),
),
));
}
let notifications = crate::transport::subscriptions::accepted_subscription_filter(
requested,
self.final_tasks_enabled(),
);
Ok(McpResponse::SubscriptionsAccepted(
crate::protocol::SubscriptionsAcceptedResult { notifications },
))
}
McpRequest::Unknown { method, .. } => {
Err(Error::JsonRpc(JsonRpcError::method_not_found(&method)))
}
_ => Err(Error::JsonRpc(JsonRpcError::method_not_found(
"unknown method",
))),
}
}
/// Handle an MCP notification (no response expected)
pub fn handle_notification(&self, notification: McpNotification) {
match notification {
McpNotification::Initialized => {
let phase_before = self.session.phase();
if self.session.mark_initialized() {
if phase_before == crate::session::SessionPhase::Uninitialized {
tracing::info!(
"Session initialized from uninitialized state (race resolved)"
);
} else {
tracing::info!("Session initialized, entering operation phase");
}
} else if phase_before == crate::session::SessionPhase::Uninitialized {
tracing::warn!(
"Ignoring initialized notification: no initialize request has been \
received for this session"
);
} else {
tracing::warn!(
phase = ?self.session.phase(),
"Received initialized notification in unexpected state"
);
}
}
McpNotification::Cancelled(params) => {
if let Some(ref request_id) = params.request_id {
if self.cancel_request(request_id) {
tracing::info!(
request_id = ?request_id,
reason = ?params.reason,
"Request cancelled"
);
} else {
tracing::debug!(
request_id = ?request_id,
reason = ?params.reason,
"Cancellation requested for unknown request"
);
}
} else {
tracing::debug!(
reason = ?params.reason,
"Cancellation notification received without request_id"
);
}
}
McpNotification::Progress(params) => {
tracing::trace!(
token = ?params.progress_token,
progress = params.progress,
total = ?params.total,
"Progress notification"
);
// Client-to-server progress notifications are unusual but
// valid through 2025-11-25. The final 2026-07-28 schema
// removes ProgressNotification from ClientNotification
// entirely -- clients no longer send this. Notifications are
// fire-and-forget with no response to reject with, so an
// off-spec one arriving here is simply logged and ignored
// rather than rejected, regardless of negotiated version.
}
McpNotification::RootsListChanged => {
tracing::info!("Client roots list changed");
// Server should re-request roots if needed
// This is handled by the application layer
}
McpNotification::Unknown { method, .. } => {
tracing::debug!(method = %method, "Unknown notification received");
}
_ => {
tracing::debug!("Unrecognized notification variant received");
}
}
}
}
impl Default for McpRouter {
fn default() -> Self {
Self::new()
}
}
// =============================================================================
// Tower Service implementation
// =============================================================================
// Re-export Extensions from context for backwards compatibility
pub use crate::context::Extensions;
/// A map of tool names to their annotations, for use by middleware.
///
/// This is automatically inserted into [`RouterRequest::extensions`] for
/// `tools/call` requests, allowing middleware to inspect tool safety hints
/// (e.g., `read_only_hint`, `destructive_hint`) without needing direct
/// access to the router's tool registry.
///
/// # Example
///
/// ```rust,ignore
/// use tower_mcp::router::ToolAnnotationsMap;
/// use tower_mcp::protocol::McpRequest;
///
/// // In a middleware Service::call():
/// fn call(&mut self, req: RouterRequest) -> Self::Future {
/// if let McpRequest::CallTool(params) = &req.inner {
/// if let Some(map) = req.extensions.get::<ToolAnnotationsMap>() {
/// let annotations = map.get(¶ms.name);
/// // Check annotations.read_only_hint, destructive_hint, etc.
/// }
/// }
/// self.inner.call(req)
/// }
/// ```
#[derive(Debug, Clone)]
pub struct ToolAnnotationsMap {
map: Arc<HashMap<String, ToolAnnotations>>,
}
impl ToolAnnotationsMap {
/// Look up annotations for a tool by name.
///
/// Returns `None` if the tool has no annotations or doesn't exist.
pub fn get(&self, tool_name: &str) -> Option<&ToolAnnotations> {
self.map.get(tool_name)
}
/// Check if a tool is read-only (does not modify state).
///
/// Returns `false` if the tool has no annotations or doesn't exist
/// (the MCP spec default for `readOnlyHint` is `false`).
pub fn is_read_only(&self, tool_name: &str) -> bool {
self.map.get(tool_name).is_some_and(|a| a.read_only_hint)
}
/// Check if a tool may have destructive effects.
///
/// Returns `true` if the tool has no annotations or doesn't exist
/// (the MCP spec default for `destructiveHint` is `true`).
pub fn is_destructive(&self, tool_name: &str) -> bool {
self.map.get(tool_name).is_none_or(|a| a.destructive_hint)
}
/// Check if a tool is idempotent.
///
/// Returns `false` if the tool has no annotations or doesn't exist
/// (the MCP spec default for `idempotentHint` is `false`).
pub fn is_idempotent(&self, tool_name: &str) -> bool {
self.map.get(tool_name).is_some_and(|a| a.idempotent_hint)
}
}
/// Request type for the tower Service implementation.
///
/// # Preserving extensions in middleware
///
/// When rewriting a request in middleware, use [`with_inner`](Self::with_inner)
/// or [`clone_with_inner`](Self::clone_with_inner) instead of constructing a
/// new `RouterRequest` directly. Constructing with `Extensions::new()` will
/// silently drop extensions set by earlier middleware layers (token claims,
/// RBAC context, etc.).
///
/// ```rust,ignore
/// // WRONG: drops extensions from earlier middleware
/// let rewritten = RouterRequest {
/// id: req.id.clone(),
/// inner: new_inner,
/// extensions: Extensions::new(),
/// };
///
/// // RIGHT: preserves extensions
/// let rewritten = req.with_inner(new_inner);
/// ```
#[derive(Debug, Clone)]
pub struct RouterRequest {
/// The JSON-RPC request ID.
pub id: RequestId,
/// The parsed MCP request.
pub inner: McpRequest,
/// Type-map for passing data (e.g., `TokenClaims`) through middleware.
pub extensions: Extensions,
}
impl RouterRequest {
/// Create a new `RouterRequest` with empty extensions.
pub fn new(id: RequestId, inner: McpRequest) -> Self {
Self {
id,
inner,
extensions: Extensions::new(),
}
}
/// Replace the inner MCP request, preserving the id and extensions.
///
/// This is the recommended way to rewrite requests in middleware,
/// as it ensures extensions set by earlier middleware layers
/// (e.g., token claims, RBAC context) are not lost.
pub fn with_inner(self, inner: McpRequest) -> Self {
Self {
id: self.id,
inner,
extensions: self.extensions,
}
}
/// Replace both the id and inner MCP request, preserving extensions.
///
/// Useful when middleware needs to assign a new request id
/// (e.g., for fan-out or request duplication) while keeping
/// the extensions from the original request.
pub fn with_id_and_inner(self, id: RequestId, inner: McpRequest) -> Self {
Self {
id,
inner,
extensions: self.extensions,
}
}
/// Create a copy of this request with a different inner request,
/// cloning the id and extensions from the original.
///
/// Unlike [`with_inner`](Self::with_inner), this borrows `self`,
/// which is useful when the original request is still needed
/// (e.g., for traffic mirroring where you send the request to
/// two backends).
pub fn clone_with_inner(&self, inner: McpRequest) -> Self {
Self {
id: self.id.clone(),
inner,
extensions: self.extensions.clone(),
}
}
}
/// Response type for the tower Service implementation
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RouterResponse {
/// The JSON-RPC request ID this response corresponds to.
pub id: RequestId,
/// The MCP response or JSON-RPC error.
pub inner: std::result::Result<McpResponse, JsonRpcError>,
}
impl RouterResponse {
/// Returns `true` if the response contains a JSON-RPC error.
///
/// Since tower-mcp services use `Error = Infallible` (errors are carried
/// inside the response, not in the `Result`), this method is useful for
/// middleware that needs to inspect whether a request failed -- for example,
/// retry or circuit breaker middleware.
///
/// # Example
///
/// ```rust,ignore
/// // Response-based retry predicate for tower-resilience or similar
/// fn is_retriable(response: &RouterResponse) -> bool {
/// response.is_error()
/// }
/// ```
pub fn is_error(&self) -> bool {
self.inner.is_err()
}
/// Convert to JSON-RPC response
pub fn into_jsonrpc(self) -> JsonRpcResponse {
match self.inner {
Ok(response) => match serde_json::to_value(response) {
Ok(result) => JsonRpcResponse::result(self.id, result),
Err(e) => {
tracing::error!(error = %e, "Failed to serialize response");
JsonRpcResponse::error(
Some(self.id),
JsonRpcError::internal_error(format!("Serialization error: {}", e)),
)
}
},
Err(error) => JsonRpcResponse::error(Some(self.id), error),
}
}
}
/// Identifies one dispatch of one request, unique for a router's lifetime.
///
/// The request id cannot play this role: a client may reuse one that is still
/// in flight, and two requests sharing an id must still be tracked separately
/// (#1270). Minted by [`Service::call`] and passed to the handler through the
/// request extensions so the registration and the guard name the same entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct DispatchId(u64);
/// One tracked dispatch in the router's in-flight registry.
struct InFlightDispatch {
dispatch: DispatchId,
token: CancellationToken,
}
/// Untracks a single dispatch when the request future ends, however it ends.
///
/// Removal used to sit on the success path in [`Service::call`], so a future
/// dropped before that point (a timeout layer firing, an HTTP client
/// disconnecting, a handler unwinding) left its entry in the registry for the
/// process lifetime. `Drop` runs on every one of those paths.
struct InFlightGuard {
router: McpRouter,
request_id: RequestId,
dispatch: DispatchId,
}
impl Drop for InFlightGuard {
fn drop(&mut self) {
self.router
.complete_dispatch(&self.request_id, self.dispatch);
}
}
impl Service<RouterRequest> for McpRouter {
type Response = RouterResponse;
type Error = std::convert::Infallible; // Errors are in the response
type Future =
Pin<Box<dyn Future<Output = std::result::Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<std::result::Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, mut req: RouterRequest) -> Self::Future {
let router = self.clone();
let request_id = req.id.clone();
// Name the dispatch before `handle` builds its context, so the
// registration inside and the guard out here refer to the same entry.
let dispatch = router.next_dispatch();
req.extensions.insert(dispatch);
Box::pin(async move {
let _tracked = InFlightGuard {
router: router.clone(),
request_id: request_id.clone(),
dispatch,
};
let result = router.handle(req.id, req.inner, req.extensions).await;
Ok(RouterResponse {
id: request_id,
// Map tower-mcp errors to JSON-RPC errors: a structured
// Error::JsonRpc is forwarded as-is (preserves the original
// code and message); everything else is sanitized to
// -32603 (Internal Error). See Error::into_json_rpc_error.
inner: result.map_err(Error::into_json_rpc_error),
})
})
}
}
mod notify;
mod task_ops;
use task_ops::{
client_declares_tasks, decode_input_responses, discard_unprepared_task,
tasks_client_capabilities,
};
// Gated in `task_ops` too, so importing it unconditionally breaks the default
// build that `--all-features` never exercises.
#[cfg(feature = "stateless")]
use task_ops::validate_input_required_result;
#[cfg(test)]
mod tests;
#[cfg(all(test, feature = "stateless"))]
mod task_error_tests;
#[cfg(test)]
mod cursor_property_tests;