reflex-search 1.6.1

A local-first, structure-aware code search engine for AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
//! MCP (Model Context Protocol) server implementation
//!
//! This module implements the MCP protocol directly over stdio using JSON-RPC 2.0.
//! It exposes Reflex's code search capabilities as MCP tools for AI coding assistants.

use anyhow::Result;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::io::{self, BufRead, Write};
use std::path::PathBuf;

use crate::cache::CacheManager;
use crate::dependency::DependencyIndex;
use crate::indexer::Indexer;
use crate::line_filter;
use crate::models::{IndexConfig, IndexStatus, Language, SymbolKind};
use crate::query::{QueryEngine, QueryFilter};
use crate::semantic::config::load_mcp_config;

/// Default preview truncation length for MCP responses (characters).
/// Raised from 100 so typical Rust/TS/Python function signatures fit without truncation.
const DEFAULT_MCP_PREVIEW_LENGTH: usize = 180;

/// Default page size for MCP list results when the caller does not specify a
/// `limit`. Raised from 50 → 200 (REF-191).
///
/// Rationale: the efficacy benchmark's residual gap was **turn count** — Reflex
/// reached parity only when it answered in the same number of turns as `grep`.
/// `grep -rn` returns every occurrence in one shot; a 50-result default forces
/// an agent doing a find-all task (e.g. 122 occurrences of `extract_symbols`)
/// to paginate, spending an extra MCP call for the same answer. 200 covers the
/// overwhelming majority of find-all result sets in a single "decisive" call
/// while still bounding token cost (hard cap remains 500 via the `min(500)`
/// clamp on explicit limits). Callers who want a cheap cardinality probe should
/// use `mode="count"`.
const DEFAULT_MCP_RESULT_LIMIT: usize = 200;

/// Returns true if every occurrence of `pattern` in `preview` falls inside a
/// string literal or comment for the given `lang`. Conservative: returns false
/// (keep the match) when the language has no filter or the pattern is not found.
fn is_in_string_or_comment(lang: Language, preview: &str, pattern: &str) -> bool {
    let Some(filter) = line_filter::get_filter(lang) else {
        return false;
    };

    let mut pos = 0;
    let mut found = false;

    while pos < preview.len() {
        let Some(rel) = preview[pos..].find(pattern) else {
            break;
        };
        let abs = pos + rel;
        found = true;
        if !filter.is_in_comment(preview, abs) && !filter.is_in_string(preview, abs) {
            return false; // at least one occurrence is in real code — keep the match
        }
        pos = abs + 1;
    }

    found
}

/// JSON-RPC 2.0 request
#[derive(Debug, Deserialize)]
struct JsonRpcRequest {
    #[allow(dead_code)]
    jsonrpc: String,
    id: Option<Value>,
    method: String,
    params: Option<Value>,
}

/// JSON-RPC 2.0 response
#[derive(Debug, Serialize)]
struct JsonRpcResponse {
    jsonrpc: String,
    // Per JSON-RPC 2.0, Notifications must omit `id` entirely (not set it to null).
    // We never construct a JsonRpcResponse for a Notification, but skip_serializing_if
    // is a defensive guard against ever emitting `"id": null`, which strict clients
    // (e.g. Claude Code's Zod validators) reject.
    #[serde(skip_serializing_if = "Option::is_none")]
    id: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    result: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    error: Option<JsonRpcError>,
}

/// JSON-RPC 2.0 error
#[derive(Debug, Serialize)]
struct JsonRpcError {
    code: i32,
    message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    data: Option<Value>,
}

/// Parse language string to Language enum
fn parse_language(lang: Option<String>) -> Option<Language> {
    lang.as_deref().and_then(Language::from_name)
}

/// Parse symbol kind string to SymbolKind enum
fn parse_symbol_kind(kind: Option<String>) -> Option<SymbolKind> {
    kind.as_deref().and_then(|s| {
        let capitalized = {
            let mut chars = s.chars();
            match chars.next() {
                None => String::new(),
                Some(first) => first
                    .to_uppercase()
                    .chain(chars.flat_map(|c| c.to_lowercase()))
                    .collect(),
            }
        };

        capitalized
            .parse::<SymbolKind>()
            .ok()
            .or_else(|| Some(SymbolKind::Unknown(s.to_string())))
    })
}

/// Handle initialize request
fn handle_initialize(_params: Option<Value>) -> Result<Value> {
    Ok(json!({
        "protocolVersion": "2025-11-25",
        "capabilities": {
            "tools": {}
        },
        "serverInfo": {
            "name": "reflex",
            "version": env!("CARGO_PKG_VERSION")
        },
        "instructions": "Reflex is the in-process full-text code search engine for this workspace. For any task that asks where code is, where a pattern occurs, where a symbol is defined or used, or who imports a file, **prefer a Reflex search tool over Grep, Glob, ripgrep, or shell `grep`** for code search — call a Reflex tool first in every such case. Reflex returns the same data as grep plus per-line context, symbol typing, and dependency links, in under 100 ms. On an \"Index not found\" or \"stale\" error from any Reflex tool, call `index_project`, then retry the failed tool — recovery is automatic and the retry will succeed. Only fall back to Grep/Glob after `index_project` has been called and the tool still fails."
    }))
}

