1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use tracing::{debug, warn};
use url::Url;
/// MCP Configuration structure for reading from IDE config files
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct MCPConfig {
/// List of MCP server configurations from IDE config files
pub servers: Option<Vec<MCPServerConfig>>,
/// Global configuration options
pub options: Option<MCPGlobalOptions>,
/// Authentication headers for all servers
pub auth_headers: Option<HashMap<String, String>>,
}
/// Cursor-specific MCP Configuration structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CursorMCPConfig {
/// List of MCP server configurations using Cursor's format
#[serde(rename = "mcpServers")]
pub mcp_servers: Option<HashMap<String, CursorMCPServerConfig>>,
/// Cursor's settings (if any)
pub settings: Option<HashMap<String, serde_json::Value>>,
}
/// Cursor-specific MCP server configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CursorMCPServerConfig {
/// Server command
pub command: Option<String>,
/// Server arguments
pub args: Option<Vec<String>>,
/// Working directory
pub cwd: Option<String>,
/// Environment variables
pub env: Option<HashMap<String, String>>,
/// Transport configuration
pub transport: Option<CursorTransportConfig>,
/// Server description
pub description: Option<String>,
/// Available tools
pub tools: Option<Vec<String>>,
/// Server URL (for HTTP transport)
pub url: Option<String>,
/// Authentication headers
pub headers: Option<HashMap<String, String>>,
}
/// Cursor transport configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CursorTransportConfig {
/// Transport type
#[serde(rename = "type")]
pub transport_type: Option<String>,
/// Host for HTTP transport
pub host: Option<String>,
/// Port for HTTP transport
pub port: Option<u16>,
}
/// Claude Desktop configuration structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClaudeDesktopConfig {
/// List of MCP server configurations using Claude Desktop's format
#[serde(rename = "mcpServers")]
pub mcp_servers: Option<HashMap<String, ClaudeDesktopServerConfig>>,
/// Global settings
#[serde(rename = "globalShortcut")]
pub global_shortcut: Option<String>,
/// Other settings
#[serde(flatten)]
pub other_settings: Option<HashMap<String, serde_json::Value>>,
}
/// Claude Desktop MCP server configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClaudeDesktopServerConfig {
/// Server command
pub command: Option<String>,
/// Server arguments
pub args: Option<Vec<String>>,
/// Environment variables
pub env: Option<HashMap<String, String>>,
/// Working directory
pub cwd: Option<String>,
/// Disabled flag
pub disabled: Option<bool>,
/// Server URL (for HTTP servers)
pub url: Option<String>,
/// Authentication headers
pub headers: Option<HashMap<String, String>>,
}
/// VS Code settings structure (can contain MCP configuration)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VSCodeSettings {
/// MCP servers configuration in VS Code settings
#[serde(rename = "mcp.servers")]
pub mcp_servers: Option<HashMap<String, VSCodeMCPServerConfig>>,
/// Other VS Code settings
#[serde(flatten)]
pub other_settings: Option<HashMap<String, serde_json::Value>>,
}
/// VS Code MCP server configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VSCodeMCPServerConfig {
/// Server command
pub command: Option<String>,
/// Server arguments
pub args: Option<Vec<String>>,
/// Environment variables
pub env: Option<HashMap<String, String>>,
/// Working directory
pub cwd: Option<String>,
/// Server URL
pub url: Option<String>,
/// Transport type (e.g., "http", "stdio")
#[serde(rename = "type")]
pub transport_type: Option<String>,
/// Authentication headers
pub headers: Option<HashMap<String, String>>,
}
/// New VS Code MCP configuration structure (for mcp.json files)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VSCodeMCPConfig {
/// MCP servers configuration in new VS Code format
pub servers: Option<HashMap<String, VSCodeMCPServerConfig>>,
/// Inputs configuration
pub inputs: Option<Vec<serde_json::Value>>,
}
/// VS Code MCP configuration with `VSCodeServerConfig` (for configs with description field)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VSCodeObjectMCPConfig {
/// MCP servers configuration in VS Code format with descriptions
pub servers: Option<HashMap<String, VSCodeServerConfig>>,
/// Inputs configuration
pub inputs: Option<Vec<serde_json::Value>>,
}
/// Individual MCP server configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MCPServerConfig {
/// Server name or identifier
pub name: Option<String>,
/// Server URL (optional for STDIO servers)
pub url: Option<String>,
/// Server command (for STDIO servers)
pub command: Option<String>,
/// Command arguments (for STDIO servers)
pub args: Option<Vec<String>>,
/// Environment variables
pub env: Option<HashMap<String, String>>,
/// Server description
pub description: Option<String>,
/// Authentication headers specific to this server
pub auth_headers: Option<HashMap<String, String>>,
/// Server-specific options
pub options: Option<MCPServerOptions>,
}
impl MCPServerConfig {
/// Get display URL for logging and display purposes
pub fn to_display_url(&self) -> String {
if let Some(url) = &self.url {
url.clone()
} else if let Some(command) = &self.command {
// For STDIO servers, create a more descriptive URL
if let Some(name) = &self.name {
// Include the server name if available: stdio:npx[server-name]
format!("stdio:{command}[{name}]")
} else if let Some(args) = &self.args {
// If no name but has args, show the main package/argument
if let Some(main_arg) = args.first() {
format!("stdio:{command}[{main_arg}]")
} else {
format!("stdio:{command}[unknown]")
}
} else {
format!("stdio:{command}")
}
} else {
"unknown".to_string()
}
}
/// Get actual URL for scanning (returns None for STDIO servers)
pub fn scan_url(&self) -> Option<&str> {
self.url.as_deref()
}
/// Generate a unique key for deduplication
pub fn dedup_key(&self) -> String {
if let Some(url) = &self.url {
// For HTTP servers, use normalized URL with explicit prefix to prevent collisions
format!("http:{}", MCPConfigManager::normalize_url(url))
} else {
// For STDIO servers, use name + command + args to create unique key with explicit prefix
let name = self.name.as_deref().unwrap_or("unnamed");
let command = self.command.as_deref().unwrap_or("unknown");
let args = if let Some(args) = &self.args {
args.join(" ")
} else {
String::new()
};
format!("stdio:{name}:{command}:{args}")
}
}
}
/// Global configuration options
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MCPGlobalOptions {
/// Default timeout in seconds
pub timeout: Option<u64>,
/// Default HTTP timeout in seconds
pub http_timeout: Option<u64>,
/// Default output format
pub format: Option<String>,
/// Whether to include detailed output by default
pub detailed: Option<bool>,
}
/// Server-specific options
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MCPServerOptions {
/// Server-specific timeout
pub timeout: Option<u64>,
/// Server-specific HTTP timeout
pub http_timeout: Option<u64>,
/// Server-specific output format
pub format: Option<String>,
/// Whether to include detailed output for this server
pub detailed: Option<bool>,
}
// IDE-specific configuration formats
/// VS Code MCP configuration format with array of servers
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VSCodeArrayMCPConfig {
/// Servers as array (alternative VS Code format)
pub servers: Option<Vec<VSCodeArrayServerConfig>>,
/// Inputs array
pub inputs: Option<Vec<serde_json::Value>>,
}
/// VS Code server configuration in array format
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VSCodeArrayServerConfig {
/// Server name
pub name: Option<String>,
/// Server URL (for HTTP servers)
pub url: Option<String>,
/// Command to run (for STDIO servers)
pub command: Option<String>,
/// Arguments for the command
pub args: Option<Vec<String>>,
/// Environment variables
pub env: Option<HashMap<String, String>>,
/// Server type (http, stdio, etc.)
#[serde(rename = "type")]
pub server_type: Option<String>,
/// Description
pub description: Option<String>,
/// Authentication headers
pub headers: Option<HashMap<String, String>>,
}
/// VS Code server configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VSCodeServerConfig {
/// Server type (http, stdio, etc.)
#[serde(rename = "type")]
pub server_type: Option<String>,
/// Server URL
pub url: Option<String>,
/// Command to run (for stdio servers)
pub command: Option<String>,
/// Arguments for the command
pub args: Option<Vec<String>>,
/// Environment variables
pub env: Option<HashMap<String, String>>,
/// Gallery flag
pub gallery: Option<bool>,
/// Description
pub description: Option<String>,
/// Authentication headers
pub headers: Option<HashMap<String, String>>,
}
/// Cursor server configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)]
pub struct CursorServerConfig {
pub command: String,
pub args: Vec<String>,
pub env: Option<HashMap<String, String>>,
}
/// Windsurf MCP configuration format
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WindsurfMCPConfig {
/// Servers configuration
pub servers: Option<HashMap<String, WindsurfServerConfig>>,
/// Global configuration
pub global: Option<MCPGlobalOptions>,
}
/// Windsurf server configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WindsurfServerConfig {
pub url: Option<String>,
pub command: Option<String>,
pub args: Option<Vec<String>>,
pub env: Option<HashMap<String, String>>,
#[serde(rename = "type")]
pub server_type: Option<String>,
pub description: Option<String>,
/// Authentication headers
pub headers: Option<HashMap<String, String>>,
}
/// Claude Desktop MCP configuration format
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClaudeMCPConfig {
/// MCP servers configuration
#[serde(rename = "mcpServers")]
pub mcp_servers: Option<HashMap<String, ClaudeServerConfig>>,
/// Alternative naming
pub servers: Option<HashMap<String, ClaudeServerConfig>>,
}
/// Claude Desktop server configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClaudeServerConfig {
pub command: Option<String>,
pub args: Option<Vec<String>>,
pub env: Option<HashMap<String, String>>,
pub url: Option<String>,
#[serde(rename = "type")]
pub server_type: Option<String>,
/// Authentication headers
pub headers: Option<HashMap<String, String>>,
}
/// Claude Code MCP configuration format (extracted from ~/.claude/settings.json)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClaudeCodeConfig {
/// MCP servers configuration
#[serde(rename = "mcpServers")]
pub mcp_servers: Option<HashMap<String, ClaudeCodeServerConfig>>,
}
/// Claude Code server configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClaudeCodeServerConfig {
#[serde(rename = "type")]
pub server_type: String,
pub command: String,
pub args: Vec<String>,
pub env: Option<HashMap<String, String>>,
}
/// Zed MCP configuration format
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ZedMCPConfig {
/// Context servers as array of objects
pub context_servers: Option<Vec<HashMap<String, ZedServerConfig>>>,
}
/// Zed server configuration with command object
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ZedServerConfig {
/// Command configuration
pub command: Option<ZedCommandConfig>,
/// Direct URL (for HTTP servers)
pub url: Option<String>,
/// Environment variables
pub env: Option<HashMap<String, String>>,
/// Authentication headers
pub headers: Option<HashMap<String, String>>,
}
/// Zed command configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ZedCommandConfig {
/// Path to executable
pub path: String,
/// Command arguments
pub args: Option<Vec<String>>,
}
/// Zencoder MCP configuration format (simple command-based)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ZencoderMCPConfig {
/// Command to run
pub command: String,
/// Command arguments
pub args: Option<Vec<String>>,
/// Environment variables
pub env: Option<HashMap<String, String>>,
}
// Conversion implementations
impl From<VSCodeMCPConfig> for MCPConfig {
fn from(vscode_config: VSCodeMCPConfig) -> Self {
let servers = vscode_config.servers.map(|servers_map| {
servers_map
.into_iter()
.map(|(name, server_config)| MCPServerConfig {
name: Some(name),
url: server_config.url,
command: server_config.command,
args: server_config.args,
env: server_config.env,
description: None, // VSCodeMCPServerConfig doesn't have a description field
auth_headers: server_config.headers,
options: None,
})
.collect()
});
MCPConfig {
servers,
options: None,
auth_headers: None,
}
}
}
impl From<VSCodeObjectMCPConfig> for MCPConfig {
fn from(vscode_config: VSCodeObjectMCPConfig) -> Self {
let servers = vscode_config.servers.map(|servers_map| {
servers_map
.into_iter()
.map(|(name, server_config)| MCPServerConfig {
name: Some(name),
url: server_config.url,
command: server_config.command,
args: server_config.args,
env: server_config.env,
description: server_config.description, // VSCodeServerConfig has a description field
auth_headers: server_config.headers,
options: None,
})
.collect()
});
MCPConfig {
servers,
options: None,
auth_headers: None,
}
}
}
impl From<VSCodeArrayMCPConfig> for MCPConfig {
fn from(vscode_config: VSCodeArrayMCPConfig) -> Self {
let servers = vscode_config.servers.map(|servers_vec| {
servers_vec
.into_iter()
.map(|server_config| MCPServerConfig {
name: server_config.name,
url: server_config.url,
command: server_config.command,
args: server_config.args,
env: server_config.env,
description: server_config.description,
auth_headers: server_config.headers,
options: None,
})
.collect()
});
MCPConfig {
servers,
options: None,
auth_headers: None,
}
}
}
impl From<CursorMCPConfig> for MCPConfig {
fn from(cursor_config: CursorMCPConfig) -> Self {
let servers = cursor_config.mcp_servers.map(|servers_map| {
servers_map
.into_iter()
.map(|(name, server_config)| MCPServerConfig {
name: Some(name),
url: server_config.url,
command: server_config.command,
args: server_config.args,
env: server_config.env,
description: server_config.description,
auth_headers: server_config.headers,
options: None,
})
.collect()
});
MCPConfig {
servers,
options: None,
auth_headers: None,
}
}
}
impl From<WindsurfMCPConfig> for MCPConfig {
fn from(windsurf_config: WindsurfMCPConfig) -> Self {
let servers = windsurf_config.servers.map(|servers_map| {
servers_map
.into_iter()
.map(|(name, server_config)| MCPServerConfig {
name: Some(name),
url: server_config.url,
command: server_config.command,
args: server_config.args,
env: server_config.env,
description: server_config.description,
auth_headers: server_config.headers,
options: None,
})
.collect()
});
MCPConfig {
servers,
options: windsurf_config.global,
auth_headers: None,
}
}
}
impl From<ClaudeMCPConfig> for MCPConfig {
fn from(claude_config: ClaudeMCPConfig) -> Self {
// Try mcp_servers first, then servers
let servers_map = claude_config.mcp_servers.or(claude_config.servers);
let servers = servers_map.map(|servers_map| {
servers_map
.into_iter()
.map(|(name, server_config)| MCPServerConfig {
name: Some(name),
url: server_config.url,
command: server_config.command,
args: server_config.args,
env: server_config.env,
description: None,
auth_headers: server_config.headers,
options: None,
})
.collect()
});
MCPConfig {
servers,
options: None,
auth_headers: None,
}
}
}
impl From<ClaudeCodeConfig> for MCPConfig {
fn from(claude_code_config: ClaudeCodeConfig) -> Self {
let servers = claude_code_config.mcp_servers.map(|servers_map| {
servers_map
.into_iter()
.map(|(name, server_config)| MCPServerConfig {
name: Some(name),
url: None,
command: Some(server_config.command),
args: Some(server_config.args),
env: server_config.env,
description: None,
auth_headers: None,
options: None,
})
.collect()
});
MCPConfig {
servers,
options: None,
auth_headers: None,
}
}
}
impl From<ZedMCPConfig> for MCPConfig {
fn from(zed_config: ZedMCPConfig) -> Self {
let servers = zed_config.context_servers.map(|context_servers| {
context_servers
.into_iter()
.flat_map(|server_map| {
server_map
.into_iter()
.map(|(name, server_config)| MCPServerConfig {
name: Some(name),
url: server_config.url,
command: server_config.command.as_ref().map(|cmd| cmd.path.clone()),
args: server_config
.command
.as_ref()
.and_then(|cmd| cmd.args.clone()),
env: server_config.env,
description: server_config.command.as_ref().map(|cmd| {
format!(
"Command: {} {}",
cmd.path,
cmd.args
.as_ref()
.map(|args| args.join(" "))
.unwrap_or_default()
)
}),
auth_headers: server_config.headers,
options: None,
})
})
.collect()
});
MCPConfig {
servers,
options: None,
auth_headers: None,
}
}
}
impl From<ZencoderMCPConfig> for MCPConfig {
fn from(zencoder_config: ZencoderMCPConfig) -> Self {
let servers = Some(vec![MCPServerConfig {
name: Some("zencoder".to_string()),
url: None,
command: Some(zencoder_config.command),
args: zencoder_config.args,
env: zencoder_config.env,
description: Some("Zencoder MCP server".to_string()),
auth_headers: None,
options: None,
}]);
MCPConfig {
servers,
options: None,
auth_headers: None,
}
}
}
/// Supported MCP client types
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum MCPClient {
Cursor,
Windsurf,
VSCode,
Claude,
ClaudeCode,
Gemini,
Neovim,
Helix,
Zed,
Zencoder,
}
impl MCPClient {
pub fn name(&self) -> &'static str {
match self {
MCPClient::Cursor => "cursor",
MCPClient::Windsurf => "windsurf",
MCPClient::VSCode => "vscode",
MCPClient::Claude => "claude",
MCPClient::ClaudeCode => "claude-code",
MCPClient::Gemini => "gemini",
MCPClient::Neovim => "neovim",
MCPClient::Helix => "helix",
MCPClient::Zed => "zed",
MCPClient::Zencoder => "zencoder",
}
}
}
/// Cache for discovered configuration paths to avoid repeated filesystem operations
static CONFIG_PATHS_CACHE: LazyLock<Vec<(PathBuf, MCPClient)>> =
LazyLock::new(MCPConfigManager::discover_config_paths);
/// IDE configuration file manager for MCP scanner
pub struct MCPConfigManager {
config_paths: Vec<(PathBuf, MCPClient)>,
}
impl MCPConfigManager {
/// Normalize URL for consistent deduplication
/// Removes trailing slashes, converts to lowercase, and handles localhost aliases
fn normalize_url(url: &str) -> String {
let mut normalized = url.trim().to_lowercase();
// Remove trailing slashes
if normalized.ends_with('/') && normalized != "http://" && normalized != "https://" {
normalized = normalized.trim_end_matches('/').to_string();
}
// Normalize localhost variants
normalized = normalized
.replace("127.0.0.1", "localhost")
.replace("0.0.0.0", "localhost");
// Normalize port defaults - currently no-op, but placeholder for future enhancement
if (normalized.starts_with("http://localhost")
|| normalized.starts_with("https://localhost"))
&& !normalized.contains(':')
{
// Don't add default port, keep as-is for now
}
normalized
}
/// Create a new configuration manager with platform-specific IDE config paths
pub fn new() -> Self {
Self {
config_paths: CONFIG_PATHS_CACHE.clone(),
}
}
/// Create a new configuration manager with fresh path discovery (bypasses cache)
/// Creates a new `MCPConfigManager` without using the cache
#[allow(dead_code)] // Used in tests and for bypassing cache when needed
pub fn new_uncached() -> Self {
let paths = Self::discover_config_paths();
Self {
config_paths: paths,
}
}
/// Discover MCP configuration paths based on platform and IDE
fn discover_config_paths() -> Vec<(PathBuf, MCPClient)> {
let mut paths = Vec::new();
// First, add workspace-level configurations (highest priority)
paths.extend(Self::get_workspace_paths());
// Then add platform-specific global configurations
let platform = env::consts::OS;
match platform {
"windows" => {
paths.extend(Self::get_windows_paths());
}
"macos" | "darwin" => {
paths.extend(Self::get_macos_paths());
}
_ => {
// Linux and other Unix-like systems
paths.extend(Self::get_unix_paths());
}
}
paths
}
/// Get workspace-level MCP configuration paths (current working directory and workspace)
fn get_workspace_paths() -> Vec<(PathBuf, MCPClient)> {
let mut paths = Vec::new();
// Current working directory workspace configurations
let current_dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
// VS Code workspace configurations
paths.push((
current_dir.join(".vscode").join("mcp.json"),
MCPClient::VSCode,
));
paths.push((
current_dir.join(".vscode").join("settings.json"),
MCPClient::VSCode,
));
// Cursor workspace configurations
paths.push((
current_dir.join(".cursor").join("mcp.json"),
MCPClient::Cursor,
));
paths.push((
current_dir.join(".cursor").join("settings.json"),
MCPClient::Cursor,
));
// Cursor repo-embedded MCP configuration used by some editors
// Example: .cursor/rules/mcp.json (supply-chain sensitive)
paths.push((
current_dir.join(".cursor").join("rules").join("mcp.json"),
MCPClient::Cursor,
));
// Claude Code workspace configurations
paths.push((
current_dir.join(".claude").join("settings.json"),
MCPClient::ClaudeCode,
));
paths.push((
current_dir.join(".claude").join("settings.local.json"),
MCPClient::ClaudeCode,
));
paths.push((
current_dir.join(".claude").join("mcp.json"),
MCPClient::Claude,
));
// Windsurf workspace configurations
paths.push((
current_dir.join(".windsurf").join("mcp.json"),
MCPClient::Windsurf,
));
paths.push((
current_dir.join(".windsurf").join("mcp_config.json"),
MCPClient::Windsurf,
));
// Gemini CLI workspace configurations
paths.push((
current_dir.join(".gemini").join("settings.json"),
MCPClient::Gemini,
));
// Also check parent directories up to 3 levels for project root configurations
let mut parent = current_dir.parent();
let mut level = 0;
while let Some(dir) = parent {
if level >= 3 {
break;
}
// Look for common project indicators
if dir.join(".git").exists()
|| dir.join("package.json").exists()
|| dir.join("Cargo.toml").exists()
|| dir.join("pyproject.toml").exists()
|| dir.join("requirements.txt").exists()
{
// VS Code project root configurations
paths.push((dir.join(".vscode").join("mcp.json"), MCPClient::VSCode));
paths.push((dir.join(".vscode").join("settings.json"), MCPClient::VSCode));
// Cursor project root configurations
paths.push((dir.join(".cursor").join("mcp.json"), MCPClient::Cursor));
// Cursor repo-embedded MCP configuration in project root
paths.push((
dir.join(".cursor").join("rules").join("mcp.json"),
MCPClient::Cursor,
));
// Claude Code project root configurations
paths.push((
dir.join(".claude").join("settings.json"),
MCPClient::ClaudeCode,
));
paths.push((
dir.join(".claude").join("settings.local.json"),
MCPClient::ClaudeCode,
));
paths.push((dir.join(".claude").join("mcp.json"), MCPClient::Claude));
// Windsurf project root configurations
paths.push((dir.join(".windsurf").join("mcp.json"), MCPClient::Windsurf));
paths.push((
dir.join(".windsurf").join("mcp_config.json"),
MCPClient::Windsurf,
));
// Gemini CLI project root configurations
paths.push((dir.join(".gemini").join("settings.json"), MCPClient::Gemini));
break; // Stop at first project root found
}
parent = dir.parent();
level += 1;
}
paths
}
/// Get Windows-specific MCP configuration paths
fn get_windows_paths() -> Vec<(PathBuf, MCPClient)> {
let mut paths = Vec::new();
// Try APPDATA first, then fallback to home directory
if let Ok(appdata) = env::var("APPDATA") {
let appdata_path = PathBuf::from(appdata);
// Cursor
paths.push((
appdata_path
.join("Cursor")
.join("User")
.join("globalStorage")
.join("rooveterinaryinc.cursor-mcp")
.join("mcp.json"),
MCPClient::Cursor,
));
paths.push((
appdata_path.join("Cursor").join("User").join("mcp.json"),
MCPClient::Cursor,
));
// Windsurf
paths.push((
appdata_path.join("Windsurf").join("User").join("mcp.json"),
MCPClient::Windsurf,
));
paths.push((
appdata_path
.join("Codeium")
.join("Windsurf")
.join("mcp_config.json"),
MCPClient::Windsurf,
));
// VS Code
paths.push((
appdata_path.join("Code").join("User").join("mcp.json"),
MCPClient::VSCode,
));
// Claude Desktop
paths.push((
appdata_path.join("Claude").join("mcp.json"),
MCPClient::Claude,
));
} else {
// Fallback: try LOCALAPPDATA if APPDATA is missing
if let Ok(localappdata) = env::var("LOCALAPPDATA") {
let localappdata_path = PathBuf::from(localappdata);
paths.push((
localappdata_path
.join("Cursor")
.join("User")
.join("mcp.json"),
MCPClient::Cursor,
));
paths.push((
localappdata_path
.join("Programs")
.join("Windsurf")
.join("mcp.json"),
MCPClient::Windsurf,
));
paths.push((
localappdata_path
.join("Programs")
.join("Microsoft VS Code")
.join("mcp.json"),
MCPClient::VSCode,
));
}
}
// User home directory configs (Unix-style on Windows)
if let Some(home_dir) = dirs::home_dir() {
paths.push((home_dir.join(".cursor").join("mcp.json"), MCPClient::Cursor));
paths.push((home_dir.join(".vscode").join("mcp.json"), MCPClient::VSCode));
paths.push((home_dir.join(".claude").join("mcp.json"), MCPClient::Claude));
paths.push((
home_dir.join(".claude").join("settings.json"),
MCPClient::ClaudeCode,
));
paths.push((
home_dir.join(".gemini").join("settings.json"),
MCPClient::Gemini,
));
// Windows-specific AppData fallback in user profile
let user_appdata = home_dir.join("AppData").join("Roaming");
if user_appdata.exists() {
// Cursor
paths.push((
user_appdata.join("Cursor").join("User").join("mcp.json"),
MCPClient::Cursor,
));
// VS Code
paths.push((
user_appdata.join("Code").join("User").join("mcp.json"),
MCPClient::VSCode,
));
paths.push((
user_appdata.join("Code").join("User").join("settings.json"),
MCPClient::VSCode,
));
// Claude Desktop
paths.push((
user_appdata
.join("Claude")
.join("claude_desktop_config.json"),
MCPClient::Claude,
));
// Windsurf
paths.push((
user_appdata.join("Windsurf").join("User").join("mcp.json"),
MCPClient::Windsurf,
));
paths.push((
user_appdata
.join("Codeium")
.join("Windsurf")
.join("mcp_config.json"),
MCPClient::Windsurf,
));
// Claude Code enterprise managed settings
if let Ok(program_data) = env::var("PROGRAMDATA") {
paths.push((
PathBuf::from(program_data)
.join("ClaudeCode")
.join("managed-settings.json"),
MCPClient::ClaudeCode,
));
}
}
}
paths
}
/// Get macOS-specific MCP configuration paths
fn get_macos_paths() -> Vec<(PathBuf, MCPClient)> {
let mut paths = Vec::new();
if let Some(home_dir) = dirs::home_dir() {
let app_support = home_dir.join("Library").join("Application Support");
// Cursor
paths.push((
app_support
.join("Cursor")
.join("User")
.join("globalStorage")
.join("rooveterinaryinc.cursor-mcp")
.join("mcp.json"),
MCPClient::Cursor,
));
paths.push((
app_support.join("Cursor").join("User").join("mcp.json"),
MCPClient::Cursor,
));
paths.push((home_dir.join(".cursor").join("mcp.json"), MCPClient::Cursor));
// Windsurf
paths.push((
app_support.join("Windsurf").join("User").join("mcp.json"),
MCPClient::Windsurf,
));
paths.push((
app_support
.join("Codeium")
.join("Windsurf")
.join("mcp_config.json"),
MCPClient::Windsurf,
));
paths.push((
home_dir
.join(".codeium")
.join("windsurf")
.join("mcp_config.json"),
MCPClient::Windsurf,
));
// VS Code - multiple configuration locations
paths.push((
app_support.join("Code").join("User").join("mcp.json"),
MCPClient::VSCode,
));
paths.push((
app_support.join("Code").join("User").join("settings.json"),
MCPClient::VSCode,
));
paths.push((home_dir.join(".vscode").join("mcp.json"), MCPClient::VSCode));
paths.push((
home_dir.join(".vscode").join("settings.json"),
MCPClient::VSCode,
));
// Claude Desktop - uses claude_desktop_config.json
paths.push((
app_support
.join("Claude")
.join("claude_desktop_config.json"),
MCPClient::Claude,
));
paths.push((
app_support
.join("Claude")
.join("User")
.join("claude_desktop_config.json"),
MCPClient::Claude,
));
// Claude Code - User/Global scope
paths.push((
home_dir.join(".claude").join("settings.json"),
MCPClient::ClaudeCode,
));
paths.push((home_dir.join(".claude").join("mcp.json"), MCPClient::Claude));
paths.push((
home_dir.join(".gemini").join("settings.json"),
MCPClient::Gemini,
));
// Zed
paths.push((app_support.join("Zed").join("mcp.json"), MCPClient::Zed));
// Zencoder
paths.push((
app_support.join("Zencoder").join("mcp.json"),
MCPClient::Zencoder,
));
// Claude Code enterprise managed settings
paths.push((
PathBuf::from("/Library/Application Support/ClaudeCode/managed-settings.json"),
MCPClient::ClaudeCode,
));
// Unix-style configs in home directory
let config_dir = home_dir.join(".config");
paths.push((config_dir.join("nvim").join("mcp.json"), MCPClient::Neovim));
paths.push((config_dir.join("helix").join("mcp.json"), MCPClient::Helix));
}
paths
}
/// Get Unix/Linux-specific MCP configuration paths
fn get_unix_paths() -> Vec<(PathBuf, MCPClient)> {
let mut paths = Vec::new();
if let Some(home_dir) = dirs::home_dir() {
let config_dir = home_dir.join(".config");
// Cursor
paths.push((home_dir.join(".cursor").join("mcp.json"), MCPClient::Cursor));
paths.push((
config_dir.join("Cursor").join("User").join("mcp.json"),
MCPClient::Cursor,
));
// Windsurf
paths.push((
home_dir.join(".windsurf").join("mcp.json"),
MCPClient::Windsurf,
));
paths.push((
home_dir
.join(".codeium")
.join("windsurf")
.join("mcp_config.json"),
MCPClient::Windsurf,
));
paths.push((
config_dir.join("Windsurf").join("User").join("mcp.json"),
MCPClient::Windsurf,
));
// VS Code
paths.push((home_dir.join(".vscode").join("mcp.json"), MCPClient::VSCode));
paths.push((
home_dir.join(".vscode").join("settings.json"),
MCPClient::VSCode,
));
paths.push((
config_dir.join("Code").join("User").join("mcp.json"),
MCPClient::VSCode,
));
// Claude Desktop
paths.push((home_dir.join(".claude").join("mcp.json"), MCPClient::Claude));
// Claude Code
paths.push((
home_dir.join(".claude").join("settings.json"),
MCPClient::ClaudeCode,
));
paths.push((
home_dir.join(".gemini").join("settings.json"),
MCPClient::Gemini,
));
paths.push((
config_dir.join("Code").join("User").join("settings.json"),
MCPClient::VSCode,
));
// Claude Desktop - uses claude_desktop_config.json
paths.push((
home_dir.join(".claude").join("claude_desktop_config.json"),
MCPClient::Claude,
));
paths.push((
config_dir.join("claude").join("claude_desktop_config.json"),
MCPClient::Claude,
));
// Claude Code - User/Global scope already added above
paths.push((home_dir.join(".claude").join("mcp.json"), MCPClient::Claude));
// Neovim
paths.push((config_dir.join("nvim").join("mcp.json"), MCPClient::Neovim));
// Helix
paths.push((config_dir.join("helix").join("mcp.json"), MCPClient::Helix));
// Zed
paths.push((config_dir.join("zed").join("mcp.json"), MCPClient::Zed));
// Zencoder
paths.push((
config_dir.join("zencoder").join("mcp.json"),
MCPClient::Zencoder,
));
// Claude Code enterprise managed settings
paths.push((
PathBuf::from("/etc/claude-code/managed-settings.json"),
MCPClient::ClaudeCode,
));
}
paths
}
/// Get client type from a configuration file path using component-based matching
/// Determines the MCP client type based on the configuration file path
pub fn detect_client<P: AsRef<Path>>(path: P) -> Option<MCPClient> {
let path = path.as_ref();
let components: Vec<_> = path
.components()
.filter_map(|c| c.as_os_str().to_str())
.map(str::to_lowercase)
.collect();
// Check specific file names FIRST for most precise detection
if let Some(filename) = path.file_name().and_then(|n| n.to_str()) {
match filename {
"claude_desktop_config.json" => return Some(MCPClient::Claude),
"settings.json" => {
// Check if it's in a Claude Code directory (exact match)
if components.iter().any(|c| c == ".claude") {
return Some(MCPClient::ClaudeCode);
}
// Check if it's in a VS Code directory (exact matches)
if components
.iter()
.any(|c| c == "code" || c == "vscode" || c == ".vscode")
{
return Some(MCPClient::VSCode);
}
}
"settings.local.json" if components.iter().any(|c| c == ".claude") => {
// Claude Code local settings (exact match)
return Some(MCPClient::ClaudeCode);
}
"managed-settings.json"
if components
.iter()
.any(|c| c == "claudecode" || c == "claude-code") =>
{
// Claude Code enterprise managed settings (exact component matches)
return Some(MCPClient::ClaudeCode);
}
_ => {}
}
}
// Check path components for broader matching
for component in &components {
match component.as_str() {
// Exact matches first
"cursor" | ".cursor" => return Some(MCPClient::Cursor),
"windsurf" => return Some(MCPClient::Windsurf),
"claude" | ".claude" => return Some(MCPClient::Claude),
"gemini" | ".gemini" => return Some(MCPClient::Gemini),
"zed" => return Some(MCPClient::Zed),
"zencoder" => return Some(MCPClient::Zencoder),
"helix" => return Some(MCPClient::Helix),
"nvim" | "neovim" => return Some(MCPClient::Neovim),
"code" | "vscode" | ".vscode" => return Some(MCPClient::VSCode),
// Exact path component matches (avoiding false positives)
"codeium" | ".codeium" => return Some(MCPClient::Windsurf), // Codeium directory means Windsurf context
// Partial matches with disambiguation for compound paths
c if c.starts_with("cursor") && !c.contains("vscode") => {
return Some(MCPClient::Cursor)
}
c if c == "microsoft vs code"
|| (c.contains("microsoft") && c.contains("code")) =>
{
return Some(MCPClient::VSCode)
}
_ => {} // Keep looking
}
}
// Fallback: check full path string for edge cases
let path_str = path.to_string_lossy().to_lowercase();
if path_str.contains("rooveterinaryinc.cursor-mcp") {
return Some(MCPClient::Cursor);
}
None
}
/// Load configuration from all available IDE config files
pub fn load_config(&self) -> MCPConfig {
let mut merged_config = MCPConfig::default();
let mut loaded_configs = 0;
let mut failed_configs = Vec::new();
// Only show existing config files
let existing_configs: Vec<_> = self
.config_paths
.iter()
.filter(|(path, _)| path.exists())
.collect();
if !existing_configs.is_empty() {
println!("🔍 Found {} IDE config files:", existing_configs.len());
for (path, client) in existing_configs {
println!(" ✓ {} IDE: {}", client.name(), path.display());
}
println!();
}
for (path, client) in &self.config_paths {
match Self::load_config_from_path(path) {
Ok(config) => {
// Validate configuration before merging
if let Err(validation_error) = Self::validate_config(&config) {
warn!(
"Invalid MCP configuration in {} ({}): {}",
client.name(),
path.display(),
validation_error
);
failed_configs.push((path.clone(), validation_error));
continue;
}
// Display what was found in this config file
let server_count = config.servers.as_ref().map(|s| s.len()).unwrap_or(0);
println!(
"📁 {} IDE config: {} ({} servers)",
client.name(),
path.display(),
server_count
);
if let Some(ref servers) = config.servers {
for server in servers {
let server_name = server.name.as_deref().unwrap_or("unnamed");
let server_type = if server.command.is_some() {
"STDIO"
} else {
"HTTP"
};
println!(
" └─ {} [{}]: {}",
server_name,
server_type,
server.to_display_url()
);
}
}
Self::merge_config_with_source(&mut merged_config, &config, client.name());
loaded_configs += 1;
debug!(
"Loaded MCP configuration from {} IDE: {}",
client.name(),
path.display()
);
}
Err(e) => {
if path.exists() {
// File exists but couldn't be parsed - this is an error
warn!(
"Failed to parse MCP configuration from {} IDE at {}: {}",
client.name(),
path.display(),
e
);
failed_configs.push((path.clone(), e));
} else {
// File doesn't exist - this is normal
debug!(
"No MCP configuration found for {} IDE at: {}",
client.name(),
path.display()
);
}
}
}
}
if loaded_configs == 0 && failed_configs.is_empty() {
debug!("No MCP configuration files found in any supported IDE locations");
} else if !failed_configs.is_empty() {
warn!(
"Found {} configuration files with errors",
failed_configs.len()
);
}
merged_config
}
/// Helper function to parse Cursor-compatible MCP configuration format
/// Used by Claude, Claude Code, Cursor, Windsurf, and Gemini
fn try_parse_cursor_compatible_config(content: &str, client_name: &str) -> Option<MCPConfig> {
if let Ok(cursor_config) = serde_json::from_str::<CursorMCPConfig>(content) {
debug!("Parsed as {} configuration format", client_name);
Some(Self::convert_cursor_config(cursor_config))
} else {
None
}
}
/// Returns `true` only when the parsed `MCPConfig` actually contains at
/// least one server.
///
/// Several IDE config schemas have all fields `Option`-wrapped, so a JSON
/// document keyed differently than expected (e.g., a Claude-Desktop-style
/// `{"mcpServers": ...}` file at a VS Code path) parses as a syntactically
/// valid but empty `MCPConfig`. Without this gate, the early-return in
/// `load_config_from_path` swallows that case and the caller's fallback
/// chain never runs. See ramparts#85.
fn config_has_servers(config: &MCPConfig) -> bool {
config
.servers
.as_ref()
.is_some_and(|servers| !servers.is_empty())
}
/// Load configuration from a specific IDE config path
pub fn load_config_from_path(path: &Path) -> Result<MCPConfig> {
if !path.exists() {
return Err(anyhow!(
"IDE configuration file does not exist: {}",
path.display()
));
}
let content = fs::read_to_string(path)
.map_err(|e| anyhow!("Failed to read IDE config file {}: {}", path.display(), e))?;
// Detect IDE type by checking the client type from path
let client = Self::detect_client(path);
let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
// Try parsing based on client type and file name
match client {
Some(MCPClient::Cursor) => {
if let Some(config) =
Self::try_parse_cursor_compatible_config(&content, "Cursor MCP")
{
return Ok(config);
}
}
Some(MCPClient::Claude) => {
// Claude Desktop uses claude_desktop_config.json
if filename == "claude_desktop_config.json" {
if let Ok(claude_config) = serde_json::from_str::<ClaudeDesktopConfig>(&content)
{
debug!("Parsed as Claude Desktop configuration format");
return Ok(Self::convert_claude_desktop_config(claude_config));
}
}
// Claude mcp.json files use Cursor format
else if filename == "mcp.json" {
if let Some(config) =
Self::try_parse_cursor_compatible_config(&content, "Claude MCP")
{
return Ok(config);
}
}
}
Some(MCPClient::ClaudeCode)
if filename == "settings.json" || filename == "settings.local.json" =>
{
// Claude Code uses settings.json files in .claude directory
if let Some(config) =
Self::try_parse_cursor_compatible_config(&content, "Claude Code")
{
return Ok(config);
}
}
Some(MCPClient::Windsurf) | Some(MCPClient::Gemini) => {
// Windsurf and Gemini use Cursor-compatible format
let client_name = format!("{} MCP", client.as_ref().unwrap().name());
if let Some(config) =
Self::try_parse_cursor_compatible_config(&content, &client_name)
{
return Ok(config);
}
}
Some(MCPClient::VSCode) => {
// VS Code settings.json may contain MCP configuration
if filename == "settings.json" {
if let Ok(vscode_config) = serde_json::from_str::<VSCodeSettings>(&content) {
let parsed = Self::convert_vscode_config(vscode_config);
if Self::config_has_servers(&parsed) {
debug!("Parsed as VS Code settings configuration format");
return Ok(parsed);
}
}
}
// VS Code mcp.json uses the new format
else if filename == "mcp.json" {
if let Ok(vscode_mcp_config) = serde_json::from_str::<VSCodeMCPConfig>(&content)
{
let parsed = Self::convert_vscode_mcp_config(vscode_mcp_config);
if Self::config_has_servers(&parsed) {
debug!("Parsed as VS Code MCP configuration format");
return Ok(parsed);
}
}
}
}
_ => {}
}
// Fallback chain. Used when client detection didn't match (or matched
// VS Code but the schema-specific parsers produced an empty config —
// e.g., a Claude-Desktop-style `{"mcpServers": ...}` saved at a VS
// Code path). The first parser to yield a non-empty config wins.
let mcp_config_parse = serde_json::from_str::<MCPConfig>(&content);
if let Ok(ref config) = mcp_config_parse {
if Self::config_has_servers(config) {
return Ok(config.clone());
}
}
if let Some(config) =
Self::try_parse_cursor_compatible_config(&content, "Cursor MCP (fallback)")
{
if Self::config_has_servers(&config) {
return Ok(config);
}
}
if let Ok(claude_config) = serde_json::from_str::<ClaudeDesktopConfig>(&content) {
let parsed = Self::convert_claude_desktop_config(claude_config);
if Self::config_has_servers(&parsed) {
debug!("Parsed as Claude Desktop configuration format (fallback)");
return Ok(parsed);
}
}
if let Ok(vscode_config) = serde_json::from_str::<VSCodeSettings>(&content) {
let parsed = Self::convert_vscode_config(vscode_config);
if Self::config_has_servers(&parsed) {
debug!("Parsed as VS Code settings configuration format (fallback)");
return Ok(parsed);
}
}
if let Ok(vscode_mcp_config) = serde_json::from_str::<VSCodeMCPConfig>(&content) {
let parsed = Self::convert_vscode_mcp_config(vscode_mcp_config);
if Self::config_has_servers(&parsed) {
debug!("Parsed as VS Code MCP configuration format (fallback)");
return Ok(parsed);
}
}
// Nothing yielded a non-empty config. If at least one parser succeeded
// syntactically, return that empty config so the caller still sees a
// "0 servers" entry; otherwise surface the original parse error.
match mcp_config_parse {
Ok(config) => Ok(config),
Err(e) => Err(anyhow!(
"Failed to parse IDE config file {}: {}",
path.display(),
e
)),
}
}
/// Convert Cursor MCP configuration to standard format
fn convert_cursor_config(cursor_config: CursorMCPConfig) -> MCPConfig {
let servers = cursor_config.mcp_servers.map(|mcp_servers| {
mcp_servers
.into_iter()
.filter_map(|(name, server_config)| {
// Use explicit URL first, then build from transport config, then handle STDIO servers
if let Some(url) = server_config.url {
// HTTP server with explicit URL
Some(MCPServerConfig {
name: Some(name),
url: Some(url),
command: None,
args: None,
env: None,
description: server_config.description,
auth_headers: server_config.headers,
options: None,
})
} else if let Some(transport) = &server_config.transport {
// HTTP server with transport configuration
let host = transport.host.as_deref().unwrap_or("localhost");
let port = transport.port.unwrap_or(8080);
#[allow(clippy::match_same_arms)]
let scheme = match transport.transport_type.as_deref() {
Some("http" | "streamable-http") => "http",
Some("https") => "https",
_ => "http",
};
let url = format!("{scheme}://{host}:{port}");
Some(MCPServerConfig {
name: Some(name),
url: Some(url),
command: None,
args: None,
env: None,
description: server_config.description,
auth_headers: server_config.headers,
options: None,
})
} else if server_config.command.is_some() {
// STDIO server with command configuration
Some(MCPServerConfig {
name: Some(name.clone()),
url: None, // STDIO servers don't use URLs
command: server_config.command,
args: server_config.args,
env: server_config.env,
description: server_config.description,
auth_headers: server_config.headers,
options: None,
})
} else {
// Skip servers without proper configuration
None
}
})
.collect()
});
MCPConfig {
servers,
options: None, // Could convert cursor settings to options if needed
auth_headers: None,
}
}
/// Convert Claude Desktop configuration to standard format
fn convert_claude_desktop_config(claude_config: ClaudeDesktopConfig) -> MCPConfig {
let servers = claude_config.mcp_servers.map(|mcp_servers| {
mcp_servers
.into_iter()
.filter_map(|(name, server_config)| {
// Skip disabled servers
if server_config.disabled.unwrap_or(false) {
return None;
}
// Use explicit URL if provided, otherwise build from command
let url = if let Some(url) = server_config.url {
url
} else if server_config.command.is_some() {
// For command-based servers, create a placeholder URL
// This represents a local server that will be started by the command
format!("stdio://{name}")
} else {
// Skip servers without explicit configuration
return None;
};
Some(MCPServerConfig {
name: Some(name),
url: Some(url),
command: None,
args: None,
env: None,
description: None, // Claude Desktop format doesn't include descriptions
auth_headers: server_config.headers,
options: None,
})
})
.collect()
});
MCPConfig {
servers,
options: None,
auth_headers: None,
}
}
/// Convert VS Code settings configuration to standard format
fn convert_vscode_config(vscode_config: VSCodeSettings) -> MCPConfig {
let servers = vscode_config.mcp_servers.map(|mcp_servers| {
mcp_servers
.into_iter()
.filter_map(|(name, server_config)| {
let is_http = server_config.url.is_some();
let is_stdio = server_config.command.is_some();
if !is_http && !is_stdio {
return None;
}
Some(MCPServerConfig {
name: Some(name),
url: if is_http { server_config.url } else { None },
command: if is_stdio {
server_config.command
} else {
None
},
args: if is_stdio { server_config.args } else { None },
env: server_config.env,
description: None, // VS Code settings don't typically include descriptions
auth_headers: None,
options: None,
})
})
.collect()
});
MCPConfig {
servers,
options: None,
auth_headers: None,
}
}
/// Convert VS Code MCP configuration (new mcp.json format) to standard format
fn convert_vscode_mcp_config(vscode_mcp_config: VSCodeMCPConfig) -> MCPConfig {
let servers = vscode_mcp_config.servers.map(|servers| {
servers
.into_iter()
.filter_map(|(name, server_config)| {
let is_http = server_config.url.is_some();
let is_stdio = server_config.command.is_some();
if !is_http && !is_stdio {
return None;
}
Some(MCPServerConfig {
name: Some(name),
url: if is_http { server_config.url } else { None },
command: if is_stdio {
server_config.command
} else {
None
},
args: if is_stdio { server_config.args } else { None },
env: server_config.env,
description: None, // VS Code MCP format doesn't include descriptions
auth_headers: server_config.headers,
options: None,
})
})
.collect()
});
MCPConfig {
servers,
options: None,
auth_headers: None,
}
}
/// Try to parse using IDE-specific format, then fall back to standard format with better error reporting
#[allow(dead_code)]
fn try_parse_with_fallback<F>(
ide_name: &str,
content: &str,
ide_parser: F,
path: &Path,
) -> Result<MCPConfig>
where
F: Fn(&str) -> Result<MCPConfig>,
{
match ide_parser(content) {
Ok(config) => Ok(config),
Err(ide_error) => {
// Try standard format as fallback
match Self::parse_standard_config(content) {
Ok(config) => {
debug!(
"{} format parsing failed for {}, but standard format succeeded. {} error was: {}",
ide_name,
path.display(),
ide_name,
ide_error
);
Ok(config)
}
Err(standard_error) => {
Err(anyhow!(
"Failed to parse IDE config file {} in both {} format and standard format. {} format error: {}. Standard format error: {}",
path.display(),
ide_name,
ide_name,
ide_error,
standard_error
))
}
}
}
}
}
/// Parse standard Ramparts MCP config format
#[allow(dead_code)]
fn parse_standard_config(content: &str) -> Result<MCPConfig> {
serde_json::from_str(content).map_err(|e| anyhow!("Standard format parsing failed: {}", e))
}
/// Parse VS Code MCP config format
#[allow(dead_code)]
fn parse_vscode_config(content: &str) -> Result<MCPConfig> {
// Try array format first (more common), then object format with descriptions, then basic object format
if let Ok(vscode_array_config) = serde_json::from_str::<VSCodeArrayMCPConfig>(content) {
Ok(vscode_array_config.into())
} else if let Ok(vscode_object_config) =
serde_json::from_str::<VSCodeObjectMCPConfig>(content)
{
Ok(vscode_object_config.into())
} else {
let vscode_config: VSCodeMCPConfig = serde_json::from_str(content)?;
Ok(vscode_config.into())
}
}
/// Parse Cursor MCP config format
#[allow(dead_code)]
fn parse_cursor_config(content: &str) -> Result<MCPConfig> {
let cursor_config: CursorMCPConfig = serde_json::from_str(content)?;
Ok(cursor_config.into())
}
/// Parse Windsurf MCP config format
#[allow(dead_code)]
fn parse_windsurf_config(content: &str) -> Result<MCPConfig> {
let windsurf_config: WindsurfMCPConfig = serde_json::from_str(content)?;
Ok(windsurf_config.into())
}
/// Parse Claude Desktop MCP config format
#[allow(dead_code)]
fn parse_claude_config(content: &str) -> Result<MCPConfig> {
let claude_config: ClaudeMCPConfig = serde_json::from_str(content)?;
Ok(claude_config.into())
}
/// Parse Claude Code MCP config format (from ~/.claude/settings.json)
#[allow(dead_code)]
fn parse_claude_code_config(content: &str) -> Result<MCPConfig> {
let claude_code_config: ClaudeCodeConfig = serde_json::from_str(content)?;
Ok(claude_code_config.into())
}
/// Parse Zed MCP config format
#[allow(dead_code)]
fn parse_zed_config(content: &str) -> Result<MCPConfig> {
let zed_config: ZedMCPConfig = serde_json::from_str(content)?;
Ok(zed_config.into())
}
/// Parse Zencoder MCP config format
#[allow(dead_code)]
fn parse_zencoder_config(content: &str) -> Result<MCPConfig> {
let zencoder_config: ZencoderMCPConfig = serde_json::from_str(content)?;
Ok(zencoder_config.into())
}
/// Merge two configurations with IDE source information
/// Handles server deduplication based on URL and preserves IDE source
fn merge_config_with_source(base: &mut MCPConfig, other: &MCPConfig, ide_name: &str) {
// Clone the config and add IDE source info to each server
let mut config_with_source = other.clone();
if let Some(ref mut servers) = config_with_source.servers {
for server in servers.iter_mut() {
// Store IDE name in description field with a prefix
let ide_info = format!("IDE:{ide_name}");
match &server.description {
Some(desc) => {
server.description = Some(format!("{desc} [{ide_info}]"));
}
None => {
server.description = Some(format!("[{ide_info}]"));
}
}
}
}
Self::merge_config(base, &config_with_source);
}
/// Merge two configurations, with the second one taking precedence
/// Handles server deduplication based on URL
fn merge_config(base: &mut MCPConfig, other: &MCPConfig) {
// Merge servers with deduplication
if let Some(other_servers) = &other.servers {
match &mut base.servers {
Some(base_servers) => {
// Pre-allocate HashMap with capacity hint for better performance
let total_capacity = base_servers.len() + other_servers.len();
let mut server_map: HashMap<String, MCPServerConfig> =
HashMap::with_capacity(total_capacity);
// Move existing servers to the map using drain() to avoid cloning
for server in base_servers.drain(..) {
let key = server.dedup_key();
server_map.insert(key, server);
}
// Add new servers - we must clone since we're borrowing from other
for server in other_servers {
let key = server.dedup_key();
server_map.insert(key, server.clone());
}
// Convert back to vector
*base_servers = server_map.into_values().collect();
}
None => {
// Avoid cloning the entire vector - move if possible
base.servers = Some(other_servers.clone());
}
}
}
// Merge global options
if let Some(other_options) = &other.options {
match &mut base.options {
Some(base_options) => {
if other_options.timeout.is_some() {
base_options.timeout = other_options.timeout;
}
if other_options.http_timeout.is_some() {
base_options.http_timeout = other_options.http_timeout;
}
if other_options.format.is_some() {
base_options.format.clone_from(&other_options.format);
}
if other_options.detailed.is_some() {
base_options.detailed = other_options.detailed;
}
}
None => {
base.options = Some(other_options.clone());
}
}
}
// Merge auth headers
if let Some(other_auth_headers) = &other.auth_headers {
match &mut base.auth_headers {
Some(base_auth_headers) => {
for (key, value) in other_auth_headers {
base_auth_headers.insert(key.clone(), value.clone());
}
}
None => {
base.auth_headers = Some(other_auth_headers.clone());
}
}
}
}
/// Validate a loaded MCP configuration with comprehensive checks
fn validate_server_count(servers: &[MCPServerConfig]) -> Result<()> {
if servers.len() > 100 {
return Err(anyhow!(
"Too many servers configured ({}). Maximum recommended: 100",
servers.len()
));
}
Ok(())
}
/// Comprehensive server configuration validation
fn validate_server_config(server: &MCPServerConfig, server_index: usize) -> Result<()> {
// Validate that server has either URL or command, but not both
match (&server.url, &server.command) {
(Some(url), None) => {
// HTTP server - validate URL
Self::validate_server_url(url, server_index)?;
}
(None, Some(command)) => {
// STDIO server - validate command and args
Self::validate_stdio_server(command, server.args.as_ref(), server_index)?;
}
(Some(_), Some(_)) => {
return Err(anyhow!(
"Server {} cannot have both URL and command specified - choose HTTP (url) or STDIO (command)",
server_index
));
}
(None, None) => {
return Err(anyhow!(
"Server {} must have either URL (for HTTP servers) or command (for STDIO servers) specified",
server_index
));
}
}
// Validate server name if present
if let Some(name) = &server.name {
Self::validate_server_name(name, server_index)?;
}
// Validate environment variables if present
if let Some(env) = &server.env {
Self::validate_env_vars(env, server_index)?;
}
Ok(())
}
/// Validate STDIO server configuration
fn validate_stdio_server(
command: &str,
args: Option<&Vec<String>>,
server_index: usize,
) -> Result<()> {
if command.trim().is_empty() {
return Err(anyhow!("Server {} has empty command", server_index));
}
if command.len() > 1024 {
return Err(anyhow!(
"Server {} command too long ({}), maximum 1024 characters",
server_index,
command.len()
));
}
// Validate command doesn't contain dangerous characters
if command.contains('\0') || command.contains('\n') || command.contains('\r') {
return Err(anyhow!(
"Server {} command contains invalid characters",
server_index
));
}
// Validate arguments if present
if let Some(args_vec) = args {
if args_vec.len() > 100 {
return Err(anyhow!(
"Server {} has too many arguments ({}), maximum 100",
server_index,
args_vec.len()
));
}
for (arg_index, arg) in args_vec.iter().enumerate() {
if arg.len() > 4096 {
return Err(anyhow!(
"Server {} argument {} too long ({}), maximum 4096 characters",
server_index,
arg_index,
arg.len()
));
}
if arg.contains('\0') {
return Err(anyhow!(
"Server {} argument {} contains null character",
server_index,
arg_index
));
}
}
}
Ok(())
}
/// Validate environment variables
fn validate_env_vars(env: &HashMap<String, String>, server_index: usize) -> Result<()> {
if env.len() > 100 {
return Err(anyhow!(
"Server {} has too many environment variables ({}), maximum 100",
server_index,
env.len()
));
}
for (key, value) in env {
if key.trim().is_empty() {
return Err(anyhow!(
"Server {} has empty environment variable name",
server_index
));
}
if key.len() > 1024 {
return Err(anyhow!(
"Server {} environment variable name '{}' too long ({}), maximum 1024 characters",
server_index,
key,
key.len()
));
}
if value.len() > 8192 {
return Err(anyhow!(
"Server {} environment variable value for '{}' too long ({}), maximum 8192 characters",
server_index,
key,
value.len()
));
}
// Validate key format (must be valid environment variable name)
if !key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
return Err(anyhow!(
"Server {} environment variable name '{}' contains invalid characters (only alphanumeric and underscore allowed)",
server_index,
key
));
}
if key.chars().next().is_some_and(|c| c.is_ascii_digit()) {
return Err(anyhow!(
"Server {} environment variable name '{}' cannot start with a digit",
server_index,
key
));
}
}
Ok(())
}
fn validate_server_url(url_str: &str, server_index: usize) -> Result<()> {
if url_str.is_empty() {
return Err(anyhow!("Server {} has empty URL", server_index));
}
let url_str = url_str.trim();
if url_str.len() > 2048 {
return Err(anyhow!(
"Server {} URL too long ({}), maximum 2048 characters",
server_index,
url_str.len()
));
}
// stdio: URLs should not be handled here - they should use command field instead
if url_str.starts_with("stdio:") {
return Err(anyhow!(
"Server {} uses deprecated stdio: URL format. Use 'command' and 'args' fields instead of 'url' for STDIO servers",
server_index
));
}
// Parse HTTP/HTTPS URLs using the url crate
if url_str.starts_with("http://") || url_str.starts_with("https://") {
match Url::parse(url_str) {
Ok(parsed_url) => {
// Validate port if present
if let Some(port) = parsed_url.port() {
if port == 0 {
return Err(anyhow!(
"Server {} has invalid port 0: {}",
server_index,
url_str
));
}
}
Ok(())
}
Err(e) => Err(anyhow!(
"Server {} has malformed URL '{}': {}",
server_index,
url_str,
e
)),
}
} else {
Err(anyhow!(
"Server {} has invalid URL scheme: {}. Supported: http://, https://, stdio:",
server_index,
url_str
))
}
}
fn validate_server_name(name: &str, server_index: usize) -> Result<()> {
let name = name.trim();
if name.is_empty() {
return Err(anyhow!("Server {} has empty name", server_index));
}
if name.len() > 255 {
return Err(anyhow!(
"Server {} name too long ({}), maximum 255 characters",
server_index,
name.len()
));
}
Ok(())
}
fn validate_auth_headers(
auth_headers: &HashMap<String, String>,
server_index: usize,
) -> Result<()> {
for (header_name, header_value) in auth_headers {
if header_name.trim().is_empty() {
return Err(anyhow!(
"Server {} has empty auth header name",
server_index
));
}
if header_value.trim().is_empty() {
return Err(anyhow!(
"Server {} has empty auth header value for '{}'",
server_index,
header_name
));
}
if header_name.len() > 1024 || header_value.len() > 4096 {
return Err(anyhow!(
"Server {} has auth header that's too long",
server_index
));
}
}
Ok(())
}
fn validate_server_description(description: &str, server_index: usize) -> Result<()> {
if description.len() > 1000 {
return Err(anyhow!(
"Server {} description too long ({}), maximum 1000 characters",
server_index,
description.len()
));
}
Ok(())
}
fn validate_global_auth_headers(global_auth_headers: &HashMap<String, String>) -> Result<()> {
for (header_name, header_value) in global_auth_headers {
if header_name.trim().is_empty() || header_value.trim().is_empty() {
return Err(anyhow!(
"Global auth headers cannot have empty names or values"
));
}
}
Ok(())
}
fn validate_config(config: &MCPConfig) -> Result<()> {
if let Some(servers) = &config.servers {
Self::validate_server_count(servers)?;
let mut seen_dedup_keys = HashMap::new();
let mut seen_names = HashMap::new();
for (i, server) in servers.iter().enumerate() {
// Validate the entire server configuration
Self::validate_server_config(server, i)?;
// Check for duplicate servers using the same deduplication logic as merge
let dedup_key = server.dedup_key();
if let Some(existing_index) = seen_dedup_keys.get(&dedup_key) {
return Err(anyhow!(
"Duplicate server configuration detected: server {} and server {} both resolve to the same configuration (key: '{}')",
existing_index, i, dedup_key
));
}
seen_dedup_keys.insert(dedup_key, i);
if let Some(name) = &server.name {
Self::validate_server_name(name, i)?;
let name = name.trim();
if let Some(existing_index) = seen_names.get(name) {
return Err(anyhow!(
"Duplicate server name '{}': server {} and server {} both use this name",
name, existing_index, i
));
}
seen_names.insert(name.to_string(), i);
}
if let Some(auth_headers) = &server.auth_headers {
Self::validate_auth_headers(auth_headers, i)?;
}
if let Some(description) = &server.description {
Self::validate_server_description(description, i)?;
}
}
}
if let Some(global_auth_headers) = &config.auth_headers {
Self::validate_global_auth_headers(global_auth_headers)?;
}
Ok(())
}
/// Check if any IDE configuration files exist
pub fn has_config_files(&self) -> bool {
self.config_paths.iter().any(|(path, _)| path.exists())
}
/// Build a `MCPConfigManager` whose `config_paths` are discovered by
/// walking `root` for known MCP configuration filenames. Used by
/// `scan-config --root <PATH>` (see ramparts#51) to scan a checked-in
/// repository of IDE configs without relying on the user's home
/// directory state.
pub fn with_root(root: &Path) -> Self {
Self {
config_paths: Self::discover_config_paths_in_root(root),
}
}
/// Recursively walk `root` collecting paths whose filename matches a
/// known MCP config pattern. The directory walk skips a small set of
/// directories that never contain MCP configs (`.git`, `node_modules`,
/// `target`, `dist`, `build`) so a repo with thousands of files in
/// those directories doesn't pay for a full crawl.
fn discover_config_paths_in_root(root: &Path) -> Vec<(PathBuf, MCPClient)> {
const SKIP_DIRS: &[&str] = &[
".git",
"node_modules",
"target",
"dist",
"build",
".venv",
"venv",
"__pycache__",
];
const CONFIG_FILENAMES: &[&str] = &[
"mcp.json",
"mcp_config.json",
"claude_desktop_config.json",
"settings.json",
"settings.local.json",
"managed-settings.json",
];
const MAX_DEPTH: usize = 16;
fn walk(
dir: &Path,
depth: usize,
max_depth: usize,
skip_dirs: &[&str],
filenames: &[&str],
out: &mut Vec<(PathBuf, MCPClient)>,
) {
if depth > max_depth {
return;
}
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
let Ok(file_type) = entry.file_type() else {
continue;
};
if file_type.is_symlink() {
// Don't follow symlinks — avoids cycles and surprises
// when scanning repos that link out to elsewhere.
continue;
}
if file_type.is_dir() {
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
if skip_dirs.contains(&name)
|| name.starts_with('.')
&& name != ".vscode"
&& name != ".cursor"
&& name != ".claude"
&& name != ".gemini"
&& name != ".windsurf"
&& name != ".codeium"
{
continue;
}
}
walk(&path, depth + 1, max_depth, skip_dirs, filenames, out);
} else if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
if filenames.contains(&name) || name.ends_with(".mcp.json") {
let client =
MCPConfigManager::detect_client(&path).unwrap_or(MCPClient::VSCode);
out.push((path, client));
}
}
}
}
let mut found = Vec::new();
if !root.exists() {
warn!("--root path does not exist: {}", root.display());
return found;
}
walk(root, 0, MAX_DEPTH, SKIP_DIRS, CONFIG_FILENAMES, &mut found);
found
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::tempdir;
#[test]
fn test_load_config_from_path() {
let temp_dir = tempdir().unwrap();
let config_path = temp_dir.path().join("test_config.json");
let config_content = r#"{
"servers": [
{
"name": "test-server",
"url": "http://localhost:3000",
"description": "Test server"
}
],
"options": {
"timeout": 60,
"format": "json"
}
}"#;
fs::write(&config_path, config_content).unwrap();
let config = MCPConfigManager::load_config_from_path(&config_path).unwrap();
assert!(config.servers.is_some());
assert_eq!(config.servers.unwrap().len(), 1);
assert!(config.options.is_some());
}
#[test]
fn test_merge_config() {
let mut base = MCPConfig::default();
let other = MCPConfig {
servers: Some(vec![MCPServerConfig {
name: Some("server1".to_string()),
url: Some("http://localhost:3000".to_string()),
command: None,
args: None,
env: None,
description: None,
auth_headers: None,
options: None,
}]),
options: Some(MCPGlobalOptions {
timeout: Some(60),
http_timeout: None,
format: Some("json".to_string()),
detailed: None,
}),
auth_headers: None,
};
MCPConfigManager::merge_config(&mut base, &other);
assert!(base.servers.is_some());
assert_eq!(base.servers.unwrap().len(), 1);
assert!(base.options.is_some());
}
#[test]
fn test_merge_config_deduplication() {
let mut base = MCPConfig {
servers: Some(vec![MCPServerConfig {
name: Some("server1".to_string()),
url: Some("http://localhost:3000".to_string()),
command: None,
args: None,
env: None,
description: None,
auth_headers: None,
options: None,
}]),
options: None,
auth_headers: None,
};
let other = MCPConfig {
servers: Some(vec![
MCPServerConfig {
name: Some("server1-updated".to_string()),
url: Some("http://localhost:3000".to_string()), // Same URL - should replace
command: None,
args: None,
env: None,
description: Some("Updated server".to_string()),
auth_headers: None,
options: None,
},
MCPServerConfig {
name: Some("server2".to_string()),
url: Some("http://localhost:4000".to_string()), // Different URL - should add
command: None,
args: None,
env: None,
description: None,
auth_headers: None,
options: None,
},
]),
options: None,
auth_headers: None,
};
MCPConfigManager::merge_config(&mut base, &other);
let servers = base.servers.unwrap();
assert_eq!(servers.len(), 2); // Should have 2 servers, not 3
// Find the server with URL localhost:3000 - should be the updated one
let updated_server = servers
.iter()
.find(|s| s.url.as_deref() == Some("http://localhost:3000"))
.unwrap();
assert_eq!(updated_server.name.as_ref().unwrap(), "server1-updated");
assert_eq!(
updated_server.description.as_ref().unwrap(),
"Updated server"
);
// Should also have the new server
let new_server = servers
.iter()
.find(|s| s.url.as_deref() == Some("http://localhost:4000"))
.unwrap();
assert_eq!(new_server.name.as_ref().unwrap(), "server2");
}
#[test]
fn test_detect_client() {
assert_eq!(
MCPConfigManager::detect_client("/home/user/.cursor/mcp.json"),
Some(MCPClient::Cursor)
);
assert_eq!(
MCPConfigManager::detect_client("/home/user/.codeium/windsurf/mcp_config.json"),
Some(MCPClient::Windsurf)
);
assert_eq!(
MCPConfigManager::detect_client("/home/user/.vscode/mcp.json"),
Some(MCPClient::VSCode)
);
assert_eq!(
MCPConfigManager::detect_client("/home/user/.claude/mcp.json"),
Some(MCPClient::Claude)
);
assert_eq!(
MCPConfigManager::detect_client("/home/user/.config/nvim/mcp.json"),
Some(MCPClient::Neovim)
);
assert_eq!(
MCPConfigManager::detect_client("/some/unknown/path.json"),
None
);
}
#[test]
fn test_validate_config() {
// Valid config
let valid_config = MCPConfig {
servers: Some(vec![MCPServerConfig {
name: Some("test".to_string()),
url: Some("http://localhost:3000".to_string()),
command: None,
args: None,
env: None,
description: None,
auth_headers: None,
options: None,
}]),
options: None,
auth_headers: None,
};
assert!(MCPConfigManager::validate_config(&valid_config).is_ok());
// Invalid config - empty URL
let invalid_config = MCPConfig {
servers: Some(vec![MCPServerConfig {
name: Some("test".to_string()),
url: Some(String::new()),
command: None,
args: None,
env: None,
description: None,
auth_headers: None,
options: None,
}]),
options: None,
auth_headers: None,
};
assert!(MCPConfigManager::validate_config(&invalid_config).is_err());
// Invalid config - bad URL format
let invalid_config2 = MCPConfig {
servers: Some(vec![MCPServerConfig {
name: Some("test".to_string()),
url: Some("not-a-url".to_string()),
command: None,
args: None,
env: None,
description: None,
auth_headers: None,
options: None,
}]),
options: None,
auth_headers: None,
};
assert!(MCPConfigManager::validate_config(&invalid_config2).is_err());
}
#[test]
fn test_mcp_client_enum() {
assert_eq!(MCPClient::Cursor.name(), "cursor");
assert_eq!(MCPClient::Windsurf.name(), "windsurf");
assert_eq!(MCPClient::VSCode.name(), "vscode");
assert_eq!(MCPClient::Claude.name(), "claude");
assert_eq!(MCPClient::Neovim.name(), "neovim");
assert_eq!(MCPClient::Helix.name(), "helix");
assert_eq!(MCPClient::Zed.name(), "zed");
assert_eq!(MCPClient::Zencoder.name(), "zencoder");
}
#[test]
fn test_url_normalization() {
assert_eq!(
MCPConfigManager::normalize_url("HTTP://LOCALHOST:3000/"),
"http://localhost:3000"
);
assert_eq!(
MCPConfigManager::normalize_url("http://127.0.0.1:3000"),
"http://localhost:3000"
);
assert_eq!(
MCPConfigManager::normalize_url("https://0.0.0.0:8080/"),
"https://localhost:8080"
);
assert_eq!(MCPConfigManager::normalize_url("stdio:test"), "stdio:test");
assert_eq!(
MCPConfigManager::normalize_url("http://example.com/path/"),
"http://example.com/path"
);
}
#[test]
fn test_enhanced_client_detection() {
use std::path::PathBuf;
// Test exact component matches
assert_eq!(
MCPConfigManager::detect_client(PathBuf::from(
"/Applications/Cursor.app/Contents/mcp.json"
)),
Some(MCPClient::Cursor)
);
// Test Windows paths - use forward slashes for cross-platform compatibility
assert_eq!(
MCPConfigManager::detect_client(PathBuf::from(
"C:/Users/test/AppData/Roaming/Code/User/mcp.json"
)),
Some(MCPClient::VSCode)
);
// Test extension ID path
assert_eq!(
MCPConfigManager::detect_client(PathBuf::from(
"/home/user/.config/rooveterinaryinc.cursor-mcp/config.json"
)),
Some(MCPClient::Cursor)
);
// Test disambiguation - should not match generic "code" in paths
assert_eq!(
MCPConfigManager::detect_client(PathBuf::from(
"/home/user/my-code-project/config.json"
)),
None
);
}
#[test]
fn test_enhanced_validation() {
// Test duplicate URL detection with normalization
let config_with_duplicate_urls = MCPConfig {
servers: Some(vec![
MCPServerConfig {
name: Some("server1".to_string()),
url: Some("http://localhost:3000".to_string()),
command: None,
args: None,
env: None,
description: None,
auth_headers: None,
options: None,
},
MCPServerConfig {
name: Some("server2".to_string()),
url: Some("HTTP://LOCALHOST:3000/".to_string()), // Different case and trailing slash
command: None,
args: None,
env: None,
description: None,
auth_headers: None,
options: None,
},
]),
options: None,
auth_headers: None,
};
assert!(MCPConfigManager::validate_config(&config_with_duplicate_urls).is_err());
// Test duplicate names
let config_with_duplicate_names = MCPConfig {
servers: Some(vec![
MCPServerConfig {
name: Some("same-name".to_string()),
url: Some("http://localhost:3000".to_string()),
command: None,
args: None,
env: None,
description: None,
auth_headers: None,
options: None,
},
MCPServerConfig {
name: Some("same-name".to_string()),
url: Some("http://localhost:4000".to_string()),
command: None,
args: None,
env: None,
description: None,
auth_headers: None,
options: None,
},
]),
options: None,
auth_headers: None,
};
assert!(MCPConfigManager::validate_config(&config_with_duplicate_names).is_err());
// Test invalid port
let config_with_invalid_port = MCPConfig {
servers: Some(vec![MCPServerConfig {
name: Some("test".to_string()),
url: Some("http://localhost:0".to_string()),
command: None,
args: None,
env: None,
description: None,
auth_headers: None,
options: None,
}]),
options: None,
auth_headers: None,
};
assert!(MCPConfigManager::validate_config(&config_with_invalid_port).is_err());
}
#[test]
fn test_platform_detection() {
// Test that platform detection works without panicking
let paths = MCPConfigManager::discover_config_paths();
assert!(
!paths.is_empty(),
"Should discover some configuration paths"
);
}
#[test]
fn test_merge_config_with_normalization() {
let mut base = MCPConfig {
servers: Some(vec![MCPServerConfig {
name: Some("server1".to_string()),
url: Some("http://localhost:3000/".to_string()), // With trailing slash
command: None,
args: None,
env: None,
description: None,
auth_headers: None,
options: None,
}]),
options: None,
auth_headers: None,
};
let other = MCPConfig {
servers: Some(vec![MCPServerConfig {
name: Some("server1-updated".to_string()),
url: Some("HTTP://LOCALHOST:3000".to_string()), // Different case, no trailing slash
command: None,
args: None,
env: None,
description: Some("Updated".to_string()),
auth_headers: None,
options: None,
}]),
options: None,
auth_headers: None,
};
MCPConfigManager::merge_config(&mut base, &other);
let servers = base.servers.unwrap();
assert_eq!(servers.len(), 1); // Should be deduplicated due to URL normalization
assert_eq!(servers[0].name.as_ref().unwrap(), "server1-updated");
assert_eq!(servers[0].description.as_ref().unwrap(), "Updated");
}
#[test]
fn test_vscode_config_parsing() {
let vscode_content = r#"{
"servers": {
"github": {
"type": "http",
"url": "https://api.githubcopilot.com/mcp/",
"gallery": true
},
"local-fs": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
"description": "Local filesystem access"
}
},
"inputs": []
}"#;
// Test VS Code format parsing
let result = MCPConfigManager::parse_vscode_config(vscode_content);
assert!(
result.is_ok(),
"Failed to parse VS Code config: {:?}",
result.err()
);
let config = result.unwrap();
assert!(config.servers.is_some());
let servers = config.servers.unwrap();
assert_eq!(servers.len(), 2);
// Check github server
let github_server = servers
.iter()
.find(|s| s.name.as_deref() == Some("github"))
.unwrap();
assert_eq!(
github_server.url,
Some("https://api.githubcopilot.com/mcp/".to_string())
);
// Check local-fs server
let fs_server = servers
.iter()
.find(|s| s.name.as_deref() == Some("local-fs"))
.unwrap();
assert_eq!(fs_server.url, None);
assert_eq!(
fs_server.description,
Some("Local filesystem access".to_string())
);
}
#[test]
fn test_zed_config_parsing() {
let zed_content = r#"{
"context_servers": [
{
"mcp-server-git": {
"command": {
"path": "uvx",
"args": ["mcp-server-git"]
}
}
},
{
"filesystem": {
"command": {
"path": "node",
"args": ["/path/to/filesystem-server.js", "/tmp"]
}
}
}
]
}"#;
// Test Zed format parsing
let result = MCPConfigManager::parse_zed_config(zed_content);
assert!(
result.is_ok(),
"Failed to parse Zed config: {:?}",
result.err()
);
let config = result.unwrap();
assert!(config.servers.is_some());
let servers = config.servers.unwrap();
assert_eq!(servers.len(), 2);
// Check git server
let git_server = servers
.iter()
.find(|s| s.name.as_deref() == Some("mcp-server-git"))
.unwrap();
assert_eq!(git_server.url, None);
assert!(git_server
.description
.as_ref()
.unwrap()
.contains("uvx mcp-server-git"));
// Check filesystem server
let fs_server = servers
.iter()
.find(|s| s.name.as_deref() == Some("filesystem"))
.unwrap();
assert_eq!(fs_server.url, None);
assert!(fs_server
.description
.as_ref()
.unwrap()
.contains("node /path/to/filesystem-server.js /tmp"));
}
#[test]
fn test_zencoder_config_parsing() {
let zencoder_content = r#"{
"command": "uvx",
"args": ["mcp-server-git", "--repository", "path/to/git/repo"]
}"#;
// Test Zencoder format parsing
let result = MCPConfigManager::parse_zencoder_config(zencoder_content);
assert!(
result.is_ok(),
"Failed to parse Zencoder config: {:?}",
result.err()
);
let config = result.unwrap();
assert!(config.servers.is_some());
let servers = config.servers.unwrap();
assert_eq!(servers.len(), 1);
// Check zencoder server
let zencoder_server = &servers[0];
assert_eq!(zencoder_server.name.as_deref(), Some("zencoder"));
assert_eq!(zencoder_server.url, None);
assert_eq!(zencoder_server.command.as_deref(), Some("uvx"));
assert_eq!(
zencoder_server.args,
Some(vec![
"mcp-server-git".to_string(),
"--repository".to_string(),
"path/to/git/repo".to_string()
])
);
assert_eq!(
zencoder_server.description.as_deref(),
Some("Zencoder MCP server")
);
}
#[test]
fn test_cursor_config_parsing() {
let cursor_content = r#"{
"mcpServers": {
"airbnb": {
"command": "npx",
"args": ["-y", "@openbnb/mcp-server-airbnb"]
},
"playwright": {
"command": "npx",
"args": ["-y", "@executeautomation/playwright-mcp-server"]
},
"time": {
"command": "uvx",
"args": ["mcp-server-time"],
"env": {
"TZ": "UTC"
}
}
}
}"#;
// Test Cursor format parsing
let result = MCPConfigManager::parse_cursor_config(cursor_content);
assert!(
result.is_ok(),
"Failed to parse Cursor config: {:?}",
result.err()
);
let config = result.unwrap();
assert!(config.servers.is_some());
let servers = config.servers.unwrap();
assert_eq!(servers.len(), 3);
// Check airbnb server
let airbnb_server = servers
.iter()
.find(|s| s.name.as_deref() == Some("airbnb"))
.unwrap();
assert_eq!(airbnb_server.command, Some("npx".to_string()));
assert_eq!(
airbnb_server.args,
Some(vec![
"-y".to_string(),
"@openbnb/mcp-server-airbnb".to_string()
])
);
assert_eq!(airbnb_server.url, None);
// Check time server with env
let time_server = servers
.iter()
.find(|s| s.name.as_deref() == Some("time"))
.unwrap();
assert_eq!(time_server.command, Some("uvx".to_string()));
assert!(time_server.env.is_some());
let env = time_server.env.as_ref().unwrap();
assert_eq!(env.get("TZ"), Some(&"UTC".to_string()));
}
#[test]
fn test_windsurf_config_parsing() {
let windsurf_content = r#"{
"servers": {
"git": {
"command": "uvx",
"args": ["mcp-server-git"],
"type": "stdio"
},
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
"description": "File system access",
"env": {
"NODE_ENV": "development"
}
}
},
"global": {
"timeout": 30
}
}"#;
// Test Windsurf format parsing
let result = MCPConfigManager::parse_windsurf_config(windsurf_content);
assert!(
result.is_ok(),
"Failed to parse Windsurf config: {:?}",
result.err()
);
let config = result.unwrap();
assert!(config.servers.is_some());
let servers = config.servers.unwrap();
assert_eq!(servers.len(), 2);
// Check git server
let git_server = servers
.iter()
.find(|s| s.name.as_deref() == Some("git"))
.unwrap();
assert_eq!(git_server.command, Some("uvx".to_string()));
assert_eq!(git_server.args, Some(vec!["mcp-server-git".to_string()]));
// Check filesystem server
let fs_server = servers
.iter()
.find(|s| s.name.as_deref() == Some("filesystem"))
.unwrap();
assert_eq!(
fs_server.description,
Some("File system access".to_string())
);
assert!(fs_server.env.is_some());
}
#[test]
fn test_claude_desktop_config_parsing() {
let claude_content = r#"{
"mcpServers": {
"brave-search": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-brave-search"],
"env": {
"BRAVE_API_KEY": "your-api-key"
}
},
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/Users/username/Desktop"],
"type": "stdio"
}
}
}"#;
// Test Claude Desktop format parsing
let result = MCPConfigManager::parse_claude_config(claude_content);
assert!(
result.is_ok(),
"Failed to parse Claude Desktop config: {:?}",
result.err()
);
let config = result.unwrap();
assert!(config.servers.is_some());
let servers = config.servers.unwrap();
assert_eq!(servers.len(), 2);
// Check brave-search server
let brave_server = servers
.iter()
.find(|s| s.name.as_deref() == Some("brave-search"))
.unwrap();
assert_eq!(brave_server.command, Some("npx".to_string()));
assert!(brave_server.env.is_some());
let env = brave_server.env.as_ref().unwrap();
assert_eq!(env.get("BRAVE_API_KEY"), Some(&"your-api-key".to_string()));
// Check filesystem server
let fs_server = servers
.iter()
.find(|s| s.name.as_deref() == Some("filesystem"))
.unwrap();
assert_eq!(fs_server.command, Some("npx".to_string()));
assert!(fs_server
.args
.as_ref()
.unwrap()
.contains(&"/Users/username/Desktop".to_string()));
}
#[test]
fn test_claude_code_config_parsing() {
let claude_code_content = r#"{
"numStartups": 36,
"installMethod": "unknown",
"mcpServers": {
"sequential-thinking": {
"type": "stdio",
"command": "npx",
"args": ["-y", "u/modelcontextprotocol/server-sequential-thinking"],
"env": {}
},
"filesystem": {
"type": "stdio",
"command": "uvx",
"args": ["mcp-server-filesystem", "/tmp"],
"env": {
"DEBUG": "true"
}
}
}
}"#;
// Test Claude Code format parsing
let result = MCPConfigManager::parse_claude_code_config(claude_code_content);
assert!(
result.is_ok(),
"Failed to parse Claude Code config: {:?}",
result.err()
);
let config = result.unwrap();
assert!(config.servers.is_some());
let servers = config.servers.unwrap();
assert_eq!(servers.len(), 2);
// Check sequential-thinking server
let seq_server = servers
.iter()
.find(|s| s.name.as_deref() == Some("sequential-thinking"))
.unwrap();
assert_eq!(seq_server.command, Some("npx".to_string()));
assert_eq!(
seq_server.args,
Some(vec![
"-y".to_string(),
"u/modelcontextprotocol/server-sequential-thinking".to_string()
])
);
assert_eq!(seq_server.url, None);
// Check filesystem server with env
let fs_server = servers
.iter()
.find(|s| s.name.as_deref() == Some("filesystem"))
.unwrap();
assert_eq!(fs_server.command, Some("uvx".to_string()));
assert!(fs_server.env.is_some());
let env = fs_server.env.as_ref().unwrap();
assert_eq!(env.get("DEBUG"), Some(&"true".to_string()));
}
#[test]
fn test_vscode_array_config_parsing() {
let vscode_array_content = r#"{
"servers": [
{
"name": "time",
"command": "uvx",
"args": ["mcp-server-time"]
},
{
"name": "everything",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-everything"]
},
{
"name": "git",
"command": "uvx",
"args": ["mcp-server-git"]
},
{
"name": "Neon",
"command": "npx",
"args": ["-y", "mcp-remote", "https://mcp.neon.tech/mcp"]
}
]
}"#;
// Test VS Code array format parsing
let result = MCPConfigManager::parse_vscode_config(vscode_array_content);
assert!(
result.is_ok(),
"Failed to parse VS Code array config: {:?}",
result.err()
);
let config = result.unwrap();
assert!(config.servers.is_some());
let servers = config.servers.unwrap();
assert_eq!(servers.len(), 4);
// Check time server
let time_server = servers
.iter()
.find(|s| s.name.as_deref() == Some("time"))
.unwrap();
assert_eq!(time_server.command, Some("uvx".to_string()));
assert_eq!(time_server.args, Some(vec!["mcp-server-time".to_string()]));
// Check Neon server
let neon_server = servers
.iter()
.find(|s| s.name.as_deref() == Some("Neon"))
.unwrap();
assert_eq!(neon_server.command, Some("npx".to_string()));
assert!(neon_server
.args
.as_ref()
.unwrap()
.contains(&"https://mcp.neon.tech/mcp".to_string()));
}
#[test]
fn test_client_path_detection_claude_code() {
// Test Claude Code vs Claude Desktop path detection
assert_eq!(
MCPConfigManager::detect_client("/home/user/.claude/settings.json"),
Some(MCPClient::ClaudeCode)
);
assert_eq!(
MCPConfigManager::detect_client("/home/user/.claude/settings.local.json"),
Some(MCPClient::ClaudeCode)
);
assert_eq!(
MCPConfigManager::detect_client("/home/user/.claude/mcp.json"),
Some(MCPClient::Claude)
);
// Test Windsurf path detection (corrected path)
assert_eq!(
MCPConfigManager::detect_client("/home/user/.codeium/windsurf/mcp_config.json"),
Some(MCPClient::Windsurf)
);
}
#[test]
fn test_gemini_config_parsing() {
let gemini_content = r#"{
"mcpServers": {
"github": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-github"
],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "ghp_example_personal_access_token12345"
}
},
"gitlab": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-gitlab"
]
},
"cloudflare-observability": {
"command": "npx",
"args": ["mcp-remote", "https://observability.mcp.cloudflare.com/sse"]
},
"cloudflare-bindings": {
"command": "npx",
"args": ["mcp-remote", "https://bindings.mcp.cloudflare.com/sse"]
}
}
}"#;
// Test Gemini format parsing (reuses Cursor parsing logic since format is the same)
let result = MCPConfigManager::parse_cursor_config(gemini_content);
assert!(
result.is_ok(),
"Failed to parse Gemini config: {:?}",
result.err()
);
let config = result.unwrap();
assert!(config.servers.is_some());
let servers = config.servers.unwrap();
assert_eq!(servers.len(), 4);
// Check github server with env
let github_server = servers
.iter()
.find(|s| s.name.as_deref() == Some("github"))
.unwrap();
assert_eq!(github_server.command, Some("npx".to_string()));
assert_eq!(
github_server.args,
Some(vec![
"-y".to_string(),
"@modelcontextprotocol/server-github".to_string()
])
);
assert_eq!(github_server.url, None);
assert!(github_server.env.is_some());
let env = github_server.env.as_ref().unwrap();
assert_eq!(
env.get("GITHUB_PERSONAL_ACCESS_TOKEN"),
Some(&"ghp_example_personal_access_token12345".to_string())
);
// Check gitlab server
let gitlab_server = servers
.iter()
.find(|s| s.name.as_deref() == Some("gitlab"))
.unwrap();
assert_eq!(gitlab_server.command, Some("npx".to_string()));
assert_eq!(
gitlab_server.args,
Some(vec![
"-y".to_string(),
"@modelcontextprotocol/server-gitlab".to_string()
])
);
// Check cloudflare-observability server
let cf_obs_server = servers
.iter()
.find(|s| s.name.as_deref() == Some("cloudflare-observability"))
.unwrap();
assert_eq!(cf_obs_server.command, Some("npx".to_string()));
assert_eq!(
cf_obs_server.args,
Some(vec![
"mcp-remote".to_string(),
"https://observability.mcp.cloudflare.com/sse".to_string()
])
);
// Check cloudflare-bindings server
let cf_bind_server = servers
.iter()
.find(|s| s.name.as_deref() == Some("cloudflare-bindings"))
.unwrap();
assert_eq!(cf_bind_server.command, Some("npx".to_string()));
assert_eq!(
cf_bind_server.args,
Some(vec![
"mcp-remote".to_string(),
"https://bindings.mcp.cloudflare.com/sse".to_string()
])
);
}
#[test]
fn test_client_path_detection_gemini() {
// Test Gemini path detection
assert_eq!(
MCPConfigManager::detect_client("/home/user/.gemini/settings.json"),
Some(MCPClient::Gemini)
);
assert_eq!(
MCPConfigManager::detect_client("/Users/user/.gemini/settings.json"),
Some(MCPClient::Gemini)
);
// Test combined with other path detections
assert_eq!(
MCPConfigManager::detect_client("/home/user/.claude/settings.json"),
Some(MCPClient::ClaudeCode)
);
assert_eq!(
MCPConfigManager::detect_client("/home/user/.codeium/windsurf/mcp_config.json"),
Some(MCPClient::Windsurf)
);
}
#[test]
fn test_client_name_mappings_complete() {
// Test all client name mappings including Claude Code and Gemini
assert_eq!(MCPClient::Cursor.name(), "cursor");
assert_eq!(MCPClient::Windsurf.name(), "windsurf");
assert_eq!(MCPClient::VSCode.name(), "vscode");
assert_eq!(MCPClient::Claude.name(), "claude");
assert_eq!(MCPClient::ClaudeCode.name(), "claude-code");
assert_eq!(MCPClient::Gemini.name(), "gemini");
assert_eq!(MCPClient::Neovim.name(), "neovim");
assert_eq!(MCPClient::Helix.name(), "helix");
assert_eq!(MCPClient::Zed.name(), "zed");
assert_eq!(MCPClient::Zencoder.name(), "zencoder");
}
}
/// Scanner Configuration structure for reading from config.yaml
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScannerConfig {
/// LLM configuration
pub llm: LLMConfig,
/// Scanner configuration
pub scanner: ScannerSettings,
/// Security configuration
pub security: SecurityConfig,
/// Logging configuration
pub logging: LoggingConfig,
/// Performance configuration
pub performance: PerformanceConfig,
}
/// LLM Configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LLMConfig {
/// Model provider (openai, anthropic, local, etc.)
pub provider: String,
/// Model name/identifier
pub model: String,
/// Base URL for the API
pub base_url: String,
/// API key (can also be set via environment variable)
pub api_key: String,
/// Request timeout in seconds
pub timeout: u64,
/// Maximum tokens for LLM responses
pub max_tokens: u32,
/// Temperature for LLM responses
pub temperature: f32,
}
/// Scanner Settings
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScannerSettings {
/// Default HTTP timeout for MCP server connections (seconds)
pub http_timeout: u64,
/// Default scan timeout (seconds)
pub scan_timeout: u64,
/// Enable/disable detailed output
pub detailed: bool,
/// Output format (json, table, text)
pub format: String,
/// Enable/disable parallel execution
pub parallel: bool,
/// Number of retries for failed requests
pub max_retries: u32,
/// Initial delay for retry backoff (milliseconds)
pub retry_delay_ms: u64,
/// Maximum number of tools to process in a single LLM batch
pub llm_batch_size: u32,
/// Enable/disable YARA rule scanning
pub enable_yara: bool,
}
/// Security Configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecurityConfig {
/// Enable/disable security scanning
pub enabled: bool,
/// Minimum severity level to report
pub min_severity: String,
/// Enable/disable specific vulnerability checks
pub checks: SecurityChecks,
}
/// Security Checks Configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(clippy::struct_excessive_bools)]
pub struct SecurityChecks {
pub tool_poisoning: bool,
pub secrets_leakage: bool,
pub sql_injection: bool,
pub command_injection: bool,
pub path_traversal: bool,
pub auth_bypass: bool,
pub prompt_injection: bool,
pub pii_leakage: bool,
pub jailbreak: bool,
}
/// Logging Configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingConfig {
/// Log level (trace, debug, info, warn, error)
pub level: String,
/// Enable/disable colored output
pub colored: bool,
/// Enable/disable timestamps in logs
pub timestamps: bool,
}
/// Performance Configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceConfig {
/// Enable/disable performance tracking
pub tracking: bool,
/// Threshold for slow execution warnings (milliseconds)
pub slow_threshold_ms: u64,
}
/// Tool Refresh Configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)]
pub struct ToolRefreshConfig {
/// Enable/disable automatic tool refresh
pub enabled: bool,
/// Refresh interval in hours
pub interval_hours: u64,
/// Start time for daily refresh (HH:MM format, UTC)
pub start_time: String,
/// List of servers to refresh automatically (empty = refresh discovered servers)
pub servers: Vec<ToolRefreshServerConfig>,
/// Rate limiting configuration
#[serde(default)]
pub rate_limit: RateLimitConfig,
}
/// Rate limiting configuration for tool refresh
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)]
pub struct RateLimitConfig {
/// Maximum number of concurrent server refreshes
pub max_concurrent: usize,
/// Delay between server refreshes in milliseconds
pub delay_between_servers_ms: u64,
/// Maximum requests per minute per server
pub max_requests_per_minute: u64,
}
/// Tool refresh server configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolRefreshServerConfig {
/// Server URL
pub url: String,
/// Authentication headers
#[serde(default)]
pub auth_headers: HashMap<String, String>,
/// Connection timeout in seconds
#[serde(default = "default_refresh_timeout")]
pub timeout: u64,
}
impl ToolRefreshServerConfig {
/// Apply environment variable mappings to auth headers
#[allow(dead_code)] // Future feature - will be used when scheduler is re-enabled
pub fn with_env_mappings(mut self) -> Self {
self.auth_headers = apply_env_mappings(self.auth_headers);
self
}
}
fn default_refresh_timeout() -> u64 {
30
}
/// Apply environment variable mappings to auth headers
/// Maps generic environment variables to standard auth headers
pub fn apply_env_mappings(mut headers: HashMap<String, String>) -> HashMap<String, String> {
// Check for LLM_API_KEY environment variable
if let Ok(llm_api_key) = std::env::var("LLM_API_KEY") {
// Only add if Authorization header is not already set
if !headers.contains_key("Authorization") && !headers.contains_key("authorization") {
headers.insert("Authorization".to_string(), format!("Bearer {llm_api_key}"));
debug!("Applied LLM_API_KEY environment variable to Authorization header");
}
}
// Check for other common generic environment variables
if let Ok(api_key) = std::env::var("API_KEY") {
if !headers.contains_key("Authorization") && !headers.contains_key("authorization") {
headers.insert("Authorization".to_string(), format!("Bearer {api_key}"));
debug!("Applied API_KEY environment variable to Authorization header");
}
}
// Check for X-API-Key style headers
if let Ok(x_api_key) = std::env::var("X_API_KEY") {
if !headers.contains_key("X-API-Key") && !headers.contains_key("x-api-key") {
headers.insert("X-API-Key".to_string(), x_api_key);
debug!("Applied X_API_KEY environment variable to X-API-Key header");
}
}
headers
}
impl Default for RateLimitConfig {
fn default() -> Self {
Self {
max_concurrent: 3, // Max 3 concurrent refreshes
delay_between_servers_ms: 1000, // 1 second delay between servers
max_requests_per_minute: 10, // Max 10 requests per minute per server
}
}
}
impl Default for ToolRefreshConfig {
fn default() -> Self {
Self {
enabled: true,
interval_hours: 24, // Daily refresh
start_time: "02:00".to_string(), // 2 AM UTC
servers: Vec::new(),
rate_limit: RateLimitConfig::default(),
}
}
}
impl Default for ScannerConfig {
fn default() -> Self {
Self {
llm: LLMConfig {
provider: "openai".to_string(),
model: "gpt-4o".to_string(),
base_url: "https://api.openai.com/v1/chat/completions".to_string(),
api_key: String::new(),
timeout: 30,
max_tokens: 4000,
temperature: 0.1,
},
scanner: ScannerSettings {
http_timeout: 30,
scan_timeout: 60,
detailed: false,
format: "table".to_string(),
parallel: true,
max_retries: 3,
retry_delay_ms: 1000,
llm_batch_size: 10,
enable_yara: true,
},
security: SecurityConfig {
enabled: true,
min_severity: "low".to_string(),
checks: SecurityChecks {
tool_poisoning: true,
secrets_leakage: true,
sql_injection: true,
command_injection: true,
path_traversal: true,
auth_bypass: true,
prompt_injection: true,
pii_leakage: true,
jailbreak: true,
},
},
logging: LoggingConfig {
level: "info".to_string(),
colored: true,
timestamps: true,
},
performance: PerformanceConfig {
tracking: true,
slow_threshold_ms: 5000,
},
}
}
}
/// Scanner Configuration Manager
pub struct ScannerConfigManager {
config_path: PathBuf,
}
impl ScannerConfigManager {
/// Create a new scanner configuration manager
pub fn new() -> Self {
let config_path = PathBuf::from("config.yaml");
Self { config_path }
}
/// Load configuration from config.yaml
pub fn load_config(&self) -> Result<ScannerConfig> {
if !self.config_path.exists() {
debug!("No config.yaml found, using default configuration");
return Ok(ScannerConfig::default());
}
let content = fs::read_to_string(&self.config_path)
.map_err(|e| anyhow!("Failed to read config.yaml: {}", e))?;
// Expand environment variables in the content
let expanded_content = Self::expand_env_vars(&content)?;
let config: ScannerConfig = serde_yaml::from_str(&expanded_content)
.map_err(|e| anyhow!("Failed to parse config.yaml: {}", e))?;
debug!("Loaded configuration from config.yaml");
Ok(config)
}
/// Expand environment variables in configuration content
/// Supports ${VAR:-default} syntax for environment variable substitution
fn expand_env_vars(content: &str) -> Result<String> {
use regex::Regex;
// Regex to match ${VAR:-default} or ${VAR} patterns
let env_var_regex = Regex::new(r"\$\{([A-Z_][A-Z0-9_]*)(:-([^}]*))?\}")
.map_err(|e| anyhow!("Failed to compile environment variable regex: {}", e))?;
// Use replace_all for efficient single-pass replacement
let result = env_var_regex.replace_all(content, |caps: ®ex::Captures| {
let var_name = &caps[1];
let default_value = caps.get(3).map(|m| m.as_str()).unwrap_or("");
// Get environment variable value or use default
let replacement = match std::env::var(var_name) {
Ok(value) if !value.is_empty() => value,
_ => default_value.to_string(),
};
debug!(
"Expanding environment variable: {} -> {}",
var_name,
if replacement.is_empty() {
"<empty>"
} else {
"<set>"
}
);
replacement
});
Ok(result.into_owned())
}
/// Save configuration to config.yaml
pub fn save_config(&self, config: &ScannerConfig) -> Result<()> {
let content = serde_yaml::to_string(config)
.map_err(|e| anyhow!("Failed to serialize configuration: {}", e))?;
fs::write(&self.config_path, content)
.map_err(|e| anyhow!("Failed to write config.yaml: {}", e))?;
debug!("Saved configuration to config.yaml");
Ok(())
}
/// Check if config.yaml exists
pub fn has_config_file(&self) -> bool {
self.config_path.exists()
}
}
#[cfg(test)]
mod scanner_config_tests {
use super::*;
use std::env;
#[test]
fn test_expand_env_vars_with_defaults() {
let content = r#"
llm:
provider: ${LLM_PROVIDER:-openai}
model: ${LLM_MODEL:-gpt-4o}
base_url: ${LLM_URL:-https://api.openai.com/v1/chat/completions}
api_key: ${LLM_API_KEY:-}
"#;
let result = ScannerConfigManager::expand_env_vars(content).unwrap();
// Should use defaults when environment variables are not set
assert!(result.contains("provider: openai"));
assert!(result.contains("model: gpt-4o"));
assert!(result.contains("base_url: https://api.openai.com/v1/chat/completions"));
assert!(result.contains("api_key: "));
}
#[test]
fn test_expand_env_vars_with_env_values() {
// Set test environment variables
env::set_var("TEST_LLM_PROVIDER", "anthropic");
env::set_var("TEST_LLM_MODEL", "claude-3");
env::set_var("TEST_LLM_URL", "https://api.anthropic.com/v1/messages");
env::set_var("TEST_LLM_API_KEY", "test-key-123");
let content = r#"
llm:
provider: ${TEST_LLM_PROVIDER:-openai}
model: ${TEST_LLM_MODEL:-gpt-4o}
base_url: ${TEST_LLM_URL:-https://api.openai.com/v1/chat/completions}
api_key: ${TEST_LLM_API_KEY:-}
"#;
let result = ScannerConfigManager::expand_env_vars(content).unwrap();
// Should use environment variable values
assert!(result.contains("provider: anthropic"));
assert!(result.contains("model: claude-3"));
assert!(result.contains("base_url: https://api.anthropic.com/v1/messages"));
assert!(result.contains("api_key: test-key-123"));
// Clean up test environment variables
env::remove_var("TEST_LLM_PROVIDER");
env::remove_var("TEST_LLM_MODEL");
env::remove_var("TEST_LLM_URL");
env::remove_var("TEST_LLM_API_KEY");
}
#[test]
fn test_expand_env_vars_mixed_content() {
env::set_var("TEST_MIXED_VAR", "test-value");
let content = r#"
normal_field: regular_value
env_field: ${TEST_MIXED_VAR:-default}
another_field: ${NONEXISTENT_VAR:-fallback}
"#;
let result = ScannerConfigManager::expand_env_vars(content).unwrap();
assert!(result.contains("normal_field: regular_value"));
assert!(result.contains("env_field: test-value"));
assert!(result.contains("another_field: fallback"));
env::remove_var("TEST_MIXED_VAR");
}
#[test]
fn test_config_loading_with_env_vars() {
// Set test environment variables
env::set_var("TEST_CONFIG_LLM_PROVIDER", "test-provider");
env::set_var("TEST_CONFIG_LLM_MODEL", "test-model");
env::set_var("TEST_CONFIG_LLM_API_KEY", "test-key");
// Create a temporary config content
let config_content = r#"
llm:
provider: ${TEST_CONFIG_LLM_PROVIDER:-openai}
model: ${TEST_CONFIG_LLM_MODEL:-gpt-4o}
base_url: ${TEST_CONFIG_LLM_URL:-https://api.openai.com/v1/chat/completions}
api_key: ${TEST_CONFIG_LLM_API_KEY:-}
timeout: 30
max_tokens: 4000
temperature: 0.1
scanner:
http_timeout: 30
scan_timeout: 60
detailed: false
format: table
parallel: true
max_retries: 3
retry_delay_ms: 1000
llm_batch_size: 10
enable_yara: true
security:
enabled: true
min_severity: low
checks:
tool_poisoning: true
secrets_leakage: true
sql_injection: true
command_injection: true
path_traversal: true
auth_bypass: true
prompt_injection: true
pii_leakage: true
jailbreak: true
logging:
level: warn
colored: true
timestamps: true
performance:
tracking: true
slow_threshold_ms: 5000
"#;
// Expand environment variables
let expanded = ScannerConfigManager::expand_env_vars(config_content).unwrap();
// Parse the expanded configuration
let config: ScannerConfig = serde_yaml::from_str(&expanded).unwrap();
// Verify the environment variables were used
assert_eq!(config.llm.provider, "test-provider");
assert_eq!(config.llm.model, "test-model");
assert_eq!(
config.llm.base_url,
"https://api.openai.com/v1/chat/completions"
); // default used
assert_eq!(config.llm.api_key, "test-key");
// Clean up
env::remove_var("TEST_CONFIG_LLM_PROVIDER");
env::remove_var("TEST_CONFIG_LLM_MODEL");
env::remove_var("TEST_CONFIG_LLM_API_KEY");
}
#[test]
fn test_security_scanner_with_env_config() {
use crate::security::SecurityScanner;
// Set test environment variables
env::set_var("TEST_SECURITY_LLM_PROVIDER", "test-provider");
env::set_var("TEST_SECURITY_LLM_MODEL", "test-model");
env::set_var("TEST_SECURITY_LLM_URL", "https://test.api.com/v1/chat");
env::set_var("TEST_SECURITY_LLM_API_KEY", "test-security-key");
// Create a config with environment variables
let config_content = r#"
llm:
provider: ${TEST_SECURITY_LLM_PROVIDER:-openai}
model: ${TEST_SECURITY_LLM_MODEL:-gpt-4o}
base_url: ${TEST_SECURITY_LLM_URL:-https://api.openai.com/v1/chat/completions}
api_key: ${TEST_SECURITY_LLM_API_KEY:-}
timeout: 30
max_tokens: 4000
temperature: 0.1
scanner:
http_timeout: 30
scan_timeout: 60
detailed: false
format: table
parallel: true
max_retries: 3
retry_delay_ms: 1000
llm_batch_size: 10
enable_yara: true
security:
enabled: true
min_severity: low
checks:
tool_poisoning: true
secrets_leakage: true
sql_injection: true
command_injection: true
path_traversal: true
auth_bypass: true
prompt_injection: true
pii_leakage: true
jailbreak: true
logging:
level: warn
colored: true
timestamps: true
performance:
tracking: true
slow_threshold_ms: 5000
"#;
// Expand environment variables and parse config
let expanded = ScannerConfigManager::expand_env_vars(config_content).unwrap();
let config: ScannerConfig = serde_yaml::from_str(&expanded).unwrap();
// Create SecurityScanner with the config
let security_scanner = SecurityScanner::with_config(config);
// Verify the SecurityScanner has the correct configuration
assert_eq!(security_scanner.model_name, "test-model");
assert_eq!(
security_scanner.model_endpoint,
Some("https://test.api.com/v1/chat".to_string())
);
assert_eq!(
security_scanner.api_key,
Some("test-security-key".to_string())
);
// Clean up
env::remove_var("TEST_SECURITY_LLM_PROVIDER");
env::remove_var("TEST_SECURITY_LLM_MODEL");
env::remove_var("TEST_SECURITY_LLM_URL");
env::remove_var("TEST_SECURITY_LLM_API_KEY");
}
}