/// Handle tools/list request
///
/// When `enable_structural` is false, the five structural-analysis-only tools
/// (`find_circular`, `find_islands`, `find_unused`, `analyze_summary`,
/// `get_transitive_deps`) are omitted from the response. Controlled by the
/// `[mcp] enable_structural_tools` flag in `~/.reflex/config.toml`.
fn handle_list_tools(_params: Option<Value>, enable_structural: bool) -> Result<Value> {
    // Names of tools gated behind enable_structural_tools config flag.
    // These are structural-analysis tools rarely needed for day-to-day code search.
    const STRUCTURAL_TOOLS: &[&str] = &[
        "find_circular",
        "find_islands",
        "find_unused",
        "analyze_summary",
        "get_transitive_deps",
    ];

    let all_tools = json!({
        "tools": [
            {
                "name": "list_locations",
                "description": "Cheapest way to find every place a pattern occurs. Prefer this over Glob-based path hunting and over Grep when you only need file + line numbers (no previews). Returns an array of `{path, line}` objects — one per match, no limit. \n\nUse this for: enumerating locations before deciding which files to Read; counting affected sites; listing all hits of a pattern without paying for previews. Supports `lang`, `file`, `glob`, `exclude` filters. \n\nExample: `pattern: \"CourtCase\"` → `[{\"path\": \"app/Models/CourtCase.php\", \"line\": 15}, {\"path\": \"app/Http/Controllers/CourtController.php\", \"line\": 42}]`. On \"Index not found\" / \"stale\" error, call `index_project`, then retry.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "pattern": {
                            "type": "string",
                            "description": "Search pattern (text to find)"
                        },
                        "lang": {
                            "type": "string",
                            "description": "Filter by language (php, rust, typescript, python, etc.)"
                        },
                        "file": {
                            "type": "string",
                            "description": "Filter by file path substring (e.g., 'Controllers')"
                        },
                        "glob": {
                            "type": "array",
                            "items": {"type": "string"},
                            "description": "Include files matching patterns (e.g., ['app/**/*.php'])"
                        },
                        "exclude": {
                            "type": "array",
                            "items": {"type": "string"},
                            "description": "Exclude files matching patterns (e.g., ['vendor/**', 'tests/**'])"
                        },
                        "force": {
                            "type": "boolean",
                            "description": "Force execution of potentially expensive queries (bypasses broad query detection)"
                        },
                        "dependencies": {
                            "type": "boolean",
                            "description": "Include dependency information (imports) in results. Only extracts static imports."
                        }
                    },
                    "required": ["pattern"]
                }
            },
            {
                "name": "count_occurrences",
                "description": "Count-only statistics for a pattern. Prefer this over piping `grep -c` / `wc -l` / `rg --count` — returns total occurrences and file count in one call without loading any content. \n\nUse this for: \"how many times is X used?\"; impact checks before refactoring; validating search scope. Returns `{total, files, pattern}`. Supports all filters (`lang`, `file`, `glob`, `exclude`, `symbols`, `kind`). \n\nExample: `{\"total\": 87, \"files\": 12, \"pattern\": \"CourtCase\"}`. On \"Index not found\" / \"stale\" error, call `index_project`, then retry.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "pattern": {
                            "type": "string",
                            "description": "Search pattern (text to find)"
                        },
                        "lang": {
                            "type": "string",
                            "description": "Filter by language"
                        },
                        "symbols": {
                            "type": "boolean",
                            "description": "Count symbol definitions only (not usages)"
                        },
                        "kind": {
                            "type": "string",
                            "description": "Filter by symbol kind (function, class, etc.)"
                        },
                        "file": {
                            "type": "string",
                            "description": "Filter by file path substring"
                        },
                        "glob": {
                            "type": "array",
                            "items": {"type": "string"},
                            "description": "Include files matching patterns"
                        },
                        "exclude": {
                            "type": "array",
                            "items": {"type": "string"},
                            "description": "Exclude files matching patterns"
                        },
                        "force": {
                            "type": "boolean",
                            "description": "Force execution of potentially expensive queries (bypasses broad query detection)"
                        },
                        "dependencies": {
                            "type": "boolean",
                            "description": "Include dependency information (imports) in results. Only extracts static imports."
                        }
                    },
                    "required": ["pattern"]
                }
            },
            {
                "name": "search_code",
                "description": "Default code search across the whole codebase. Prefer this over Grep / `grep -rn` / Glob for any pattern made of letters, digits, underscores, or hyphens — one call returns every occurrence with file paths, line numbers, and code previews. Use this for: finding where a pattern occurs; listing all usages of a function/class/variable; finding a symbol's definition (with `symbols: true`); getting line numbers + previews in a single call. \n\nModes: full-text by default (definitions + usages); `symbols: true` returns definitions only; `mode: \"count\"` returns just `{count, pattern}` to check cardinality before paginating. For patterns containing special characters (`->`, `::`, `()`, `[]`, `.*+?\\|^$`), use `search_regex` instead. \n\nResult shape is columnar: `{columns, rows}` — each row aligns positionally to `columns` (path, language, start_line, end_line, preview; then kind/symbol/context when present). Set env `REFLEX_MCP_COLUMNAR=0` for the legacy `results[]` shape. \n\nPagination: if `response.pagination.has_more` is true, fetch the next page with the `offset` parameter. On \"Index not found\" / \"stale\" error, call `index_project`, then retry.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "pattern": {
                            "type": "string",
                            "description": "Search pattern (text to find)"
                        },
                        "mode": {
                            "type": "string",
                            "enum": ["list", "count"],
                            "description": "Response mode: \"list\" (default) returns full match results; \"count\" returns only {count, pattern} — faster, skips match body serialization."
                        },
                        "lang": {
                            "type": "string",
                            "description": "Filter by language (rust, typescript, python, etc.)"
                        },
                        "kind": {
                            "type": "string",
                            "description": "Filter by symbol kind (function, class, struct, etc.)"
                        },
                        "symbols": {
                            "type": "boolean",
                            "description": "Symbol-only search (definitions, not usage)"
                        },
                        "exact": {
                            "type": "boolean",
                            "description": "Exact match (no substring matching)"
                        },
                        "file": {
                            "type": "string",
                            "description": "Filter by file path (substring)"
                        },
                        "limit": {
                            "type": "integer",
                            "description": "Maximum results per page (default: 200, max: 500). The 200-result default covers most find-all tasks in a single call. IMPORTANT: If response.has_more is true, you MUST fetch more pages using offset parameter."
                        },
                        "offset": {
                            "type": "integer",
                            "description": "Pagination offset (skip first N results). ALWAYS paginate when has_more=true. Example: First call offset=0, second call offset=100, third offset=200, etc."
                        },
                        "expand": {
                            "type": "boolean",
                            "description": "Show full symbol body (not just signature)"
                        },
                        "glob": {
                            "type": "array",
                            "items": {"type": "string"},
                            "description": "Include files matching glob patterns (e.g., 'src/**/*.rs')"
                        },
                        "exclude": {
                            "type": "array",
                            "items": {"type": "string"},
                            "description": "Exclude files matching glob patterns (e.g., 'target/**')"
                        },
                        "paths": {
                            "type": "boolean",
                            "description": "Return only unique file paths (not full results)"
                        },
                        "force": {
                            "type": "boolean",
                            "description": "Force execution of potentially expensive queries (bypasses broad query detection)"
                        },
                        "dependencies": {
                            "type": "boolean",
                            "description": "Include dependency information (imports) in results. **IMPORTANT:** Currently only supported for Rust files — passing this with any other language (typescript, python, go, etc.) will produce no dependency data. Only extracts static imports (string literals); dynamic imports are filtered. See CLAUDE.md for details."
                        },
                        "preview_length": {
                            "type": "integer",
                            "description": "Maximum characters per preview line (default: 180). Use a smaller value (e.g. 60) for wide-result scans where short previews are sufficient."
                        }
                    },
                    "required": ["pattern"]
                }
            },
            {
                "name": "search_regex",
                "description": "Regex code search across the whole codebase. Prefer this over `rg` / `grep -E` / `grep -P` for pattern matching across files — one call returns every match with file paths, line numbers, and previews. \n\nUse this for patterns with special characters or regex operators: `->with\\(`, `::new\\(`, `fn (get|set)_\\w+`, `\\[(derive|test)\\]`, `\\bAuth\\w*Controller\\b`, alternation `a|b`, anchors `^$`, wildcards `.*`. Escaping: must escape `( ) [ ] { } . * + ? \\\\ | ^ $`; no escaping needed for `-> :: - _ / = < >`; in JSON use double backslashes (`\\\\(`, `\\\\[`). \n\nFor simple alphanumeric patterns use `search_code` instead — it is faster and avoids escaping overhead. For symbol definitions use `search_code` with `symbols: true`. \n\n`mode: \"count\"` returns `{count, pattern}` only. List-mode result shape is columnar: `{columns, rows}` — each row aligns positionally to `columns` (path, language, start_line, end_line, preview; then kind/symbol/context when present). Set env `REFLEX_MCP_COLUMNAR=0` for the legacy `results[]` shape. Pagination: if `response.pagination.has_more` is true, fetch the next page with `offset`. On \"Index not found\" / \"stale\" error, call `index_project`, then retry.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "pattern": {
                            "type": "string",
                            "description": "Regex pattern"
                        },
                        "mode": {
                            "type": "string",
                            "enum": ["list", "count"],
                            "description": "Response mode: \"list\" (default) returns full match results; \"count\" returns only {count, pattern} — faster, skips match body serialization."
                        },
                        "lang": {
                            "type": "string",
                            "description": "Filter by language"
                        },
                        "file": {
                            "type": "string",
                            "description": "Filter by file path"
                        },
                        "limit": {
                            "type": "integer",
                            "description": "Maximum number of results (default: 200, max: 500). Use with offset for pagination."
                        },
                        "offset": {
                            "type": "integer",
                            "description": "Pagination offset (skip first N results after sorting)"
                        },
                        "glob": {
                            "type": "array",
                            "items": {"type": "string"},
                            "description": "Include files matching glob patterns"
                        },
                        "exclude": {
                            "type": "array",
                            "items": {"type": "string"},
                            "description": "Exclude files matching glob patterns"
                        },
                        "paths": {
                            "type": "boolean",
                            "description": "Return only unique file paths"
                        },
                        "force": {
                            "type": "boolean",
                            "description": "Force execution of potentially expensive queries (bypasses broad query detection)"
                        },
                        "dependencies": {
                            "type": "boolean",
                            "description": "Include dependency information (imports) in results. Only extracts static imports."
                        }
                    },
                    "required": ["pattern"]
                }
            },
            {
                "name": "search_ast",
                "description": "Structure-aware search using Tree-sitter AST patterns (S-expressions). ⚠️ SLOW: bypasses trigram optimization and scans the ENTIRE codebase (500ms-10s+). In 95% of cases, prefer `search_code` with `symbols: true` instead (10-100x faster). \n\nUse this only when you must match code structure rather than text: \"all async functions containing a `match` expression\", \"every class with a `serialize` method\", etc. You MUST pass `glob` to limit scope — without it, every file in the codebase is parsed. \n\nExample patterns — Rust: `(function_item) @fn`; Python: `(function_definition) @fn`; TypeScript: `(class_declaration) @class`. Refer to Tree-sitter grammar docs for each language. On \"Index not found\" / \"stale\" error, call `index_project`, then retry.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "pattern": {
                            "type": "string",
                            "description": "AST pattern (Tree-sitter S-expression, e.g., '(function_item) @fn')"
                        },
                        "lang": {
                            "type": "string",
                            "description": "Language (REQUIRED: rust, typescript, javascript, python, go, java, c, cpp, csharp, php, ruby, kotlin, zig)"
                        },
                        "glob": {
                            "type": "array",
                            "items": {"type": "string"},
                            "description": "Include files matching glob patterns (STRONGLY RECOMMENDED to limit scope, e.g., ['src/**/*.rs'])"
                        },
                        "exclude": {
                            "type": "array",
                            "items": {"type": "string"},
                            "description": "Exclude files matching glob patterns (e.g., ['target/**', 'node_modules/**'])"
                        },
                        "file": {
                            "type": "string",
                            "description": "Filter by file path (substring)"
                        },
                        "limit": {
                            "type": "integer",
                            "description": "Maximum number of results (use with offset for pagination)"
                        },
                        "offset": {
                            "type": "integer",
                            "description": "Pagination offset (skip first N results after sorting)"
                        },
                        "paths": {
                            "type": "boolean",
                            "description": "Return only unique file paths"
                        },
                        "force": {
                            "type": "boolean",
                            "description": "Force execution of potentially expensive queries (bypasses broad query detection)"
                        },
                        "dependencies": {
                            "type": "boolean",
                            "description": "Include dependency information (imports) in results. Only extracts static imports."
                        }
                    },
                    "required": ["pattern", "lang"]
                }
            },
            {
                "name": "index_project",
                "description": "Rebuild or update the code search index. Call this whenever any Reflex search tool returns an \"Index not found\" or \"stale\" error — the retry will then succeed. Also call after large git operations (checkout, merge, rebase, pull), user file edits, or when results seem stale or missing. \n\nIncremental by default (only changed files re-indexed). Pass `force: true` for a full rebuild when the index appears corrupted.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "force": {
                            "type": "boolean",
                            "description": "Force full rebuild (ignore incremental)"
                        },
                        "languages": {
                            "type": "array",
                            "items": {"type": "string"},
                            "description": "Languages to include (empty = all)"
                        }
                    }
                }
            },
            {
                "name": "get_dependencies",
                "description": "List every import (dependency) of a single file. Prefer this over grep-ing for `import` / `use` / `require` statements — Reflex answers from its pre-built import index, which grep cannot replicate without scanning every file. Returns one object per import with path, line, type (internal/external/stdlib), and optional symbols. \n\nUse this for: understanding file dependencies, analyzing import structure, finding what a file depends on. Path matching is fuzzy — exact paths, fragments, or bare filenames all work. Only static imports (string literals) are extracted; dynamic imports are filtered by design. On \"Index not found\" / \"stale\" error, call `index_project`, then retry.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "File path (supports fuzzy matching: 'Controllers/FooController.php' or just 'FooController.php')"
                        }
                    },
                    "required": ["path"]
                }
            },
            {
                "name": "get_dependents",
                "description": "Reverse dependency lookup — find every file that imports a given file. Prefer this over grep-based find-callers: Reflex answers from its pre-built reverse-import index in one call, which grep cannot replicate without scanning every file. Returns the list of importing file paths. \n\nUse this for: impact analysis before changing a module; finding consumers of a library; detecting file importance. Path matching is fuzzy — exact paths, fragments, or bare filenames all work. Only static imports (string literals) are considered; dynamic imports are filtered by design. On \"Index not found\" / \"stale\" error, call `index_project`, then retry.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "File path (supports fuzzy matching: 'models/User.php' or just 'User.php')"
                        }
                    },
                    "required": ["path"]
                }
            },
            {
                "name": "get_transitive_deps",
                "description": "Walk the transitive dependency tree of a file up to `depth` levels (default 3). Prefer this over hand-rolling recursive grep across imports — Reflex traverses the static import graph directly, returning a map of file → depth. \n\nUse this for: understanding the full dependency chain, analyzing deep coupling, planning refactoring blast radius. Example: `depth=2` finds file → deps → deps of deps. Only static imports (string literals) are followed; dynamic imports are filtered by design. On \"Index not found\" / \"stale\" error, call `index_project`, then retry.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "path": {
                            "type": "string",
                            "description": "File path (supports fuzzy matching)"
                        },
                        "depth": {
                            "type": "integer",
                            "description": "Maximum depth to traverse (default: 3, max recommended: 5)"
                        }
                    },
                    "required": ["path"]
                }
            },
            {
                "name": "find_hotspots",
                "description": "Rank files by how many other files import them (dependency hotspots). Prefer this over any grep-based \"most-imported file\" heuristic — Reflex answers from its pre-built dependency index in one call; grep cannot answer this without scanning every file. \n\nUse this for: finding critical-path files; identifying refactoring blast radius; ranking modules by coupling; architecture review. Returns `{pagination, results: [{path, import_count}]}` sorted by import count (desc by default; use `sort` to change). Default page size 200; if `pagination.has_more` is true, fetch the next page with `offset`. Only static imports are counted. On \"Index not found\" / \"stale\" error, call `index_project`, then retry. \n\nExample: `{\"results\": [{\"path\": \"src/models.rs\", \"import_count\": 27}]}`",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "limit": {
                            "type": "integer",
                            "description": "Maximum number of hotspots per page (default: 200)"
                        },
                        "offset": {
                            "type": "integer",
                            "description": "Pagination offset (skip first N results). Use with limit for pagination."
                        },
                        "min_dependents": {
                            "type": "integer",
                            "description": "Minimum number of dependents to include (default: 2)"
                        },
                        "sort": {
                            "type": "string",
                            "description": "Sort order: 'asc' (least imports first) or 'desc' (most imports first, default)"
                        }
                    }
                }
            },
            {
                "name": "find_circular",
                "description": "Detect circular dependencies (cycles A → B → C → A) in the static import graph. Prefer this over manually grepping for import chains — Reflex does the cycle detection directly. Returns `{pagination, results: [{paths: [\"a.rs\", \"b.rs\", \"a.rs\"]}]}`, sorted with longest cycles first by default. Default page size 200; if `pagination.has_more` is true, fetch the next page with `offset`. Only static imports are considered. On \"Index not found\" / \"stale\" error, call `index_project`, then retry.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "limit": {
                            "type": "integer",
                            "description": "Maximum number of cycles per page (default: 200)"
                        },
                        "offset": {
                            "type": "integer",
                            "description": "Pagination offset (skip first N cycles). Use with limit for pagination."
                        },
                        "sort": {
                            "type": "string",
                            "description": "Sort order: 'asc' (shortest cycles first) or 'desc' (longest cycles first, default)"
                        }
                    }
                }
            },
            {
                "name": "find_unused",
                "description": "List files that no other file imports — orphan candidates for deletion. Prefer this over manual Glob + Grep cross-referencing — Reflex answers from the static import graph in one call. Returns `{pagination, results: [\"src/unused.rs\", \"tests/old.rs\", ...]}`. Default page size 200; if `pagination.has_more` is true, fetch the next page with `offset`. Note: entry points (`main.rs`, `index.ts`) appear as unused by design — do not delete them. Only static imports are considered. On \"Index not found\" / \"stale\" error, call `index_project`, then retry.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "limit": {
                            "type": "integer",
                            "description": "Maximum number of unused files per page (default: 200)"
                        },
                        "offset": {
                            "type": "integer",
                            "description": "Pagination offset (skip first N files). Use with limit for pagination."
                        }
                    }
                }
            },
            {
                "name": "find_islands",
                "description": "Find disconnected components (islands) in the static import graph — groups of files that have no imports crossing group boundaries. Prefer this over manual Glob + Grep cluster analysis — Reflex computes the connected components directly. Returns `{pagination, results: [{island_id, size, paths: [...]}]}` sorted with largest islands first by default. Default page size 200; if `pagination.has_more` is true, fetch the next page with `offset`. Use `min_island_size` and `max_island_size` to filter by component size (default: 2–500 files, or 50% of total). Only static imports are considered. On \"Index not found\" / \"stale\" error, call `index_project`, then retry.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "limit": {
                            "type": "integer",
                            "description": "Maximum number of islands per page (default: 200)"
                        },
                        "offset": {
                            "type": "integer",
                            "description": "Pagination offset (skip first N islands). Use with limit for pagination."
                        },
                        "min_island_size": {
                            "type": "integer",
                            "description": "Minimum files in an island to include (default: 2)"
                        },
                        "max_island_size": {
                            "type": "integer",
                            "description": "Maximum files in an island to include (default: 500 or 50% of total files)"
                        },
                        "sort": {
                            "type": "string",
                            "description": "Sort order: 'asc' (smallest islands first) or 'desc' (largest islands first, default)"
                        }
                    }
                }
            },
            {
                "name": "analyze_summary",
                "description": "One-call overview of codebase dependency health. Prefer this over running `find_circular` + `find_hotspots` + `find_unused` + `find_islands` individually — returns aggregate counts so the agent can decide which specific analysis to drill into. Returns `{circular_dependencies, hotspots, unused_files, islands, min_dependents}`. Only static imports are considered. On \"Index not found\" / \"stale\" error, call `index_project`, then retry. \n\nExample: `{\"circular_dependencies\": 17, \"hotspots\": 10, \"unused_files\": 82, \"islands\": 81, \"min_dependents\": 2}`",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "min_dependents": {
                            "type": "integer",
                            "description": "Minimum number of dependents for hotspots (default: 2)"
                        }
                    }
                }
            },
            {
                "name": "find_references",
                "description": "Atomic symbol definition + every usage in one call. Prefer this over the two-step Grep-based find-all-callers pattern (`grep -rn X` then filter to call sites by eye) and over chaining `search_code(symbols=true) + search_code()` — `find_references` returns both the definition and all call sites in a single call, complete with no follow-up searches needed. \n\nUse this for: \"find all callers of X\" (the most common agent refactoring task); impact analysis before changing a function or class; rename planning; dead-code detection before deleting a function. \n\nBy default, matches inside string literals and comments are excluded (so test fixtures and doc comments don't drown out real call sites); pass `include_strings: true` to restore all occurrences. Returns `{definition, references, total_references, pagination, status}` where `definition` is the first symbol definition (`{path, line, kind, symbol, span, preview}`) or null, and `references` is a flat array of `{path, line, preview}` covering every textual occurrence including the definition site itself. Pagination applies to `references` only; if `pagination.has_more` is true, fetch the next page with `offset`. On \"Index not found\" / \"stale\" error, call `index_project`, then retry.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "pattern": {
                            "type": "string",
                            "description": "Symbol name or text pattern to find references for (e.g., 'CacheManager', 'extract_symbols')"
                        },
                        "mode": {
                            "type": "string",
                            "enum": ["list", "count"],
                            "description": "Response mode: \"list\" (default) returns full results with definition + references; \"count\" returns only {count, pattern} — faster, skips match body serialization."
                        },
                        "kind": {
                            "type": "string",
                            "description": "Filter definition lookup by symbol kind (function, class, struct, trait, etc.)"
                        },
                        "lang": {
                            "type": "string",
                            "description": "Filter by language (rust, typescript, python, go, etc.)"
                        },
                        "glob": {
                            "type": "array",
                            "items": {"type": "string"},
                            "description": "Include files matching glob patterns (e.g., ['src/**/*.rs'])"
                        },
                        "exclude": {
                            "type": "array",
                            "items": {"type": "string"},
                            "description": "Exclude files matching glob patterns (e.g., ['target/**', 'tests/**'])"
                        },
                        "limit": {
                            "type": "integer",
                            "description": "Max references per page (default: 200, max: 500). The 200-result default covers most find-all tasks in a single call. Pagination applies to references only."
                        },
                        "offset": {
                            "type": "integer",
                            "description": "Pagination offset for references (skip first N). Use with limit."
                        },
                        "force": {
                            "type": "boolean",
                            "description": "Force execution of potentially expensive queries (bypasses broad query detection)"
                        },
                        "include_strings": {
                            "type": "boolean",
                            "description": "Include matches inside string literals and comments (default: false). By default these are excluded to focus on real call sites."
                        }
                    },
                    "required": ["pattern"]
                }
            },
            {
                "name": "gather_context",
                "description": "One-shot codebase orientation: structure, file types, project type, frameworks, entry points, test layout, config files. Prefer this over Glob-based recon at session start — Reflex returns a single consolidated overview instead of multiple glob calls. By default (no parameters) all context types are gathered; pass individual flags (`structure`, `framework`, `entry_points`, etc.) for a focused slice. Use `depth` to control tree depth (default 2) and `path` to focus on a subdirectory. \n\nUse this for: getting oriented in an unfamiliar codebase; locating entry points; confirming which frameworks/languages are in use. For finding where a specific symbol/pattern lives, use `search_code` or `find_references` instead.",
                "inputSchema": {
                    "type": "object",
                    "properties": {
                        "structure": {
                            "type": "boolean",
                            "description": "Show directory structure"
                        },
                        "file_types": {
                            "type": "boolean",
                            "description": "Show file type distribution"
                        },
                        "project_type": {
                            "type": "boolean",
                            "description": "Detect project type (CLI/library/webapp/monorepo)"
                        },
                        "framework": {
                            "type": "boolean",
                            "description": "Detect frameworks and conventions"
                        },
                        "entry_points": {
                            "type": "boolean",
                            "description": "Show entry point files"
                        },
                        "test_layout": {
                            "type": "boolean",
                            "description": "Show test organization pattern"
                        },
                        "config_files": {
                            "type": "boolean",
                            "description": "List important configuration files"
                        },
                        "depth": {
                            "type": "integer",
                            "description": "Tree depth for structure (default: 2)"
                        },
                        "path": {
                            "type": "string",
                            "description": "Focus on specific directory path"
                        }
                    }
                }
            },
            {
                "name": "check_index_status",
                "description": "Check whether the Reflex search index is fresh, stale, or missing — without running any search. Call this once at session start and before any bulk search/refactoring task; if `status` is stale or missing, call `index_project` before searching. \n\nReturns `{status: \"fresh\" | \"stale\" | \"missing\", reason, action_required, files_modified?}`. Useful after git operations (checkout, merge, rebase, pull) that may have moved HEAD off the indexed commit; `reason` explains the staleness and `action_required` gives the fix command (always `rfx index` when stale). \n\nExample fresh: `{\"status\": \"fresh\"}`. Example stale: `{\"status\": \"stale\", \"reason\": \"Commit changed from abc1234 to def5678\", \"action_required\": \"rfx index\"}`",
                "inputSchema": {
                    "type": "object",
                    "properties": {}
                }
            }
        ]
    });

    if enable_structural {
        return Ok(all_tools);
    }

    // Filter out structural-analysis tools when disabled in config
    let tools: Vec<Value> = all_tools["tools"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|t| !STRUCTURAL_TOOLS.contains(&t["name"].as_str().unwrap_or("")))
        .cloned()
        .collect();
    Ok(json!({ "tools": tools }))
}

/// Handle tools/call request
/// Build a successful MCP `tools/call` result.
///
/// REF-215: Reflex emits only the spec-guaranteed `content[text]` baseline — the
/// result data serialized as a JSON string. The spec-optional `structuredContent`
/// field (REF-202) was dropped per the REF-196 board decision: every conforming
/// MCP client must handle `content[text]`, it is what reaches the model in
/// Reflex's primary Claude Code use case, and emitting a single field removes any
/// chance of a client consuming both and double-counting tokens. The columnar
/// `{columns, rows}` shape (REF-209) is independent and still lives inside this
/// text payload.
///
/// Only success paths use this — error results are surfaced through the JSON-RPC
/// error channel in `process_request`, never as a tool result, so there are no
/// `isError` responses to preserve here.
fn make_tool_result(data: Value) -> Value {
    json!({
        "content": [{"type": "text", "text": serde_json::to_string(&data).unwrap_or_default()}]
    })
}

/// REF-209: columnar result-format toggle for `search_code` / `search_regex`.
///
/// Default ON. Returns `false` only when `REFLEX_MCP_COLUMNAR` is explicitly set
/// to a falsey value (`0`/`false`/`off`/`no`, case-insensitive), which restores
/// the legacy file-grouped `results` array for backwards compatibility. The
/// emitted payload (`to_columnar`) consults this to decide the shape.
fn columnar_enabled() -> bool {
    match std::env::var("REFLEX_MCP_COLUMNAR") {
        Ok(v) => !matches!(
            v.trim().to_ascii_lowercase().as_str(),
            "0" | "false" | "off" | "no"
        ),
        Err(_) => true,
    }
}

/// REF-212: render a bool as a compact on/off token for the startup diagnostic.
fn onoff(v: bool) -> &'static str {
    if v { "on" } else { "off" }
}

/// REF-212: one-line startup diagnostic summarising the flags the MCP server
/// resolved from its environment, plus build provenance.
///
/// Emitted to **stderr** at startup (never stdout, which carries the JSON-RPC
/// stream). Claude Code captures an MCP server's stderr into its per-session
/// `mcp-logs-<server>/` files, so this line is the ground-truth record of which
/// `columnar` / structural behaviour a given trial actually ran with.
///
/// It exists specifically to catch the failure mode behind [REF-212]: an env
/// toggle that *was* forwarded to the process but was not honoured because the
/// running binary predated the code that reads it. The reported flags reflect
/// what THIS binary actually resolved, and `build=` names the commit it was
/// compiled from — so a benchmark run against an out-of-date rfx is obvious
/// rather than silently corrupting results.
///
/// REF-215 removed the `structuredContent` / `sc_stage2` flags along with the
/// env vars that drove them.
fn startup_flags_line(columnar: bool, structural: bool) -> String {
    format!(
        "reflex-mcp startup: version={} build={} columnar={} structural_tools={}",
        env!("CARGO_PKG_VERSION"),
        option_env!("REFLEX_GIT_SHA").unwrap_or("unknown"),
        onoff(columnar),
        onoff(structural),
    )
}

/// REF-209: reshape a search response's file-grouped `results` array into a
/// columnar `{ columns, rows }` pair to cut key-repetition token cost.
///
/// One row is emitted per match; `path`/`language` (and any file-level
/// `dependencies`) repeat per row so each row is self-contained and needs no
/// back-reference. Columns are emitted dynamically: the five always-present
/// fields (`path`, `language`, `start_line`, `end_line`, `preview`) plus any
/// optional field (`kind`, `symbol`, `context_before`, `context_after`,
/// `dependencies`) that at least one match/file actually carries — so the common
/// full-text case stays at five columns with no all-`null` padding.
///
/// Objects without a `results` array (count-mode `{count, pattern}`, error
/// shapes) are returned unchanged, so this is safe to call on any success value.
fn to_columnar(mut value: Value) -> Value {
    // Only transform success objects that carry a `results` array.
    if !value.get("results").map(Value::is_array).unwrap_or(false) {
        return value;
    }
    let obj = value
        .as_object_mut()
        .expect("value has a `results` member, so it is an object");
    let results = match obj.remove("results") {
        Some(Value::Array(results)) => results,
        // Unreachable given the guard above, but stay total rather than panic.
        other => {
            if let Some(other) = other {
                obj.insert("results".to_string(), other);
            }
            return value;
        }
    };

    // Pass 1: decide which optional columns any row needs.
    let mut has_kind = false;
    let mut has_symbol = false;
    let mut has_ctx_before = false;
    let mut has_ctx_after = false;
    let mut has_deps = false;
    for file in &results {
        if file.get("dependencies").is_some() {
            has_deps = true;
        }
        if let Some(matches) = file.get("matches").and_then(Value::as_array) {
            for m in matches {
                has_kind |= m.get("kind").is_some();
                has_symbol |= m.get("symbol").is_some();
                has_ctx_before |= m.get("context_before").is_some();
                has_ctx_after |= m.get("context_after").is_some();
            }
        }
    }

    // Fixed base columns; optional ones appended only when present, in a stable
    // order so `columns[i]` is deterministic for a given result set.
    let mut columns: Vec<&'static str> =
        vec!["path", "language", "start_line", "end_line", "preview"];
    if has_kind {
        columns.push("kind");
    }
    if has_symbol {
        columns.push("symbol");
    }
    if has_ctx_before {
        columns.push("context_before");
    }
    if has_ctx_after {
        columns.push("context_after");
    }
    if has_deps {
        columns.push("dependencies");
    }

    // Pass 2: project each match into a positional row aligned to `columns`.
    let mut rows: Vec<Value> = Vec::new();
    for file in &results {
        let path = file.get("path").cloned().unwrap_or(Value::Null);
        let language = file.get("language").cloned().unwrap_or(Value::Null);
        let deps = file.get("dependencies").cloned().unwrap_or(Value::Null);
        let Some(matches) = file.get("matches").and_then(Value::as_array) else {
            continue;
        };
        for m in matches {
            let span = m.get("span");
            let start_line = span
                .and_then(|s| s.get("start_line"))
                .cloned()
                .unwrap_or(Value::Null);
            let end_line = span
                .and_then(|s| s.get("end_line"))
                .cloned()
                .unwrap_or(Value::Null);
            let preview = m.get("preview").cloned().unwrap_or(Value::Null);

            let mut row: Vec<Value> = vec![
                path.clone(),
                language.clone(),
                start_line,
                end_line,
                preview,
            ];
            if has_kind {
                row.push(m.get("kind").cloned().unwrap_or(Value::Null));
            }
            if has_symbol {
                row.push(m.get("symbol").cloned().unwrap_or(Value::Null));
            }
            if has_ctx_before {
                row.push(m.get("context_before").cloned().unwrap_or(Value::Null));
            }
            if has_ctx_after {
                row.push(m.get("context_after").cloned().unwrap_or(Value::Null));
            }
            if has_deps {
                row.push(deps.clone());
            }
            rows.push(Value::Array(row));
        }
    }

    obj.insert("columns".to_string(), json!(columns));
    obj.insert("rows".to_string(), Value::Array(rows));
    value
}

fn handle_call_tool(params: Option<Value>) -> Result<Value> {
    let params = params.ok_or_else(|| anyhow::anyhow!("Missing params for tools/call"))?;

    let name = params["name"]
        .as_str()
        .ok_or_else(|| anyhow::anyhow!("Missing tool name"))?;

    let arguments = params["arguments"].clone();

    match name {
        "list_locations" => {
            // Location discovery tool (minimal token usage)
            let pattern = arguments["pattern"]
                .as_str()
                .ok_or_else(|| anyhow::anyhow!("Missing pattern"))?
                .to_string();

            let lang = arguments["lang"].as_str().map(|s| s.to_string());
            let file = arguments["file"].as_str().map(|s| s.to_string());
            let glob_patterns = arguments["glob"]
                .as_array()
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                        .collect()
                })
                .unwrap_or_default();
            let exclude_patterns = arguments["exclude"]
                .as_array()
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                        .collect()
                })
                .unwrap_or_default();
            let force = arguments["force"].as_bool().unwrap_or(false);
            let dependencies = arguments["dependencies"].as_bool().unwrap_or(false);

            let language = parse_language(lang);

            let filter = QueryFilter {
                language,
                kind: None,
                use_ast: false,
                use_regex: false,
                limit: None, // No limit for paths-only mode
                symbols_mode: false,
                expand: false,
                file_pattern: file,
                exact: false,
                use_contains: false,
                timeout_secs: 30,
                glob_patterns,
                exclude_patterns,
                paths_only: true, // KEY: Enable paths-only mode
                offset: None,
                force,
                suppress_output: true, // MCP always returns JSON
                include_dependencies: dependencies,
                ..Default::default()
            };

            let cache = CacheManager::new(".");
            let engine = QueryEngine::new(cache);
            let response = engine.search_with_metadata(&pattern, filter)?;

            // Extract locations (path + line) for each match
            let locations: Vec<serde_json::Value> = response
                .results
                .iter()
                .flat_map(|file_group| {
                    file_group.matches.iter().map(move |m| {
                        json!({
                            "path": file_group.path.clone(),
                            "line": m.span.start_line
                        })
                    })
                })
                .collect();

            // Return compact response (just locations + count)
            let compact_response = json!({
                "status": response.status,
                "total_locations": locations.len(),
                "locations": locations
            });

            Ok(make_tool_result(compact_response))
        }
        "count_occurrences" => {
            // Quick stats tool (minimal token usage)
            let pattern = arguments["pattern"]
                .as_str()
                .ok_or_else(|| anyhow::anyhow!("Missing pattern"))?
                .to_string();

            let lang = arguments["lang"].as_str().map(|s| s.to_string());
            let kind = arguments["kind"].as_str().map(|s| s.to_string());
            let symbols = arguments["symbols"].as_bool();
            let file = arguments["file"].as_str().map(|s| s.to_string());
            let glob_patterns = arguments["glob"]
                .as_array()
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                        .collect()
                })
                .unwrap_or_default();
            let exclude_patterns = arguments["exclude"]
                .as_array()
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                        .collect()
                })
                .unwrap_or_default();
            let force = arguments["force"].as_bool().unwrap_or(false);
            let dependencies = arguments["dependencies"].as_bool().unwrap_or(false);

            let language = parse_language(lang);
            let parsed_kind = parse_symbol_kind(kind);
            let symbols_mode = symbols.unwrap_or(false) || parsed_kind.is_some();

            let filter = QueryFilter {
                language,
                kind: parsed_kind,
                use_ast: false,
                use_regex: false,
                limit: None, // No limit for counting
                symbols_mode,
                expand: false,
                file_pattern: file,
                exact: false,
                use_contains: false,
                timeout_secs: 30,
                glob_patterns,
                exclude_patterns,
                paths_only: false, // Need to count all occurrences
                offset: None,
                force,
                suppress_output: true, // MCP always returns JSON
                include_dependencies: dependencies,
                ..Default::default()
            };

            let cache = CacheManager::new(".");
            let engine = QueryEngine::new(cache);
            let response = engine.search_with_metadata(&pattern, filter)?;

            // Count unique files
            use std::collections::HashSet;
            let unique_files: HashSet<String> =
                response.results.iter().map(|fg| fg.path.clone()).collect();

            // Return minimal stats
            let stats = json!({
                "status": response.status,
                "pattern": pattern,
                "total": response.pagination.total,
                "files": unique_files.len()
            });

            Ok(make_tool_result(stats))
        }
        "search_code" => {
            let pattern = arguments["pattern"]
                .as_str()
                .ok_or_else(|| anyhow::anyhow!("Missing pattern"))?
                .to_string();

            let lang = arguments["lang"].as_str().map(|s| s.to_string());
            let kind = arguments["kind"].as_str().map(|s| s.to_string());
            let symbols = arguments["symbols"].as_bool();
            let exact = arguments["exact"].as_bool();
            let file = arguments["file"].as_str().map(|s| s.to_string());
            let limit = arguments["limit"].as_u64().map(|n| n as usize);
            let expand = arguments["expand"].as_bool();
            let glob_patterns: Vec<String> = arguments["glob"]
                .as_array()
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                        .collect()
                })
                .unwrap_or_default();
            let exclude_patterns = arguments["exclude"]
                .as_array()
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                        .collect()
                })
                .unwrap_or_default();
            let paths_only = arguments["paths"].as_bool().unwrap_or(false);
            let force = arguments["force"].as_bool().unwrap_or(false);
            let dependencies = arguments["dependencies"].as_bool().unwrap_or(false);
            let preview_length = arguments["preview_length"]
                .as_u64()
                .map(|n| n as usize)
                .unwrap_or(DEFAULT_MCP_PREVIEW_LENGTH);

            let language = parse_language(lang.clone());

            // Build warning for unsupported language + dependencies combination (REF-171)
            let deps_lang_warning: Option<String> =
                if dependencies && matches!(language, Some(l) if l != Language::Rust) {
                    Some(format!(
                        "Warning: dependencies is currently only supported for Rust files. \
                         No dependency data will be included for {} files.",
                        lang.as_deref().unwrap_or("non-Rust")
                    ))
                } else {
                    None
                };

            let parsed_kind = parse_symbol_kind(kind);
            let symbols_mode = symbols.unwrap_or(false) || parsed_kind.is_some();

            let offset = arguments["offset"].as_u64().map(|n| n as usize);

            // Smart limit handling:
            // 1. If --paths is set and user didn't specify limit: no limit (None)
            // 2. If user specified limit: use that value, capped at 500
            // 3. Otherwise: use the agent-oriented default (REF-191) so find-all
            //    tasks come back in one call instead of paginating.
            let final_limit = if paths_only && limit.is_none() {
                None // --paths without explicit limit means no limit
            } else if let Some(user_limit) = limit {
                Some(user_limit.min(500)) // Use user-specified limit, capped at 500
            } else {
                Some(DEFAULT_MCP_RESULT_LIMIT)
            };

            let mode = arguments["mode"].as_str().unwrap_or("list");

            // Count mode: run query but return only the total match count.
            // Skips preview truncation and full result serialization for speed.
            if mode == "count" {
                let count_filter = QueryFilter {
                    language,
                    kind: parsed_kind,
                    use_ast: false,
                    use_regex: false,
                    limit: None, // count everything
                    symbols_mode,
                    expand: false,
                    file_pattern: file,
                    exact: exact.unwrap_or(false),
                    use_contains: false,
                    timeout_secs: 30,
                    glob_patterns,
                    exclude_patterns,
                    paths_only: false,
                    offset: None,
                    force,
                    suppress_output: true,
                    include_dependencies: false,
                    ..Default::default()
                };
                let cache = CacheManager::new(".");
                let engine = QueryEngine::new(cache);
                let response = engine.search_with_metadata(&pattern, count_filter)?;
                let result = json!({"count": response.pagination.total, "pattern": pattern});
                return Ok(make_tool_result(result));
            }

            let filter = QueryFilter {
                language,
                kind: parsed_kind,
                use_ast: false,
                use_regex: false,
                limit: final_limit,
                symbols_mode,
                expand: expand.unwrap_or(false),
                file_pattern: file,
                exact: exact.unwrap_or(false),
                use_contains: false, // Default to word-boundary matching for MCP
                timeout_secs: 30,    // Default 30 second timeout for MCP queries
                glob_patterns: glob_patterns.clone(),
                exclude_patterns,
                paths_only,
                offset,
                force,
                suppress_output: true, // MCP always returns JSON
                include_dependencies: dependencies,
                ..Default::default()
            };

            let cache = CacheManager::new(".");
            let engine = QueryEngine::new(cache);
            let mut response = engine.search_with_metadata(&pattern, filter)?;

            // Apply preview truncation for token efficiency
            for file_group in response.results.iter_mut() {
                for m in file_group.matches.iter_mut() {
                    m.preview = crate::cli::truncate_preview(&m.preview, preview_length);
                }
            }

            // Calculate result count for AI instruction
            let result_count: usize = response.results.iter().map(|fg| fg.matches.len()).sum();

            // Generate AI instruction (MCP always uses AI mode)
            response.ai_instruction = crate::query::generate_ai_instruction(
                result_count,
                response.pagination.total,
                response.pagination.has_more,
                symbols_mode,
                paths_only,
                false, // use_ast
                false, // use_regex
                language.is_some(),
                !glob_patterns.is_empty(),
                exact.unwrap_or(false),
            );

            // Prepend language limitation warning to AI instruction (REF-171)
            if let Some(warn) = deps_lang_warning {
                response.ai_instruction = Some(match response.ai_instruction.take() {
                    Some(existing) => format!("{warn}\n\n{existing}"),
                    None => warn,
                });
            }

            // Extract pagination scalars before consuming response (REF-185)
            let has_more = response.pagination.has_more;
            let total_count = response.pagination.total;

            let mut response_val = serde_json::to_value(response)?;
            if let serde_json::Value::Object(ref mut map) = response_val {
                map.insert("has_more".to_string(), json!(has_more));
                map.insert("total_count".to_string(), json!(total_count));
                map.insert("returned_count".to_string(), json!(result_count));
            }

            // REF-209: emit the token-efficient columnar shape by default; the
            // env toggle restores the legacy results[] array for compatibility.
            if columnar_enabled() {
                response_val = to_columnar(response_val);
            }

            Ok(make_tool_result(response_val))
        }
        "search_regex" => {
            let pattern = arguments["pattern"]
                .as_str()
                .ok_or_else(|| anyhow::anyhow!("Missing pattern"))?
                .to_string();

            let lang = arguments["lang"].as_str().map(|s| s.to_string());
            let file = arguments["file"].as_str().map(|s| s.to_string());
            let limit = arguments["limit"].as_u64().map(|n| n as usize);
            let glob_patterns: Vec<String> = arguments["glob"]
                .as_array()
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                        .collect()
                })
                .unwrap_or_default();
            let exclude_patterns = arguments["exclude"]
                .as_array()
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                        .collect()
                })
                .unwrap_or_default();
            let paths_only = arguments["paths"].as_bool().unwrap_or(false);
            let force = arguments["force"].as_bool().unwrap_or(false);
            let dependencies = arguments["dependencies"].as_bool().unwrap_or(false);

            let language = parse_language(lang);
            let offset = arguments["offset"].as_u64().map(|n| n as usize);

            // Smart limit handling (same as search_code)
            let final_limit = if paths_only && limit.is_none() {
                None // --paths without explicit limit means no limit
            } else if let Some(user_limit) = limit {
                Some(user_limit.min(500)) // Use user-specified limit, capped at 500
            } else {
                Some(DEFAULT_MCP_RESULT_LIMIT) // REF-191: one-call default
            };

            let mode = arguments["mode"].as_str().unwrap_or("list");

            // Count mode: return only the total match count, no match bodies.
            if mode == "count" {
                let count_filter = QueryFilter {
                    language,
                    kind: None,
                    use_ast: false,
                    use_regex: true,
                    limit: None, // count everything
                    symbols_mode: false,
                    expand: false,
                    file_pattern: file,
                    exact: false,
                    use_contains: false,
                    timeout_secs: 30,
                    glob_patterns,
                    exclude_patterns,
                    paths_only: false,
                    offset: None,
                    force,
                    suppress_output: true,
                    include_dependencies: false,
                    ..Default::default()
                };
                let cache = CacheManager::new(".");
                let engine = QueryEngine::new(cache);
                let response = engine.search_with_metadata(&pattern, count_filter)?;
                let result = json!({"count": response.pagination.total, "pattern": pattern});
                return Ok(make_tool_result(result));
            }

            let filter = QueryFilter {
                language,
                kind: None,
                use_ast: false,
                use_regex: true,
                limit: final_limit,
                symbols_mode: false,
                expand: false,
                file_pattern: file,
                exact: false,
                use_contains: false, // Regex mode uses substring matching via use_regex flag
                timeout_secs: 30,    // Default 30 second timeout for MCP queries
                glob_patterns: glob_patterns.clone(),
                exclude_patterns,
                paths_only,
                offset,
                force,
                suppress_output: true, // MCP always returns JSON
                include_dependencies: dependencies,
                ..Default::default()
            };

            let cache = CacheManager::new(".");
            let engine = QueryEngine::new(cache);
            let mut response = engine.search_with_metadata(&pattern, filter)?;

            // Apply preview truncation for token efficiency
            for file_group in response.results.iter_mut() {
                for m in file_group.matches.iter_mut() {
                    m.preview =
                        crate::cli::truncate_preview(&m.preview, DEFAULT_MCP_PREVIEW_LENGTH);
                }
            }

            // Calculate result count for AI instruction
            let result_count: usize = response.results.iter().map(|fg| fg.matches.len()).sum();

            // Generate AI instruction (MCP always uses AI mode)
            response.ai_instruction = crate::query::generate_ai_instruction(
                result_count,
                response.pagination.total,
                response.pagination.has_more,
                false, // symbols_mode
                paths_only,
                false, // use_ast
                true,  // use_regex
                language.is_some(),
                !glob_patterns.is_empty(),
                false, // exact
            );

            // Extract pagination scalars before consuming response (REF-185)
            let has_more = response.pagination.has_more;
            let total_count = response.pagination.total;

            let mut response_val = serde_json::to_value(response)?;
            if let serde_json::Value::Object(ref mut map) = response_val {
                map.insert("has_more".to_string(), json!(has_more));
                map.insert("total_count".to_string(), json!(total_count));
                map.insert("returned_count".to_string(), json!(result_count));
            }

            // REF-209: emit the token-efficient columnar shape by default; the
            // env toggle restores the legacy results[] array for compatibility.
            if columnar_enabled() {
                response_val = to_columnar(response_val);
            }

            Ok(make_tool_result(response_val))
        }
        "search_ast" => {
            // AST pattern (Tree-sitter S-expression)
            let ast_pattern = arguments["pattern"]
                .as_str()
                .ok_or_else(|| anyhow::anyhow!("Missing pattern (AST S-expression)"))?
                .to_string();

            let lang_str = arguments["lang"]
                .as_str()
                .ok_or_else(|| anyhow::anyhow!("Missing lang (required for AST queries)"))?
                .to_string();

            let file = arguments["file"].as_str().map(|s| s.to_string());
            let limit = arguments["limit"].as_u64().map(|n| n as usize);
            let glob_patterns: Vec<String> = arguments["glob"]
                .as_array()
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                        .collect()
                })
                .unwrap_or_default();
            let exclude_patterns: Vec<String> = arguments["exclude"]
                .as_array()
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                        .collect()
                })
                .unwrap_or_default();
            let paths_only = arguments["paths"].as_bool().unwrap_or(false);
            let force = arguments["force"].as_bool().unwrap_or(false);
            let dependencies = arguments["dependencies"].as_bool().unwrap_or(false);

            let language = parse_language(Some(lang_str)).ok_or_else(|| {
                anyhow::anyhow!("Invalid or unsupported language for AST queries")
            })?;

            // Warn if glob patterns are not provided (performance issue)
            if glob_patterns.is_empty() && exclude_patterns.is_empty() {
                log::warn!(
                    "⚠️  AST query without glob patterns will scan the ENTIRE codebase. This may take 2-10+ seconds."
                );
                log::warn!(
                    "    Strongly recommend using glob patterns, e.g., glob=['src/**/*.rs']"
                );
            }

            let offset = arguments["offset"].as_u64().map(|n| n as usize);

            // Smart limit handling (same as search_code)
            let final_limit = if paths_only && limit.is_none() {
                None // --paths without explicit limit means no limit
            } else if let Some(user_limit) = limit {
                Some(user_limit) // Use user-specified limit
            } else {
                Some(100) // Default: limit to 100 results for token efficiency
            };

            let filter = QueryFilter {
                language: Some(language),
                kind: None,
                use_ast: true,
                use_regex: false,
                limit: final_limit,
                symbols_mode: false,
                expand: false,
                file_pattern: file,
                exact: false,
                use_contains: false,
                timeout_secs: 60, // Longer timeout for AST queries (they're slow)
                glob_patterns,
                exclude_patterns,
                paths_only,
                offset,
                force,
                suppress_output: true, // MCP always returns JSON
                include_dependencies: dependencies,
                ..Default::default()
            };

            let cache = CacheManager::new(".");
            let engine = QueryEngine::new(cache);

            // Use the new search_ast_all_files method (no trigram filtering)
            let mut results = engine.search_ast_all_files(&ast_pattern, filter)?;

            // Apply preview truncation for token efficiency
            for result in &mut results {
                result.preview =
                    crate::cli::truncate_preview(&result.preview, DEFAULT_MCP_PREVIEW_LENGTH);
            }

            Ok(make_tool_result(serde_json::to_value(&results)?))
        }
        "index_project" => {
            let force = arguments["force"].as_bool();
            let languages = arguments["languages"].as_array().map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(|s| s.to_string()))
                    .collect::<Vec<_>>()
            });

            let cache = CacheManager::new(".");

            if force.unwrap_or(false) {
                log::info!("Force rebuild requested, clearing existing cache");
                cache.clear()?;
            }

            let lang_filters: Vec<Language> = languages
                .unwrap_or_default()
                .iter()
                .filter_map(|s| parse_language(Some(s.clone())))
                .collect();

            let config = IndexConfig {
                languages: lang_filters,
                ..Default::default()
            };

            let indexer = Indexer::new(cache, config);
            let path = PathBuf::from(".");
            let stats = indexer.index(&path, false)?;

            Ok(make_tool_result(serde_json::to_value(&stats)?))
        }
        "get_dependencies" => {
            let path = arguments["path"]
                .as_str()
                .ok_or_else(|| anyhow::anyhow!("Missing path"))?
                .to_string();

            let cache = CacheManager::new(".");
            let deps_index = DependencyIndex::new(cache);

            // Fuzzy path matching
            let file_id = deps_index
                .get_file_id_by_path(&path)?
                .ok_or_else(|| anyhow::anyhow!("File '{}' not found in index", path))?;

            let dependencies = deps_index.get_dependencies_info(file_id)?;

            Ok(make_tool_result(serde_json::to_value(&dependencies)?))
        }
        "get_dependents" => {
            let path = arguments["path"]
                .as_str()
                .ok_or_else(|| anyhow::anyhow!("Missing path"))?
                .to_string();

            let cache = CacheManager::new(".");
            let deps_index = DependencyIndex::new(cache);

            // Fuzzy path matching
            let file_id = deps_index
                .get_file_id_by_path(&path)?
                .ok_or_else(|| anyhow::anyhow!("File '{}' not found in index", path))?;

            let dependents = deps_index.get_dependents(file_id)?;
            let paths = deps_index.get_file_paths(&dependents)?;

            // Convert to array of paths
            let path_list: Vec<String> = dependents
                .iter()
                .filter_map(|id| paths.get(id).cloned())
                .collect();

            Ok(make_tool_result(serde_json::to_value(&path_list)?))
        }
        "get_transitive_deps" => {
            let path = arguments["path"]
                .as_str()
                .ok_or_else(|| anyhow::anyhow!("Missing path"))?
                .to_string();

            let depth = arguments["depth"].as_u64().map(|n| n as usize).unwrap_or(3); // Default depth of 3

            let cache = CacheManager::new(".");
            let deps_index = DependencyIndex::new(cache);

            // Fuzzy path matching
            let file_id = deps_index
                .get_file_id_by_path(&path)?
                .ok_or_else(|| anyhow::anyhow!("File '{}' not found in index", path))?;

            let transitive = deps_index.get_transitive_deps(file_id, depth)?;

            // Get paths for all file IDs
            let file_ids: Vec<i64> = transitive.keys().copied().collect();
            let paths = deps_index.get_file_paths(&file_ids)?;

            // Build result with path → depth mapping
            let result: Vec<serde_json::Value> = transitive
                .iter()
                .filter_map(|(id, depth)| {
                    paths.get(id).map(|path| {
                        json!({
                            "path": path,
                            "depth": depth
                        })
                    })
                })
                .collect();

            Ok(make_tool_result(serde_json::to_value(&result)?))
        }
        "find_hotspots" => {
            let limit = arguments["limit"].as_u64().map(|n| n as usize);
            let offset = arguments["offset"].as_u64().map(|n| n as usize);
            let min_dependents = arguments["min_dependents"]
                .as_u64()
                .map(|n| n as usize)
                .unwrap_or(2);
            let sort = arguments["sort"].as_str().map(|s| s.to_string());

            let cache = CacheManager::new(".");
            let deps_index = DependencyIndex::new(cache);

            // Get all hotspots first (without limit) to track total count
            let mut all_hotspots = deps_index.find_hotspots(None, min_dependents)?;

            // Apply sorting (default: descending - most imports first)
            let sort_order = sort.as_deref().unwrap_or("desc");
            match sort_order {
                "asc" => {
                    // Ascending: least imports first
                    all_hotspots.sort_by_key(|a| a.1);
                }
                "desc" => {
                    // Descending: most imports first (default)
                    all_hotspots.sort_by_key(|a| std::cmp::Reverse(a.1));
                }
                _ => {
                    return Err(anyhow::anyhow!(
                        "Invalid sort order '{}'. Supported: asc, desc",
                        sort_order
                    ));
                }
            }

            let total_count = all_hotspots.len();

            // Apply offset pagination
            let offset_val = offset.unwrap_or(0);
            let mut hotspots: Vec<_> = all_hotspots.into_iter().skip(offset_val).collect();

            // Apply limit (default 200)
            let limit_val = limit.unwrap_or(200);
            hotspots.truncate(limit_val);

            let count = hotspots.len();
            let has_more = offset_val + count < total_count;

            // Get paths for all file IDs
            let file_ids: Vec<i64> = hotspots.iter().map(|(id, _)| *id).collect();
            let paths = deps_index.get_file_paths(&file_ids)?;

            // Build result with path + import_count (no file_id)
            let results: Vec<serde_json::Value> = hotspots
                .iter()
                .filter_map(|(id, import_count)| {
                    paths.get(id).map(|path| {
                        json!({
                            "path": path,
                            "import_count": import_count,
                        })
                    })
                })
                .collect();

            let response = json!({
                "pagination": {
                    "total": total_count,
                    "count": count,
                    "offset": offset_val,
                    "limit": limit_val,
                    "has_more": has_more,
                },
                "results": results,
            });

            Ok(make_tool_result(response))
        }
        "find_circular" => {
            let limit = arguments["limit"].as_u64().map(|n| n as usize);
            let offset = arguments["offset"].as_u64().map(|n| n as usize);
            let sort = arguments["sort"].as_str().map(|s| s.to_string());

            let cache = CacheManager::new(".");
            let deps_index = DependencyIndex::new(cache);

            let mut all_cycles = deps_index.detect_circular_dependencies()?;

            // Apply sorting (default: descending - longest cycles first)
            let sort_order = sort.as_deref().unwrap_or("desc");
            match sort_order {
                "asc" => {
                    // Ascending: shortest cycles first
                    all_cycles.sort_by_key(|cycle| cycle.len());
                }
                "desc" => {
                    // Descending: longest cycles first (default)
                    all_cycles.sort_by_key(|cycle| std::cmp::Reverse(cycle.len()));
                }
                _ => {
                    return Err(anyhow::anyhow!(
                        "Invalid sort order '{}'. Supported: asc, desc",
                        sort_order
                    ));
                }
            }

            let total_count = all_cycles.len();

            // Apply offset pagination
            let offset_val = offset.unwrap_or(0);
            let mut cycles: Vec<_> = all_cycles.into_iter().skip(offset_val).collect();

            // Apply limit (default 200)
            let limit_val = limit.unwrap_or(200);
            cycles.truncate(limit_val);

            let count = cycles.len();
            let has_more = offset_val + count < total_count;

            // Convert cycles to paths (without file_ids)
            let file_ids: Vec<i64> = cycles.iter().flat_map(|c| c.iter()).copied().collect();
            let paths = deps_index.get_file_paths(&file_ids)?;

            let results: Vec<serde_json::Value> = cycles
                .iter()
                .map(|cycle| {
                    let cycle_paths: Vec<_> = cycle
                        .iter()
                        .filter_map(|id| paths.get(id).cloned())
                        .collect();
                    json!({
                        "paths": cycle_paths,
                    })
                })
                .collect();

            let response = json!({
                "pagination": {
                    "total": total_count,
                    "count": count,
                    "offset": offset_val,
                    "limit": limit_val,
                    "has_more": has_more,
                },
                "results": results,
            });

            Ok(make_tool_result(response))
        }
        "find_unused" => {
            let limit = arguments["limit"].as_u64().map(|n| n as usize);
            let offset = arguments["offset"].as_u64().map(|n| n as usize);

            let cache = CacheManager::new(".");
            let deps_index = DependencyIndex::new(cache);

            let all_unused = deps_index.find_unused_files()?;
            let total_count = all_unused.len();

            // Apply offset pagination
            let offset_val = offset.unwrap_or(0);
            let mut unused: Vec<_> = all_unused.into_iter().skip(offset_val).collect();

            // Apply limit (default 200)
            let limit_val = limit.unwrap_or(200);
            unused.truncate(limit_val);

            let count = unused.len();
            let has_more = offset_val + count < total_count;

            // Get paths for all unused file IDs
            let paths = deps_index.get_file_paths(&unused)?;

            // Build result (flat array of path strings)
            let results: Vec<String> = unused
                .iter()
                .filter_map(|id| paths.get(id).cloned())
                .collect();

            let response = json!({
                "pagination": {
                    "total": total_count,
                    "count": count,
                    "offset": offset_val,
                    "limit": limit_val,
                    "has_more": has_more,
                },
                "results": results,
            });

            Ok(make_tool_result(response))
        }
        "find_islands" => {
            let limit = arguments["limit"].as_u64().map(|n| n as usize);
            let offset = arguments["offset"].as_u64().map(|n| n as usize);
            let min_island_size = arguments["min_island_size"]
                .as_u64()
                .map(|n| n as usize)
                .unwrap_or(2);
            let max_island_size = arguments["max_island_size"].as_u64().map(|n| n as usize);
            let sort = arguments["sort"].as_str().map(|s| s.to_string());

            let cache = CacheManager::new(".");
            let deps_index = DependencyIndex::new(cache);

            let all_islands = deps_index.find_islands()?;
            let total_components = all_islands.len();

            // Get total file count for percentage calculation
            let total_files = deps_index.get_cache().stats()?.total_files;

            // Calculate max_island_size default: min of 500 or 50% of total files
            let max_size = max_island_size.unwrap_or_else(|| {
                let fifty_percent = (total_files as f64 * 0.5) as usize;
                fifty_percent.min(500)
            });

            // Filter islands by size
            let mut islands: Vec<_> = all_islands
                .into_iter()
                .filter(|island| {
                    let size = island.len();
                    size >= min_island_size && size <= max_size
                })
                .collect();

            // Apply sorting (default: descending - largest islands first)
            let sort_order = sort.as_deref().unwrap_or("desc");
            match sort_order {
                "asc" => {
                    // Ascending: smallest islands first
                    islands.sort_by_key(|island| island.len());
                }
                "desc" => {
                    // Descending: largest islands first (default)
                    islands.sort_by_key(|island| std::cmp::Reverse(island.len()));
                }
                _ => {
                    return Err(anyhow::anyhow!(
                        "Invalid sort order '{}'. Supported: asc, desc",
                        sort_order
                    ));
                }
            }

            let _filtered_count = total_components - islands.len();
            let total_after_filter = islands.len();

            // Apply offset pagination
            let offset_val = offset.unwrap_or(0);
            if offset_val > 0 && offset_val < islands.len() {
                islands = islands.into_iter().skip(offset_val).collect();
            } else if offset_val >= islands.len() {
                islands.clear();
            }

            // Apply limit (default 200)
            let limit_val = limit.unwrap_or(200);
            islands.truncate(limit_val);

            let count = islands.len();
            let has_more = offset_val + count < total_after_filter;

            // Get all file IDs from all islands
            let file_ids: Vec<i64> = islands
                .iter()
                .flat_map(|island| island.iter())
                .copied()
                .collect();
            let paths = deps_index.get_file_paths(&file_ids)?;

            // Build result (array of islands with paths, no file_ids)
            let results: Vec<serde_json::Value> = islands
                .iter()
                .enumerate()
                .map(|(idx, island)| {
                    let island_paths: Vec<_> = island
                        .iter()
                        .filter_map(|id| paths.get(id).cloned())
                        .collect();
                    json!({
                        "island_id": idx + 1,
                        "size": island.len(),
                        "paths": island_paths,
                    })
                })
                .collect();

            let response = json!({
                "pagination": {
                    "total": total_after_filter,
                    "count": count,
                    "offset": offset_val,
                    "limit": limit_val,
                    "has_more": has_more,
                },
                "results": results,
            });

            Ok(make_tool_result(response))
        }
        "analyze_summary" => {
            let min_dependents = arguments["min_dependents"]
                .as_u64()
                .map(|n| n as usize)
                .unwrap_or(2);

            let cache = CacheManager::new(".");
            let deps_index = DependencyIndex::new(cache);

            let cycles = deps_index.detect_circular_dependencies()?;
            let hotspots = deps_index.find_hotspots(None, min_dependents)?;
            let unused = deps_index.find_unused_files()?;
            let all_islands = deps_index.find_islands()?;

            let summary = json!({
                "circular_dependencies": cycles.len(),
                "hotspots": hotspots.len(),
                "unused_files": unused.len(),
                "islands": all_islands.len(),
                "min_dependents": min_dependents,
            });

            Ok(make_tool_result(summary))
        }
        "gather_context" => {
            // Parse optional parameters
            let structure = arguments["structure"].as_bool().unwrap_or(false);
            let file_types = arguments["file_types"].as_bool().unwrap_or(false);
            let project_type = arguments["project_type"].as_bool().unwrap_or(false);
            let framework = arguments["framework"].as_bool().unwrap_or(false);
            let entry_points = arguments["entry_points"].as_bool().unwrap_or(false);
            let test_layout = arguments["test_layout"].as_bool().unwrap_or(false);
            let config_files = arguments["config_files"].as_bool().unwrap_or(false);
            let depth = arguments["depth"].as_u64().map(|n| n as usize).unwrap_or(2);
            let path = arguments["path"].as_str().map(|s| s.to_string());

            // Build context options
            let mut opts = crate::context::ContextOptions {
                structure,
                path,
                file_types,
                project_type,
                framework,
                entry_points,
                test_layout,
                config_files,
                depth,
                json: false, // MCP always returns text format
            };

            // If no context flags specified, return minimal orientation context only.
            // Requesting all types by default floods agent context windows (2000-5000 tokens).
            let no_flags_set = opts.is_empty();
            if no_flags_set {
                opts.project_type = true;
                opts.entry_points = true;
            }

            let cache = CacheManager::new(".");
            let context = crate::context::generate_context(&cache, &opts)?;

            let hint = if no_flags_set {
                "\n\n---\nHint: this is the minimal orientation view. Pass any combination of these flags for more detail: structure, file_types, framework, test_layout, config_files."
            } else {
                ""
            };

            // gather_context returns human-readable prose, not JSON. Running it
            // through make_tool_result would JSON-encode (quote + escape) the text
            // and change content[text]; instead keep content[text] as the raw
            // string (REF-215: content[text] only, no structuredContent).
            let context_text = format!("{}{}", context, hint);
            let result = json!({
                "content": [{
                    "type": "text",
                    "text": context_text
                }]
            });
            Ok(result)
        }
        "check_index_status" => {
            let cache = CacheManager::new(".");

            if !cache.exists() {
                let result = json!({
                    "status": "missing",
                    "action_required": "rfx index"
                });
                return Ok(make_tool_result(result));
            }

            let engine = QueryEngine::new(cache);
            let (status, _can_trust, warning) = engine.get_index_status()?;

            let status_str = match status {
                IndexStatus::Fresh => "fresh",
                IndexStatus::Stale => "stale",
            };

            let result = if let Some(w) = warning {
                let mut obj = json!({
                    "status": status_str,
                    "reason": w.reason,
                    "action_required": w.action_required
                });
                if let Some(fm) = w.files_modified {
                    obj["files_modified"] = json!(fm);
                }
                obj
            } else {
                json!({ "status": status_str })
            };

            Ok(make_tool_result(result))
        }
        "find_references" => {
            let pattern = arguments["pattern"]
                .as_str()
                .ok_or_else(|| anyhow::anyhow!("Missing pattern"))?
                .to_string();

            let lang = arguments["lang"].as_str().map(|s| s.to_string());
            let kind = arguments["kind"].as_str().map(|s| s.to_string());
            let limit = arguments["limit"].as_u64().map(|n| n as usize);
            let offset = arguments["offset"].as_u64().map(|n| n as usize);
            let glob_patterns: Vec<String> = arguments["glob"]
                .as_array()
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                        .collect()
                })
                .unwrap_or_default();
            let exclude_patterns: Vec<String> = arguments["exclude"]
                .as_array()
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                        .collect()
                })
                .unwrap_or_default();
            let force = arguments["force"].as_bool().unwrap_or(false);
            let include_strings = arguments["include_strings"].as_bool().unwrap_or(false);

            let language = parse_language(lang);
            let parsed_kind = parse_symbol_kind(kind);

            let mode = arguments["mode"].as_str().unwrap_or("list");

            // Count mode: skip the definition lookup and just count textual references.
            if mode == "count" {
                let count_filter = QueryFilter {
                    language,
                    kind: None,
                    use_ast: false,
                    use_regex: false,
                    limit: None, // count everything
                    symbols_mode: false,
                    expand: false,
                    file_pattern: None,
                    exact: false,
                    use_contains: false,
                    timeout_secs: 30,
                    glob_patterns,
                    exclude_patterns,
                    paths_only: false,
                    offset: None,
                    force,
                    suppress_output: true,
                    include_dependencies: false,
                    ..Default::default()
                };
                let cache = CacheManager::new(".");
                let engine = QueryEngine::new(cache);
                let response = engine.search_with_metadata(&pattern, count_filter)?;
                let result = json!({"count": response.pagination.total, "pattern": pattern});
                return Ok(make_tool_result(result));
            }

            // Search 1: Find symbol definition (symbols_mode=true, small cap)
            let def_filter = QueryFilter {
                language,
                kind: parsed_kind,
                use_ast: false,
                use_regex: false,
                limit: Some(5),
                symbols_mode: true,
                expand: false,
                file_pattern: None,
                exact: false,
                use_contains: false,
                timeout_secs: 30,
                glob_patterns: glob_patterns.clone(),
                exclude_patterns: exclude_patterns.clone(),
                paths_only: false,
                offset: None,
                force,
                suppress_output: true,
                include_dependencies: false,
                ..Default::default()
            };

            let cache = CacheManager::new(".");
            let engine = QueryEngine::new(cache);
            let def_response = engine.search_with_metadata(&pattern, def_filter)?;

            // Extract first definition as a compact object (reuse MatchResult's Serialize impl)
            let definition: Option<serde_json::Value> =
                def_response.results.first().and_then(|fg| {
                    fg.matches.first().map(|m| {
                        let mut def_obj = serde_json::to_value(m).unwrap_or(json!({}));
                        if let serde_json::Value::Object(ref mut map) = def_obj {
                            map.insert("path".to_string(), json!(fg.path.clone()));
                            // Truncate preview if present
                            if let Some(preview) = map.get("preview").and_then(|v| v.as_str()) {
                                let truncated = crate::cli::truncate_preview(
                                    preview,
                                    DEFAULT_MCP_PREVIEW_LENGTH,
                                );
                                map.insert("preview".to_string(), json!(truncated));
                            }
                        }
                        def_obj
                    })
                });

            // Search 2: Find all textual references (symbols_mode=false)
            let ref_filter = QueryFilter {
                language,
                kind: None,
                use_ast: false,
                use_regex: false,
                // REF-191: default to the one-call page size so "find all callers"
                // returns the full set instead of paginating at 50.
                limit: limit.map(|l| l.min(500)).or(Some(DEFAULT_MCP_RESULT_LIMIT)),
                symbols_mode: false,
                expand: false,
                file_pattern: None,
                exact: false,
                use_contains: false,
                timeout_secs: 30,
                glob_patterns,
                exclude_patterns,
                paths_only: false,
                offset,
                force,
                suppress_output: true,
                include_dependencies: false,
                ..Default::default()
            };

            let ref_response = engine.search_with_metadata(&pattern, ref_filter)?;

            // Flatten references to compact {path, line, preview} array,
            // excluding matches inside string literals or comments (unless include_strings).
            let references: Vec<serde_json::Value> = ref_response.results.iter()
                .flat_map(|fg| {
                    fg.matches.iter()
                        .filter(|m| {
                            include_strings
                                || !is_in_string_or_comment(fg.language, &m.preview, &pattern)
                        })
                        .map(move |m| {
                            json!({
                                "path": fg.path,
                                "line": m.span.start_line,
                                "preview": crate::cli::truncate_preview(&m.preview, DEFAULT_MCP_PREVIEW_LENGTH)
                            })
                        })
                })
                .collect();

            let total_references = references.len();
            let has_more = ref_response.pagination.has_more;
            let returned_count = references.len();

            let response = json!({
                "status": ref_response.status,
                "definition": definition,
                "references": references,
                "total_references": total_references,
                "total_count": total_references,
                "returned_count": returned_count,
                "has_more": has_more,
                "pagination": ref_response.pagination,
            });

            Ok(make_tool_result(response))
        }
        _ => Err(anyhow::anyhow!("Unknown tool: {}", name)),
    }
}

/// Process a single JSON-RPC request
fn process_request(request: JsonRpcRequest, enable_structural: bool) -> JsonRpcResponse {
    log::debug!("MCP request: method={}", request.method);

    let result = match request.method.as_str() {
        "initialize" => handle_initialize(request.params),
        "tools/list" => handle_list_tools(request.params, enable_structural),
        "tools/call" => handle_call_tool(request.params),
        _ => Err(anyhow::anyhow!("Unknown method: {}", request.method)),
    };

    match result {
        Ok(value) => JsonRpcResponse {
            jsonrpc: "2.0".to_string(),
            id: request.id,
            result: Some(value),
            error: None,
        },
        Err(e) => {
            log::error!("MCP error: {}", e);
            let msg = e.to_string();
            // REF-67: map to the correct JSON-RPC error code instead of always using -32603.
            let (code, kind, message) =
                if let Some(re) = e.downcast_ref::<crate::errors::ReflexError>() {
                    let code = match re {
                        crate::errors::ReflexError::QuerySyntaxError(_) => -32602, // Invalid params
                        _ => -32603,                                               // Internal error
                    };
                    (code, re.kind().to_string(), re.to_string())
                } else if msg.starts_with("Unknown method:") {
                    (-32601, "MethodNotFound".to_string(), msg)
                } else if msg.starts_with("Missing")
                    || msg.starts_with("Unknown tool:")
                    || msg.starts_with("Invalid or unsupported")
                {
                    (-32602, "InvalidParams".to_string(), msg)
                } else {
                    (-32603, "InternalError".to_string(), msg)
                };
            JsonRpcResponse {
                jsonrpc: "2.0".to_string(),
                id: request.id,
                result: None,
                error: Some(JsonRpcError {
                    code,
                    message: message.clone(),
                    data: Some(json!({ "kind": kind })),
                }),
            }
        }
    }
}

/// Handle a JSON-RPC Notification. Notifications never receive a response.
fn handle_notification(method: &str, _params: Option<Value>) {
    match method {
        "notifications/initialized" | "notifications/cancelled" => {
            log::debug!("MCP notification: {}", method);
        }
        other => {
            log::debug!("MCP unknown notification: {}", other);
        }
    }
}

/// Run the MCP server on stdio.
pub fn run_mcp_server() -> Result<()> {
    let stdin = io::stdin();
    let stdout = io::stdout();
    run_mcp_server_io(stdin.lock(), stdout.lock())
}

/// Run the MCP server reading JSON-RPC messages from `reader` and writing
/// responses to `writer`. Exposed at crate-level for integration tests.
pub fn run_mcp_server_io<R: BufRead, W: Write>(reader: R, writer: W) -> Result<()> {
    let mcp_config = load_mcp_config();
    run_mcp_server_io_impl(reader, writer, mcp_config.enable_structural_tools)
}

/// Inner server loop. Accepts `enable_structural` so tests can drive the flag
/// without touching the filesystem.
fn run_mcp_server_io_impl<R: BufRead, W: Write>(
    reader: R,
    mut writer: W,
    enable_structural: bool,
) -> Result<()> {
    log::info!("Starting Reflex MCP server on stdio");

    // REF-212: unconditional stderr diagnostic (NOT gated behind RUST_LOG) so the
    // resolved runtime flags are always captured in Claude Code's mcp-logs. This
    // is the verification hook for efficacy trials: it proves which behaviour the
    // running binary actually honoured and pins the exact build it came from.
    eprintln!(
        "{}",
        startup_flags_line(columnar_enabled(), enable_structural)
    );

    for line in reader.lines() {
        let line = line?;

        // Skip empty lines
        if line.trim().is_empty() {
            continue;
        }

        log::debug!("MCP input: {}", line);

        // Parse JSON-RPC message
        let request: JsonRpcRequest = match serde_json::from_str(&line) {
            Ok(req) => req,
            Err(e) => {
                log::error!("Failed to parse JSON-RPC request: {}", e);
                // REF-61: send -32700 Parse error instead of silently dropping.
                // Per JSON-RPC 2.0, use null id when the id cannot be determined.
                let error_response = JsonRpcResponse {
                    jsonrpc: "2.0".to_string(),
                    id: Some(Value::Null),
                    result: None,
                    error: Some(JsonRpcError {
                        code: -32700,
                        message: format!("Parse error: {}", e),
                        data: None,
                    }),
                };
                let response_json = serde_json::to_string(&error_response)?;
                writeln!(writer, "{}", response_json)?;
                writer.flush()?;
                continue;
            }
        };

        // Notifications (no `id`) must not receive a response per JSON-RPC 2.0.
        if request.id.is_none() {
            handle_notification(&request.method, request.params);
            continue;
        }

        // Process request and write response
        let response = process_request(request, enable_structural);
        let response_json = serde_json::to_string(&response)?;
        writeln!(writer, "{}", response_json)?;
        writer.flush()?;

        log::debug!("MCP output: {}", response_json);
    }

    log::info!("Reflex MCP server stopped");
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Cursor;

    fn call_server(input: &str) -> String {
        call_server_with_structural(input, true)
    }

    fn call_server_with_structural(input: &str, enable_structural: bool) -> String {
        let reader = Cursor::new(input.as_bytes());
        let mut output = Vec::new();
        run_mcp_server_io_impl(reader, &mut output, enable_structural).unwrap();
        String::from_utf8(output).unwrap()
    }

    fn parse_first_response(raw: &str) -> serde_json::Value {
        let line = raw.lines().next().expect("no response line");
        serde_json::from_str(line).expect("invalid JSON response")
    }

    // REF-61: malformed JSON must return -32700 Parse error (not silence)
    #[test]
    fn test_parse_error_returns_32700() {
        let raw = call_server("not-valid-json\n");
        let resp = parse_first_response(&raw);
        assert_eq!(resp["jsonrpc"], "2.0");
        assert_eq!(resp["error"]["code"], -32700);
        // Per JSON-RPC 2.0, id must be null when id cannot be determined
        assert!(resp["id"].is_null(), "id must be null for parse errors");
    }

    // REF-67: unknown method returns -32601 (Method not found)
    #[test]
    fn test_unknown_method_returns_32601() {
        let req = r#"{"jsonrpc":"2.0","id":1,"method":"no_such_method","params":null}"#;
        let raw = call_server(&format!("{}\n", req));
        let resp = parse_first_response(&raw);
        assert_eq!(resp["error"]["code"], -32601);
    }

    // REF-67: missing required param returns -32602 (Invalid params), not -32603
    #[test]
    fn test_missing_param_returns_32602() {
        // search_code requires "pattern" — omit it
        let req = r#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"search_code","arguments":{}}}"#;
        let raw = call_server(&format!("{}\n", req));
        let resp = parse_first_response(&raw);
        assert_eq!(resp["error"]["code"], -32602);
    }

    // Notification (no id) must produce no response
    #[test]
    fn test_notification_produces_no_response() {
        let notif = r#"{"jsonrpc":"2.0","method":"notifications/initialized","params":null}"#;
        let raw = call_server(&format!("{}\n", notif));
        assert!(
            raw.trim().is_empty(),
            "notification must not get a response"
        );
    }

    // REF-197: initialize handshake must carry the MCP `instructions` field that
    // nudges clients to prefer reflex tools (moved out of the per-repo CLAUDE.md).
    //
    // Stage 1 of the client-agnostic instructions rewrite: the universal base
    // directive must be present, must name the `index_project` recovery step,
    // and must carry the "prefer Reflex over Grep/Glob/ripgrep" directive.
    // The Claude-Code-specific `mcp__reflex__` addendum is no longer emitted on
    // a generic `clientInfo.name` — see Stage 2's gated-addendum tests.
    #[test]
    fn test_initialize_includes_instructions() {
        let req = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1"}}}"#;
        let raw = call_server(&format!("{}\n", req));
        let resp = parse_first_response(&raw);

        let instructions = resp["result"]["instructions"]
            .as_str()
            .expect("instructions must be a string");
        assert!(!instructions.is_empty(), "instructions must be non-empty");
        assert!(
            instructions.contains("index_project"),
            "instructions must mention the index_project recovery step"
        );
        assert!(
            instructions.to_lowercase().contains("prefer"),
            "instructions must carry the prefer-Reflex directive"
        );
        assert!(
            instructions.to_lowercase().contains("grep"),
            "instructions must name the native tools Reflex replaces (grep/glob/ripgrep)"
        );
        // The Claude-Code-isms (`mcp__reflex__`, ToolSearch) are gated behind the
        // addendum path (Stage 2). A generic client must NOT receive them.
        assert!(
            !instructions.contains("mcp__reflex__"),
            "generic client must not receive the Claude-Code addendum"
        );
        assert!(
            !instructions.contains("ToolSearch"),
            "generic client must not receive the Claude-Code ToolSearch nudge"
        );

        // Pre-existing handshake fields must be unchanged.
        assert_eq!(resp["result"]["protocolVersion"], "2025-11-25");
        assert_eq!(resp["result"]["serverInfo"]["name"], "reflex");
    }

    // REF-215: make_tool_result must emit ONLY the spec-guaranteed content[text]
    // JSON string — no structuredContent key. Dropped per the REF-196 board
    // decision so no client can consume both fields and double-count tokens.
    #[test]
    fn test_make_tool_result_content_text_only() {
        let data = json!({"status": "fresh", "count": 3});
        let result = super::make_tool_result(data.clone());

        // No structuredContent key anywhere in the result.
        assert!(
            result.get("structuredContent").is_none(),
            "make_tool_result must not emit structuredContent (REF-215): {result}"
        );

        // content[text] is the data serialized as a JSON string and round-trips
        // back to the original object.
        assert_eq!(result["content"][0]["type"], "text");
        let text = result["content"][0]["text"]
            .as_str()
            .expect("content[0].text must be a string");
        let roundtrip: serde_json::Value =
            serde_json::from_str(text).expect("content[text] must be valid JSON");
        assert_eq!(roundtrip, data);

        // The result object carries exactly the `content` key and nothing else,
        // so the tool-result shape is strictly content[text]-only.
        assert_eq!(
            result.as_object().map(|o| o.len()),
            Some(1),
            "result must contain only the `content` key: {result}"
        );
    }

    // REF-209: columnar output is the shipped default unless a caller opts out.
    #[test]
    fn test_columnar_enabled_default_on() {
        // Relies on REFLEX_MCP_COLUMNAR being unset in the harness environment.
        assert!(super::columnar_enabled());
    }

    // REF-212: the startup diagnostic must faithfully report every resolved flag
    // plus build provenance, so a stale binary or an un-honoured env toggle is
    // visible in Claude Code's mcp-logs for any trial.
    #[test]
    fn test_startup_flags_line_reports_resolved_flags() {
        // REF-215: only columnar + structural_tools remain (structuredContent /
        // sc_stage2 were removed along with the env vars that drove them).
        let line = super::startup_flags_line(false, true);
        assert!(line.starts_with("reflex-mcp startup:"), "line: {line}");
        assert!(line.contains("columnar=off"), "line: {line}");
        assert!(line.contains("structural_tools=on"), "line: {line}");
        // Build provenance present so an out-of-date rfx is identifiable.
        assert!(line.contains("build="), "line: {line}");
        // The removed flags must not reappear in the diagnostic.
        assert!(!line.contains("structuredContent"), "line: {line}");
        assert!(!line.contains("sc_stage2"), "line: {line}");

        // Inverting every flag flips exactly the on/off tokens.
        let off = super::startup_flags_line(true, false);
        assert!(off.contains("columnar=on"), "line: {off}");
        assert!(off.contains("structural_tools=off"), "line: {off}");
    }

    /// A representative two-file list-mode search response (post-flattening),
    /// mixing a symbol match and a plain-text match.
    fn sample_search_response() -> serde_json::Value {
        json!({
            "status": "fresh",
            "pagination": {"total": 2, "count": 2, "offset": 0, "limit": 200, "has_more": false},
            "results": [
                {
                    "path": "src/mcp.rs",
                    "language": "rust",
                    "matches": [
                        {"kind": "Function", "symbol": "make_tool_result",
                         "span": {"start_line": 955, "end_line": 957}, "preview": "fn make_tool_result"}
                    ]
                },
                {
                    "path": "src/query.rs",
                    "language": "rust",
                    "matches": [
                        {"span": {"start_line": 10, "end_line": 10}, "preview": "let x = 1;"},
                        {"span": {"start_line": 20, "end_line": 20}, "preview": "let y = 2;"}
                    ]
                }
            ],
            "total_count": 2,
            "returned_count": 2,
            "has_more": false
        })
    }

    // REF-209: `results` array is replaced by columns/rows; one row per match.
    #[test]
    fn test_to_columnar_reshapes_results() {
        let out = super::to_columnar(sample_search_response());

        // `results` is gone, replaced by `columns` + `rows`.
        assert!(out.get("results").is_none(), "results must be removed");
        let columns = out["columns"].as_array().expect("columns array");
        let rows = out["rows"].as_array().expect("rows array");

        // The five base columns always lead; kind/symbol appended because one
        // match carries them. No context columns (none present).
        let col_names: Vec<&str> = columns.iter().filter_map(|c| c.as_str()).collect();
        assert_eq!(
            col_names,
            vec![
                "path",
                "language",
                "start_line",
                "end_line",
                "preview",
                "kind",
                "symbol"
            ]
        );

        // One row per match across all files (1 + 2 = 3).
        assert_eq!(rows.len(), 3);

        // Symbol row is fully populated and positionally aligned to columns.
        assert_eq!(
            rows[0],
            json!([
                "src/mcp.rs",
                "rust",
                955,
                957,
                "fn make_tool_result",
                "Function",
                "make_tool_result"
            ])
        );
        // Plain-text rows carry null in the trailing optional columns.
        assert_eq!(
            rows[1],
            json!(["src/query.rs", "rust", 10, 10, "let x = 1;", null, null])
        );
        assert_eq!(
            rows[2],
            json!(["src/query.rs", "rust", 20, 20, "let y = 2;", null, null])
        );
    }

    // REF-209: top-level metadata (status/pagination/scalars) survives the reshape.
    #[test]
    fn test_to_columnar_preserves_metadata() {
        let out = super::to_columnar(sample_search_response());
        assert_eq!(out["status"], "fresh");
        assert_eq!(out["total_count"], 2);
        assert_eq!(out["returned_count"], 2);
        assert_eq!(out["has_more"], false);
        assert_eq!(out["pagination"]["total"], 2);
        assert_eq!(out["pagination"]["limit"], 200);
    }

    // REF-209: a pure full-text result (no kind/symbol/context) stays at the five
    // base columns — no all-null padding claws back the token saving.
    #[test]
    fn test_to_columnar_omits_absent_optional_columns() {
        let data = json!({
            "status": "fresh",
            "pagination": {"total": 1, "count": 1, "offset": 0, "limit": 200, "has_more": false},
            "results": [{
                "path": "a.rs", "language": "rust",
                "matches": [{"span": {"start_line": 1, "end_line": 1}, "preview": "struct X"}]
            }],
            "total_count": 1, "returned_count": 1, "has_more": false
        });
        let out = super::to_columnar(data);
        let col_names: Vec<&str> = out["columns"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|c| c.as_str())
            .collect();
        assert_eq!(
            col_names,
            vec!["path", "language", "start_line", "end_line", "preview"]
        );
        assert_eq!(out["rows"][0], json!(["a.rs", "rust", 1, 1, "struct X"]));
    }

    // REF-209: context columns appear only when a match carries context lines.
    #[test]
    fn test_to_columnar_includes_context_columns_when_present() {
        let data = json!({
            "status": "fresh",
            "pagination": {"total": 1, "count": 1, "offset": 0, "limit": 200, "has_more": false},
            "results": [{
                "path": "a.rs", "language": "rust",
                "matches": [{
                    "span": {"start_line": 5, "end_line": 5}, "preview": "hit",
                    "context_before": ["above"], "context_after": ["below"]
                }]
            }],
            "total_count": 1, "returned_count": 1, "has_more": false
        });
        let out = super::to_columnar(data);
        let col_names: Vec<&str> = out["columns"]
            .as_array()
            .unwrap()
            .iter()
            .filter_map(|c| c.as_str())
            .collect();
        assert_eq!(
            col_names,
            vec![
                "path",
                "language",
                "start_line",
                "end_line",
                "preview",
                "context_before",
                "context_after"
            ]
        );
        assert_eq!(
            out["rows"][0],
            json!(["a.rs", "rust", 5, 5, "hit", ["above"], ["below"]])
        );
    }

    // REF-209: count-mode / non-results shapes pass through untouched, so
    // `to_columnar` is safe to call on any success value.
    #[test]
    fn test_to_columnar_passthrough_non_results() {
        let count = json!({"count": 7, "pattern": "foo"});
        assert_eq!(super::to_columnar(count.clone()), count);

        let scalar = json!("not an object");
        assert_eq!(super::to_columnar(scalar.clone()), scalar);
    }

    // REF-200: tool schemas must advertise the correct default limit (200, raised from 50 in REF-191) and max cap (500)
    #[test]
    fn test_tool_schema_limit_defaults() {
        let req = r#"{"jsonrpc":"2.0","id":5,"method":"tools/list","params":null}"#;
        let raw = call_server(&format!("{}\n", req));
        let resp = parse_first_response(&raw);
        let tools = resp["result"]["tools"].as_array().expect("tools array");

        let find_tool = |name: &str| {
            tools
                .iter()
                .find(|t| t["name"] == name)
                .unwrap_or_else(|| panic!("tool '{}' not found", name))
        };

        for tool_name in &["search_code", "search_regex", "find_references"] {
            let tool = find_tool(tool_name);
            let limit_desc = tool["inputSchema"]["properties"]["limit"]["description"]
                .as_str()
                .unwrap_or_else(|| panic!("{}: missing limit description", tool_name));
            assert!(
                limit_desc.contains("200"),
                "{}: limit description should mention default 200, got: {}",
                tool_name,
                limit_desc
            );
            assert!(
                limit_desc.contains("500"),
                "{}: limit description should mention max 500, got: {}",
                tool_name,
                limit_desc
            );
        }
    }

    // REF-189: structural tools absent when enable_structural_tools = false
    #[test]
    fn test_structural_tools_gated_by_flag() {
        const STRUCTURAL: &[&str] = &[
            "find_circular",
            "find_islands",
            "find_unused",
            "analyze_summary",
            "get_transitive_deps",
        ];
        const ALWAYS_ON: &[&str] = &["search_code", "find_hotspots", "get_dependencies"];

        let req = r#"{"jsonrpc":"2.0","id":10,"method":"tools/list","params":null}"#;

        // Default (structural enabled): all 5 structural tools present
        let raw_on = call_server_with_structural(&format!("{}\n", req), true);
        let resp_on = parse_first_response(&raw_on);
        let tools_on = resp_on["result"]["tools"].as_array().expect("tools array");
        let names_on: Vec<&str> = tools_on.iter().filter_map(|t| t["name"].as_str()).collect();
        for name in STRUCTURAL {
            assert!(
                names_on.contains(name),
                "structural tool '{}' should appear when flag=true",
                name
            );
        }

        // Disabled: structural tools absent, day-to-day tools still present
        let raw_off = call_server_with_structural(&format!("{}\n", req), false);
        let resp_off = parse_first_response(&raw_off);
        let tools_off = resp_off["result"]["tools"].as_array().expect("tools array");
        let names_off: Vec<&str> = tools_off
            .iter()
            .filter_map(|t| t["name"].as_str())
            .collect();
        for name in STRUCTURAL {
            assert!(
                !names_off.contains(name),
                "structural tool '{}' must be absent when flag=false",
                name
            );
        }
        for name in ALWAYS_ON {
            assert!(
                names_off.contains(name),
                "always-on tool '{}' must remain when flag=false",
                name
            );
        }
    }

    // REF-186: find_references should filter string/comment matches by default
    #[test]
    fn test_is_in_string_or_comment_filters_comment() {
        // Pattern inside a Rust single-line comment should be filtered
        let line = "let x = 5; // extract_symbols here";
        assert!(
            super::is_in_string_or_comment(crate::models::Language::Rust, line, "extract_symbols"),
            "pattern in comment should be classified as non-code"
        );
    }

    #[test]
    fn test_is_in_string_or_comment_filters_string_literal() {
        // Pattern inside a string literal should be filtered
        let line = r#"let s = "extract_symbols";"#;
        assert!(
            super::is_in_string_or_comment(crate::models::Language::Rust, line, "extract_symbols"),
            "pattern in string literal should be classified as non-code"
        );
    }

    #[test]
    fn test_is_in_string_or_comment_keeps_real_code() {
        // Pattern in real code should NOT be filtered
        let line = "fn extract_symbols(source: &str) -> Vec<SearchResult> {";
        assert!(
            !super::is_in_string_or_comment(crate::models::Language::Rust, line, "extract_symbols"),
            "real function name should not be classified as non-code"
        );
    }

    #[test]
    fn test_is_in_string_or_comment_mixed_line_keeps_match() {
        // When a line has the pattern both in a string AND in real code, the match
        // should be kept (conservative: real code occurrence wins)
        let line = r#"let _s = "extract_symbols"; extract_symbols(data);"#;
        assert!(
            !super::is_in_string_or_comment(crate::models::Language::Rust, line, "extract_symbols"),
            "when pattern appears in code on the same line, match should be kept"
        );
    }

    #[test]
    fn test_is_in_string_or_comment_unknown_language_keeps_match() {
        // Unknown language has no filter — always keep the match (conservative)
        let line = "extract_symbols in some unknown syntax";
        assert!(
            !super::is_in_string_or_comment(
                crate::models::Language::Unknown,
                line,
                "extract_symbols"
            ),
            "unknown language should never filter matches"
        );
    }

    #[test]
    fn test_find_references_schema_has_include_strings() {
        let tools_json =
            call_server(r#"{"jsonrpc":"2.0","id":1,"method":"tools/list","params":null}"#);
        let resp = parse_first_response(&tools_json);
        let tools = resp["result"]["tools"].as_array().expect("tools array");
        let find_refs = tools
            .iter()
            .find(|t| t["name"] == "find_references")
            .expect("find_references tool");
        let props = &find_refs["inputSchema"]["properties"];
        assert!(
            !props["include_strings"].is_null(),
            "find_references inputSchema must expose include_strings parameter"
        );
    }

    // REF-187: search_code, search_regex, and find_references must expose mode parameter
    #[test]
    fn test_count_mode_schema_exposed_on_search_tools() {
        let raw = call_server(r#"{"jsonrpc":"2.0","id":1,"method":"tools/list","params":null}"#);
        let resp = parse_first_response(&raw);
        let tools = resp["result"]["tools"].as_array().expect("tools array");

        for tool_name in &["search_code", "search_regex", "find_references"] {
            let tool = tools
                .iter()
                .find(|t| t["name"] == *tool_name)
                .unwrap_or_else(|| panic!("tool '{}' not found", tool_name));
            let props = &tool["inputSchema"]["properties"];
            assert!(
                !props["mode"].is_null(),
                "'{}' inputSchema must expose 'mode' parameter (REF-187)",
                tool_name
            );
            let enum_vals = props["mode"]["enum"]
                .as_array()
                .unwrap_or_else(|| panic!("'{}' mode must have enum values", tool_name));
            let vals: Vec<&str> = enum_vals.iter().filter_map(|v| v.as_str()).collect();
            assert!(
                vals.contains(&"count") && vals.contains(&"list"),
                "'{}' mode enum must contain 'count' and 'list', got {:?}",
                tool_name,
                vals
            );
        }
    }

    // REF-187: count mode must return {count, pattern} without match bodies
    // This test verifies the handler shape via a missing-index path (schema-level only,
    // since integration tests with a real index live in tests/).
    #[test]
    fn test_count_mode_missing_required_param_still_returns_32602() {
        // Ensure count mode parsing doesn't interfere with required param validation.
        let req = r#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"search_code","arguments":{"mode":"count"}}}"#;
        let raw = call_server(&format!("{}\n", req));
        let resp = parse_first_response(&raw);
        // Missing pattern → must still return InvalidParams (-32602), not a crash
        assert_eq!(
            resp["error"]["code"], -32602,
            "count mode must not bypass required-param validation"
        );
    }
}