sqry-mcp 7.2.0

MCP server for sqry semantic code search
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
#[cfg(any(test, fuzzing))]
use anyhow::{Result, bail, ensure};
#[cfg(any(test, fuzzing))]
use serde_json::Value;

#[derive(Debug, Clone, Default)]
pub struct SearchFilters {
    pub languages: Vec<String>,
    pub visibility: Option<Visibility>,
    pub kinds: Vec<String>,
    pub min_score: Option<f64>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Visibility {
    Public,
    Private,
}

#[derive(Debug, Clone)]
pub struct PaginationArgs {
    pub offset: usize,
    pub size: usize,
}

#[derive(Debug, Clone)]
pub struct SemanticSearchArgs {
    pub query: String,
    pub path: String,
    pub filters: SearchFilters,
    pub max_results: usize,
    pub context_lines: usize,
    pub pagination: PaginationArgs,
    pub score_min: Option<f64>,
    /// Whether to include classpath (external dependency) results.
    /// Defaults to `false` — only workspace results are returned.
    pub include_classpath: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RelationType {
    Callers,
    Callees,
    Imports,
    Exports,
    Returns,
}

impl RelationType {
    pub fn as_str(self) -> &'static str {
        match self {
            RelationType::Callers => "callers",
            RelationType::Callees => "callees",
            RelationType::Imports => "imports",
            RelationType::Exports => "exports",
            RelationType::Returns => "returns",
        }
    }
}

#[derive(Debug, Clone)]
pub struct RelationQueryArgs {
    pub symbol: String,
    pub relation: RelationType,
    pub path: String,
    pub max_depth: usize,
    pub max_results: usize,
    pub pagination: PaginationArgs,
}

#[derive(Debug, Clone)]
pub struct ExplainCodeArgs {
    pub file_path: String,
    pub symbol_name: String,
    pub path: String,
    pub include_context: bool,
    pub include_relations: bool,
}

#[derive(Debug, Clone)]
pub struct ShowDependenciesArgs {
    pub file_path: Option<String>,
    pub symbol_name: Option<String>,
    pub path: String,
    pub max_depth: usize,
    pub max_results: usize,
    pub pagination: PaginationArgs,
}

#[derive(Debug, Clone)]
#[allow(clippy::struct_excessive_bools)] // Mirrors MCP tool flags without extra wrapper types.
pub struct ExportGraphArgs {
    pub file_path: Option<String>,
    pub symbol_name: Option<String>,
    /// Multiple seed symbol names (alternative to `symbol_name` for multi-seed exports)
    pub symbols: Vec<String>,
    pub path: String,
    pub format: String,
    pub max_depth: usize,
    pub max_results: usize,
    pub pagination: PaginationArgs,
    pub include_calls: bool,
    pub include_imports: bool,
    pub include_exports: bool,
    pub include_returns: bool,
    pub languages: Vec<String>,
    pub verbose: bool,
}

#[derive(Debug, Clone)]
pub struct CrossLanguageEdgesArgs {
    pub path: String,
    pub from_lang: Option<String>,
    pub to_lang: Option<String>,
    pub max_results: usize,
    pub pagination: PaginationArgs,
}

#[derive(Debug, Clone)]
pub struct TracePathArgs {
    pub from_symbol: String,
    pub to_symbol: String,
    pub path: String,
    pub max_hops: usize,
    pub max_paths: usize,
    pub cross_language: bool,
    pub min_confidence: f64,
}

#[derive(Debug, Clone)]
#[allow(clippy::struct_excessive_bools)] // Mirrors MCP tool flags without extra wrapper types.
pub struct SubgraphArgs {
    pub symbols: Vec<String>,
    pub path: String,
    pub max_depth: usize,
    pub max_nodes: usize,
    pub include_callers: bool,
    pub include_callees: bool,
    pub include_imports: bool,
    pub cross_language: bool,
    pub pagination: PaginationArgs,
}

#[derive(Debug, Clone)]
pub struct GetIndexStatusArgs {
    pub path: String,
}

/// Arguments for `find_duplicates` tool
#[derive(Debug, Clone)]
pub struct FindDuplicatesArgs {
    pub path: String,
    pub duplicate_type: DuplicateType,
    pub threshold: u32,
    pub exact: bool,
    pub max_results: usize,
    pub pagination: PaginationArgs,
}

/// Duplicate type enum for `find_duplicates` tool
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DuplicateType {
    Body,
    Signature,
    Struct,
}

/// Arguments for `find_cycles` tool
#[derive(Debug, Clone)]
pub struct FindCyclesArgs {
    pub path: String,
    pub cycle_type: CycleType,
    pub min_depth: usize,
    pub max_depth: Option<usize>,
    pub include_self_loops: bool,
    pub max_results: usize,
    pub pagination: PaginationArgs,
}

/// Cycle type enum for `find_cycles` tool
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CycleType {
    Calls,
    Imports,
    Modules,
}

/// Arguments for `find_unused` tool
///
/// Note: Some fields are reserved for future use when reachability analysis
/// is fully implemented for `CodeGraph`.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct FindUnusedArgs {
    pub path: String,
    pub scope: UnusedScope,
    pub languages: Vec<String>,
    pub kinds: Vec<String>,
    pub max_results: usize,
    pub pagination: PaginationArgs,
}

/// Scope enum for `find_unused` tool
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnusedScope {
    Public,
    Private,
    Function,
    Struct,
    All,
}

#[derive(Debug, Clone)]
pub struct SearchSimilarArgs {
    pub path: String,
    pub file_path: String,
    pub symbol_name: String,
    pub similarity_threshold: f64,
    pub max_results: usize,
    pub pagination: PaginationArgs,
}

#[derive(Debug, Clone)]
pub struct DependencyImpactArgs {
    pub symbol: String,
    pub path: String,
    pub max_depth: usize,
    pub include_files: bool,
    pub include_indirect: bool,
    pub max_results: usize,
    pub pagination: PaginationArgs,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ChangeType {
    Added,
    Removed,
    Modified,
    Renamed,
    SignatureChanged,
}

impl ChangeType {
    pub fn as_str(&self) -> &'static str {
        match self {
            ChangeType::Added => "added",
            ChangeType::Removed => "removed",
            ChangeType::Modified => "modified",
            ChangeType::Renamed => "renamed",
            ChangeType::SignatureChanged => "signature_changed",
        }
    }
}

#[derive(Debug, Clone, Default)]
pub struct SemanticDiffFilters {
    pub change_types: Vec<ChangeType>,
    pub symbol_kinds: Vec<String>,
}

#[derive(Debug, Clone)]
pub struct GitVersionRef {
    pub git_ref: String,
    #[allow(dead_code)]
    pub file_path: Option<String>,
}

#[derive(Debug, Clone)]
pub struct SemanticDiffArgs {
    pub base: GitVersionRef,
    pub target: GitVersionRef,
    #[allow(dead_code)]
    pub path: String,
    pub include_unchanged: bool,
    pub filters: SemanticDiffFilters,
    pub max_results: usize,
    pub pagination: PaginationArgs,
}

/// Arguments for `hierarchical_search` tool
/// Semantic search with file → container → symbol grouping for RAG
#[derive(Debug, Clone)]
pub struct HierarchicalSearchArgs {
    /// Semantic query expression
    pub query: String,
    /// Workspace-relative directory to search
    pub path: String,
    /// Search filters (same as `semantic_search`)
    pub filters: SearchFilters,
    /// Maximum symbols before grouping (default: 200)
    pub max_results: usize,
    /// Context lines around matches (default: 3)
    pub context_lines: usize,
    /// Pagination arguments
    pub pagination: PaginationArgs,
    /// Minimum relevance score
    pub score_min: Option<f64>,
    /// Enable auto-merge of small contexts (default: true)
    pub auto_merge: bool,
    /// Token threshold for auto-merge (default: 256)
    pub merge_threshold: usize,
    /// Maximum files per page (default: 20)
    pub max_files: usize,
    /// Maximum containers per file (default: 50)
    pub max_containers_per_file: usize,
    /// Maximum symbols per container (default: 100)
    pub max_symbols_per_container: usize,
    /// Hard limit on total symbols (default: 2000)
    pub max_total_symbols: usize,
    /// Target tokens for file-level grouping (default: 2000)
    pub file_target_tokens: u64,
    /// Target tokens for container-level grouping (default: 1500)
    pub container_target_tokens: u64,
    /// Target tokens for symbol-level detail (default: 500)
    pub symbol_target_tokens: u64,
    /// Target tokens for context clusters (default: 768)
    pub context_cluster_target_tokens: u64,
    /// Include file-level code summary (default: false)
    pub include_file_context: bool,
    /// Include container-level code (default: false)
    pub include_container_context: bool,
    /// File paths to expand (load full details for stubs)
    /// Use this to lazily load specific files from a previous stub response
    pub expand_files: Vec<String>,
}

/// Validate `semantic_search` arguments.
///
/// # Errors
///
/// Returns an error if required fields are missing or values are out of range.
#[cfg(any(test, fuzzing))]
pub fn validate_semantic_search_args(args: &Value) -> Result<SemanticSearchArgs> {
    let query = args
        .get("query")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing required field: query"))?;
    if query.trim().is_empty() {
        bail!("query cannot be empty");
    }

    let path = args.get("path").and_then(|v| v.as_str()).unwrap_or(".");

    let max_results = args
        .get("max_results")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(200);
    ensure!(
        (1..=10_000).contains(&max_results),
        "max_results must be between 1 and 10000"
    );

    let context_lines = args
        .get("context_lines")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(3);
    ensure!(
        (0..=20).contains(&context_lines),
        "context_lines must be between 0 and 20"
    );

    let filters = parse_filters(args.get("filters"), args)?;
    let pagination = parse_pagination(args, 50, 500)?;

    let score_min = filters.min_score;

    let include_classpath = args
        .get("include_classpath")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false);

    Ok(SemanticSearchArgs {
        query: query.to_string(),
        path: path.to_string(),
        filters,
        // Validated i64 fits in usize on this platform; reject if out of range
        max_results: max_results
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_results out of range"))?,
        context_lines: context_lines
            .try_into()
            .map_err(|_| anyhow::anyhow!("context_lines out of range"))?,
        pagination,
        score_min,
        include_classpath,
    })
}

/// Validate `relation_query` arguments.
///
/// # Errors
///
/// Returns an error if required fields are missing or values are invalid.
#[cfg(any(test, fuzzing))]
pub fn validate_relation_query_args(args: &Value) -> Result<RelationQueryArgs> {
    let symbol = args
        .get("symbol")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing required field: symbol"))?;
    if symbol.trim().is_empty() {
        bail!("symbol cannot be empty");
    }

    let relation = match args
        .get("relation_type")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing required field: relation_type"))?
    {
        "callers" => RelationType::Callers,
        "callees" => RelationType::Callees,
        "imports" => RelationType::Imports,
        "exports" => RelationType::Exports,
        "returns" => RelationType::Returns,
        other => bail!("Unsupported relation_type: {other}"),
    };

    let path = args.get("path").and_then(|v| v.as_str()).unwrap_or(".");

    let max_depth = args
        .get("max_depth")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(1);
    ensure!(
        (1..=5).contains(&max_depth),
        "max_depth must be between 1 and 5"
    );

    let max_results = args
        .get("max_results")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(200);
    ensure!(
        (1..=5_000).contains(&max_results),
        "max_results must be between 1 and 5000"
    );

    let pagination = parse_pagination(args, 50, 500)?;

    Ok(RelationQueryArgs {
        symbol: symbol.to_string(),
        relation,
        path: path.to_string(),
        // Validated i64 fits in usize on this platform; reject if out of range
        max_depth: max_depth
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_depth out of range"))?,
        max_results: max_results
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_results out of range"))?,
        pagination,
    })
}

/// Validate `explain_code` arguments.
///
/// # Errors
///
/// Returns an error if required fields are missing or values are invalid.
#[cfg(any(test, fuzzing))]
pub fn validate_explain_code_args(args: &Value) -> Result<ExplainCodeArgs> {
    let file_path = args
        .get("file_path")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing required field: file_path"))?;
    let symbol_name = args
        .get("symbol_name")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing required field: symbol_name"))?;

    if symbol_name.trim().is_empty() {
        bail!("symbol_name cannot be empty");
    }

    let path = args.get("path").and_then(|v| v.as_str()).unwrap_or(".");
    let include_context = args
        .get("include_context")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(true);
    let include_relations = args
        .get("include_relations")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(true);

    Ok(ExplainCodeArgs {
        file_path: file_path.to_string(),
        symbol_name: symbol_name.to_string(),
        path: path.to_string(),
        include_context,
        include_relations,
    })
}

/// Validate `show_dependencies` arguments.
///
/// # Errors
///
/// Returns an error if required fields are missing or values are invalid.
#[cfg(any(test, fuzzing))]
pub fn validate_show_dependencies_args(args: &Value) -> Result<ShowDependenciesArgs> {
    let file_path = args
        .get("file_path")
        .and_then(|v| v.as_str())
        .map(str::to_string);
    let symbol_name = args
        .get("symbol_name")
        .and_then(|v| v.as_str())
        .map(std::string::ToString::to_string);
    if file_path.is_none() && symbol_name.is_none() {
        bail!("At least one of file_path or symbol_name must be provided");
    }

    let path = args.get("path").and_then(|v| v.as_str()).unwrap_or(".");

    let max_depth = args
        .get("max_depth")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(2);
    ensure!(
        (1..=5).contains(&max_depth),
        "max_depth must be between 1 and 5"
    );

    let max_results = args
        .get("max_results")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(500);
    ensure!(
        (1..=5_000).contains(&max_results),
        "max_results must be between 1 and 5000"
    );

    let pagination = parse_pagination(args, 100, 1_000)?;

    Ok(ShowDependenciesArgs {
        file_path,
        symbol_name,
        path: path.to_string(),
        // Validated i64 fits in usize on this platform; reject if out of range
        max_depth: max_depth
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_depth out of range"))?,
        max_results: max_results
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_results out of range"))?,
        pagination,
    })
}

/// Validate `export_graph` arguments.
///
/// # Errors
///
/// Returns an error if required fields are missing or values are invalid.
#[cfg(any(test, fuzzing))]
pub fn validate_export_graph_args(args: &Value) -> Result<ExportGraphArgs> {
    let file_path = args
        .get("file_path")
        .and_then(|v| v.as_str())
        .map(str::to_string);
    let symbol_name = args
        .get("symbol_name")
        .and_then(|v| v.as_str())
        .map(std::string::ToString::to_string);
    let symbols = args
        .get("symbols")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(std::string::ToString::to_string))
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();
    if file_path.is_none() && symbol_name.is_none() && symbols.is_empty() {
        bail!("At least one of file_path, symbol_name, or symbols must be provided");
    }

    let path = args.get("path").and_then(|v| v.as_str()).unwrap_or(".");

    let max_depth = args
        .get("max_depth")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(2);
    ensure!(
        (1..=5).contains(&max_depth),
        "max_depth must be between 1 and 5"
    );

    let max_results = args
        .get("max_results")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(1000);
    ensure!(
        (1..=5_000).contains(&max_results),
        "max_results must be between 1 and 5000"
    );

    // Edge kind inclusion
    let mut include_calls = true; // default to calls
    let mut include_imports = false;
    let mut include_exports = false;
    let mut include_returns = false;
    if let Some(include) = args.get("include").and_then(|v| v.as_array()) {
        include_calls = false;
        for item in include {
            let s = item
                .as_str()
                .ok_or_else(|| anyhow::anyhow!("include entries must be strings"))?;
            match s {
                "calls" => include_calls = true,
                "imports" => include_imports = true,
                "exports" => include_exports = true,
                "returns" => include_returns = true,
                other => bail!("Unsupported include kind: {other}"),
            }
        }
    }

    let languages = args
        .get("languages")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(|s| s.trim().to_string()))
                .filter(|s| !s.is_empty())
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();

    let pagination = parse_pagination(args, 200, 1_000)?;

    let format = args
        .get("format")
        .and_then(|v| v.as_str())
        .unwrap_or("json");
    ensure!(
        matches!(format, "json" | "dot" | "d2" | "mermaid"),
        "format must be one of: json | dot | d2 | mermaid"
    );

    Ok(ExportGraphArgs {
        file_path,
        symbol_name,
        symbols,
        path: path.to_string(),
        format: format.to_string(),
        // Validated i64 fits in usize on this platform; reject if out of range
        max_depth: max_depth
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_depth out of range"))?,
        max_results: max_results
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_results out of range"))?,
        pagination,
        include_calls,
        include_imports,
        include_exports,
        include_returns,
        languages,
        verbose: args
            .get("verbose")
            .and_then(serde_json::Value::as_bool)
            .unwrap_or(false),
    })
}

/// Validate `cross_language_edges` arguments.
///
/// # Errors
///
/// Returns an error if required fields are missing or values are invalid.
#[cfg(any(test, fuzzing))]
pub fn validate_cross_language_edges_args(args: &Value) -> Result<CrossLanguageEdgesArgs> {
    let path = args.get("path").and_then(|v| v.as_str()).unwrap_or(".");
    let from_lang = args
        .get("from_lang")
        .and_then(|v| v.as_str())
        .map(std::string::ToString::to_string);
    let to_lang = args
        .get("to_lang")
        .and_then(|v| v.as_str())
        .map(std::string::ToString::to_string);

    let max_results = args
        .get("max_results")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(500);
    ensure!(
        (1..=5_000).contains(&max_results),
        "max_results must be between 1 and 5000"
    );

    let pagination = parse_pagination(args, 200, 1_000)?;

    Ok(CrossLanguageEdgesArgs {
        path: path.to_string(),
        from_lang,
        to_lang,
        // Validated i64 fits in usize on this platform; reject if out of range
        max_results: max_results
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_results out of range"))?,
        pagination,
    })
}

/// Validate `trace_path` arguments.
///
/// # Errors
///
/// Returns an error if required fields are missing or values are invalid.
#[cfg(any(test, fuzzing))]
pub fn validate_trace_path_args(args: &Value) -> Result<TracePathArgs> {
    let from_symbol = args
        .get("from_symbol")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing required field 'from_symbol'"))?;

    let to_symbol = args
        .get("to_symbol")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing required field 'to_symbol'"))?;

    let path = args.get("path").and_then(|v| v.as_str()).unwrap_or(".");

    let max_hops = args
        .get("max_hops")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(5);
    ensure!(
        (1..=10).contains(&max_hops),
        "max_hops must be between 1 and 10"
    );

    let max_paths = args
        .get("max_paths")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(5);
    ensure!(
        (1..=20).contains(&max_paths),
        "max_paths must be between 1 and 20"
    );

    let cross_language = args
        .get("cross_language")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(true);

    let min_confidence = args
        .get("min_confidence")
        .and_then(serde_json::Value::as_f64)
        .unwrap_or(0.5);
    ensure!(
        (0.0..=1.0).contains(&min_confidence),
        "min_confidence must be between 0.0 and 1.0"
    );

    Ok(TracePathArgs {
        from_symbol: from_symbol.to_string(),
        to_symbol: to_symbol.to_string(),
        path: path.to_string(),
        // Validated i64 fits in usize on this platform; reject if out of range
        max_hops: max_hops
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_hops out of range"))?,
        max_paths: max_paths
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_paths out of range"))?,
        cross_language,
        min_confidence,
    })
}

/// Validate `subgraph` arguments.
///
/// # Errors
///
/// Returns an error if required fields are missing or values are invalid.
#[cfg(any(test, fuzzing))]
pub fn validate_subgraph_args(args: &Value) -> Result<SubgraphArgs> {
    let symbols_array = args
        .get("symbols")
        .and_then(|v| v.as_array())
        .ok_or_else(|| anyhow::anyhow!("Missing required field 'symbols' (must be an array)"))?;

    let symbols: Vec<String> = symbols_array
        .iter()
        .filter_map(|v| v.as_str())
        .map(std::string::ToString::to_string)
        .collect();

    if symbols.is_empty() {
        bail!("symbols array must contain at least one symbol");
    }

    let path = args.get("path").and_then(|v| v.as_str()).unwrap_or(".");

    let max_depth = args
        .get("max_depth")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(2);
    ensure!(
        (1..=5).contains(&max_depth),
        "max_depth must be between 1 and 5"
    );

    let max_nodes = args
        .get("max_nodes")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(50);
    ensure!(
        (1..=500).contains(&max_nodes),
        "max_nodes must be between 1 and 500"
    );

    let include_incoming_calls = args
        .get("include_callers")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(true);

    let include_outgoing_calls = args
        .get("include_callees")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(true);

    let include_imports = args
        .get("include_imports")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false);

    let cross_language = args
        .get("cross_language")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(true);

    let pagination = parse_pagination(args, 50, 200)?;

    Ok(SubgraphArgs {
        symbols,
        path: path.to_string(),
        // Validated i64 fits in usize on this platform; reject if out of range
        max_depth: max_depth
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_depth out of range"))?,
        max_nodes: max_nodes
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_nodes out of range"))?,
        include_callers: include_incoming_calls,
        include_callees: include_outgoing_calls,
        include_imports,
        cross_language,
        pagination,
    })
}

#[must_use]
#[cfg(any(test, fuzzing))]
pub fn validate_get_index_status_args(args: &Value) -> GetIndexStatusArgs {
    let path = args.get("path").and_then(|v| v.as_str()).unwrap_or(".");

    GetIndexStatusArgs {
        path: path.to_string(),
    }
}

/// Validate `search_similar` arguments.
///
/// # Errors
///
/// Returns an error if required fields are missing or values are invalid.
#[cfg(any(test, fuzzing))]
pub fn validate_search_similar_args(args: &Value) -> Result<SearchSimilarArgs> {
    let reference = args
        .get("reference")
        .ok_or_else(|| anyhow::anyhow!("Missing required field: reference"))?;
    let reference_obj = reference
        .as_object()
        .ok_or_else(|| anyhow::anyhow!("reference must be an object"))?;

    let file_path = reference_obj
        .get("file_path")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("reference.file_path is required"))?;
    let symbol_name = reference_obj
        .get("symbol_name")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("reference.symbol_name is required"))?;
    if symbol_name.trim().is_empty() {
        bail!("reference.symbol_name cannot be empty");
    }

    let path = args.get("path").and_then(|v| v.as_str()).unwrap_or(".");

    let similarity_threshold = args
        .get("similarity_threshold")
        .and_then(serde_json::Value::as_f64)
        .unwrap_or(0.7);
    ensure!(
        (0.0..=1.0).contains(&similarity_threshold),
        "similarity_threshold must be between 0.0 and 1.0"
    );

    let max_results = args
        .get("max_results")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(20);
    ensure!(
        (1..=200).contains(&max_results),
        "max_results must be between 1 and 200"
    );

    let pagination = parse_pagination(args, 20, 200)?;

    Ok(SearchSimilarArgs {
        path: path.to_string(),
        file_path: file_path.to_string(),
        symbol_name: symbol_name.to_string(),
        similarity_threshold,
        // Validated i64 fits in usize on this platform; reject if out of range
        max_results: max_results
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_results out of range"))?,
        pagination,
    })
}

/// Validate `dependency_impact` arguments.
///
/// # Errors
///
/// Returns an error if required fields are missing or values are invalid.
#[cfg(any(test, fuzzing))]
pub fn validate_dependency_impact_args(args: &Value) -> Result<DependencyImpactArgs> {
    let symbol = args
        .get("symbol")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing required field: symbol"))?;
    if symbol.trim().is_empty() {
        bail!("symbol cannot be empty");
    }

    let path = args.get("path").and_then(|v| v.as_str()).unwrap_or(".");

    let max_depth = args
        .get("max_depth")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(3);
    ensure!(
        (1..=10).contains(&max_depth),
        "max_depth must be between 1 and 10"
    );

    let include_files = args
        .get("include_files")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(true);

    let include_indirect = args
        .get("include_indirect")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(true);

    let max_results = args
        .get("max_results")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(500);
    ensure!(
        (1..=5_000).contains(&max_results),
        "max_results must be between 1 and 5000"
    );

    let pagination = parse_pagination(args, 100, 500)?;

    Ok(DependencyImpactArgs {
        symbol: symbol.to_string(),
        path: path.to_string(),
        // Validated i64 fits in usize on this platform; reject if out of range
        max_depth: max_depth
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_depth out of range"))?,
        include_files,
        include_indirect,
        max_results: max_results
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_results out of range"))?,
        pagination,
    })
}

/// Validate `semantic_diff` arguments.
///
/// # Errors
///
/// Returns an error if required fields are missing or values are invalid.
#[cfg(any(test, fuzzing))]
pub fn validate_semantic_diff_args(args: &Value) -> Result<SemanticDiffArgs> {
    let base = args
        .get("base")
        .ok_or_else(|| anyhow::anyhow!("Missing required field: base"))?;
    let base_obj = base
        .as_object()
        .ok_or_else(|| anyhow::anyhow!("base must be an object"))?;
    let base_ref = base_obj
        .get("ref")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("base.ref is required"))?;
    if base_ref.trim().is_empty() {
        bail!("base.ref cannot be empty");
    }
    let base_file_path = base_obj
        .get("file_path")
        .and_then(|v| v.as_str())
        .map(std::string::ToString::to_string);

    let target = args
        .get("target")
        .ok_or_else(|| anyhow::anyhow!("Missing required field: target"))?;
    let target_obj = target
        .as_object()
        .ok_or_else(|| anyhow::anyhow!("target must be an object"))?;
    let target_ref = target_obj
        .get("ref")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("target.ref is required"))?;
    if target_ref.trim().is_empty() {
        bail!("target.ref cannot be empty");
    }
    let target_file_path = target_obj
        .get("file_path")
        .and_then(|v| v.as_str())
        .map(std::string::ToString::to_string);

    let path = args.get("path").and_then(|v| v.as_str()).unwrap_or(".");

    let include_unchanged = args
        .get("include_unchanged")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false);

    let filters = parse_semantic_diff_filters(args.get("filters"))?;

    let max_results = args
        .get("max_results")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(500);
    ensure!(
        (1..=5_000).contains(&max_results),
        "max_results must be between 1 and 5000"
    );

    let pagination = parse_pagination(args, 100, 500)?;

    Ok(SemanticDiffArgs {
        base: GitVersionRef {
            git_ref: base_ref.to_string(),
            file_path: base_file_path,
        },
        target: GitVersionRef {
            git_ref: target_ref.to_string(),
            file_path: target_file_path,
        },
        path: path.to_string(),
        include_unchanged,
        filters,
        // Validated i64 fits in usize on this platform; reject if out of range
        max_results: max_results
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_results out of range"))?,
        pagination,
    })
}

#[cfg(any(test, fuzzing))]
fn parse_semantic_diff_filters(value: Option<&Value>) -> Result<SemanticDiffFilters> {
    let Some(val) = value else {
        return Ok(SemanticDiffFilters::default());
    };
    ensure!(
        val.is_object(),
        "filters must be a JSON object, not a string. \
         Pass a structured object like {{\"language\":[\"rust\"]}}."
    );
    let mut filters = SemanticDiffFilters::default();

    if let Some(change_types_val) = val.get("change_types") {
        let change_types = change_types_val
            .as_array()
            .ok_or_else(|| anyhow::anyhow!("filters.change_types must be an array"))?
            .iter()
            .map(|entry| {
                let s = entry.as_str().ok_or_else(|| {
                    anyhow::anyhow!("filters.change_types entries must be strings")
                })?;
                match s {
                    "added" => Ok(ChangeType::Added),
                    "removed" => Ok(ChangeType::Removed),
                    "modified" => Ok(ChangeType::Modified),
                    "renamed" => Ok(ChangeType::Renamed),
                    "signature_changed" => Ok(ChangeType::SignatureChanged),
                    other => bail!("Invalid change type: {other}"),
                }
            })
            .collect::<Result<Vec<_>>>()?;
        filters.change_types = change_types;
    }

    if let Some(symbol_kinds_val) = val.get("symbol_kinds") {
        let kinds = symbol_kinds_val
            .as_array()
            .ok_or_else(|| anyhow::anyhow!("filters.symbol_kinds must be an array"))?
            .iter()
            .map(|entry| {
                let s = entry.as_str().ok_or_else(|| {
                    anyhow::anyhow!("filters.symbol_kinds entries must be strings")
                })?;
                Ok(s.trim().to_string())
            })
            .collect::<Result<Vec<_>>>()?;
        filters.symbol_kinds = kinds.into_iter().filter(|s| !s.is_empty()).collect();
    }

    Ok(filters)
}

#[cfg(any(test, fuzzing))]
fn parse_filters(value: Option<&Value>, root: &Value) -> Result<SearchFilters> {
    let Some(val) = value else {
        return Ok(SearchFilters::default());
    };
    ensure!(
        val.is_object(),
        "filters must be a JSON object (e.g., {{\"language\":[\"rust\"]}}), \
         not a string. For string-style filtering, use query predicates \
         like 'lang:rust' in the `query` parameter instead."
    );
    let mut filters = SearchFilters::default();

    if let Some(lang_val) = val.get("language") {
        let langs = lang_val
            .as_array()
            .ok_or_else(|| anyhow::anyhow!("filters.language must be an array"))?
            .iter()
            .map(|entry| {
                let s = entry
                    .as_str()
                    .ok_or_else(|| anyhow::anyhow!("filters.language entries must be strings"))?;
                Ok(s.trim().to_string())
            })
            .collect::<Result<Vec<_>>>()?;
        filters.languages = langs.into_iter().filter(|s| !s.is_empty()).collect();
    }

    if let Some(vis_val) = val.get("visibility") {
        let vis_str = vis_val
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("filters.visibility must be a string"))?;
        filters.visibility = match vis_str {
            "public" => Some(Visibility::Public),
            "private" => Some(Visibility::Private),
            other => bail!("Invalid visibility: {other}"),
        };
    }

    if let Some(kind_val) = val.get("kind") {
        let kind = kind_val
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("filters.kind must be a string"))?;
        if kind.trim().is_empty() {
            bail!("filters.kind cannot be empty");
        }
        filters.kinds.push(kind.trim().to_string());
    }

    if let Some(kind_array) = val.get("symbol_kind") {
        let kinds = kind_array
            .as_array()
            .ok_or_else(|| anyhow::anyhow!("filters.symbol_kind must be an array"))?
            .iter()
            .map(|entry| {
                let s = entry.as_str().ok_or_else(|| {
                    anyhow::anyhow!("filters.symbol_kind entries must be strings")
                })?;
                Ok(s.trim().to_string())
            })
            .collect::<Result<Vec<_>>>()?;
        filters
            .kinds
            .extend(kinds.into_iter().filter(|s| !s.is_empty()));
    }

    if let Some(score_min) = val
        .get("score_min")
        .or_else(|| root.get("score_min"))
        .or_else(|| root.get("min_score"))
    {
        let score = score_min
            .as_f64()
            .ok_or_else(|| anyhow::anyhow!("score_min must be a number"))?;
        ensure!(
            (0.0..=1.0).contains(&score),
            "score_min must be between 0.0 and 1.0"
        );
        filters.min_score = Some(score);
    }

    filters.kinds.retain(|value| !value.trim().is_empty());

    Ok(filters)
}

#[cfg(any(test, fuzzing))]
fn parse_pagination(args: &Value, default_size: usize, max_size: usize) -> Result<PaginationArgs> {
    use crate::pagination::decode_cursor;

    let pagination_obj = args.get("pagination");

    let page_size = pagination_obj
        .and_then(|obj| obj.get("page_size").or_else(|| obj.get("pageSize")))
        .and_then(serde_json::Value::as_i64)
        .or_else(|| args.get("page_size").and_then(serde_json::Value::as_i64))
        // Validated i64 fits in usize on this platform; clamp to max
        .unwrap_or(default_size.try_into().unwrap_or(i64::MAX));
    // Validated i64 fits in usize on this platform; reject if out of range
    let page_size_usize: usize = page_size
        .try_into()
        .map_err(|_| anyhow::anyhow!("page_size out of range"))?;
    ensure!(
        page_size >= 1 && page_size_usize <= max_size,
        "page_size must be between 1 and {max_size}"
    );

    let cursor_value = pagination_obj
        .and_then(|obj| obj.get("cursor"))
        .or_else(|| args.get("page_token"));

    let offset = if let Some(token) = cursor_value {
        let token_str = token
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("cursor must be a string"))?;
        decode_cursor(token_str)?
    } else {
        0
    };

    Ok(PaginationArgs {
        offset,
        size: page_size_usize,
    })
}

/// Validate `hierarchical_search` arguments.
///
/// Hierarchical search returns semantic search results organized into a
/// file → container → symbol hierarchy optimized for RAG token budgets.
///
/// # Errors
///
/// Returns an error if required fields are missing or values are out of range.
#[allow(clippy::too_many_lines)] // Parsing logic mirrors MCP argument schema.
#[cfg(any(test, fuzzing))]
pub fn validate_hierarchical_search_args(args: &Value) -> Result<HierarchicalSearchArgs> {
    // Required: query
    let query = args
        .get("query")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing required field: query"))?;
    if query.trim().is_empty() {
        bail!("query cannot be empty");
    }

    let path = args.get("path").and_then(|v| v.as_str()).unwrap_or(".");

    // max_results: 1-1000, default 200
    let max_results = args
        .get("max_results")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(200);
    ensure!(
        (1..=1000).contains(&max_results),
        "max_results must be between 1 and 1000"
    );

    // context_lines: 0-20, default 3
    let context_lines = args
        .get("context_lines")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(3);
    ensure!(
        (0..=20).contains(&context_lines),
        "context_lines must be between 0 and 20"
    );

    // auto_merge: default true
    let auto_merge = args
        .get("auto_merge")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(true);

    // merge_threshold: 0-1000, default 256
    let merge_threshold = args
        .get("merge_threshold")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(256);
    ensure!(
        (0..=1000).contains(&merge_threshold),
        "merge_threshold must be between 0 and 1000"
    );

    // max_files: 1-100, default 20
    let max_files = args
        .get("max_files")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(20);
    ensure!(
        (1..=100).contains(&max_files),
        "max_files must be between 1 and 100"
    );

    // max_containers_per_file: 1-200, default 50
    let max_containers_per_file = args
        .get("max_containers_per_file")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(50);
    ensure!(
        (1..=200).contains(&max_containers_per_file),
        "max_containers_per_file must be between 1 and 200"
    );

    // max_symbols_per_container: 1-500, default 100
    let max_symbols_per_container = args
        .get("max_symbols_per_container")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(100);
    ensure!(
        (1..=500).contains(&max_symbols_per_container),
        "max_symbols_per_container must be between 1 and 500"
    );

    // max_total_symbols: 1-5000, default 2000
    let max_total_symbols = args
        .get("max_total_symbols")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(2000);
    ensure!(
        (1..=5000).contains(&max_total_symbols),
        "max_total_symbols must be between 1 and 5000"
    );

    // file_target_tokens: 100-10000, default 2000
    let file_target_tokens = args
        .get("file_target_tokens")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(2000);
    ensure!(
        (100..=10000).contains(&file_target_tokens),
        "file_target_tokens must be between 100 and 10000"
    );

    // container_target_tokens: 100-5000, default 1500
    let container_target_tokens = args
        .get("container_target_tokens")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(1500);
    ensure!(
        (100..=5000).contains(&container_target_tokens),
        "container_target_tokens must be between 100 and 5000"
    );

    // symbol_target_tokens: 50-2000, default 500
    let symbol_target_tokens = args
        .get("symbol_target_tokens")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(500);
    ensure!(
        (50..=2000).contains(&symbol_target_tokens),
        "symbol_target_tokens must be between 50 and 2000"
    );

    // context_cluster_target_tokens: 100-2000, default 768
    let context_cluster_target_tokens = args
        .get("context_cluster_target_tokens")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(768);
    ensure!(
        (100..=2000).contains(&context_cluster_target_tokens),
        "context_cluster_target_tokens must be between 100 and 2000"
    );

    // include_file_context: default false
    let include_file_context = args
        .get("include_file_context")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false);

    // include_container_context: default false
    let include_container_context = args
        .get("include_container_context")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false);

    // expand_files: array of file paths to expand from stubs (default: empty)
    let expand_files: Vec<String> = args
        .get("expand_files")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    let filters = parse_filters(args.get("filters"), args)?;
    let pagination = parse_pagination(args, 20, 100)?;

    let score_min = filters.min_score;

    Ok(HierarchicalSearchArgs {
        query: query.to_string(),
        path: path.to_string(),
        filters,
        max_results: max_results
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_results out of range"))?,
        context_lines: context_lines
            .try_into()
            .map_err(|_| anyhow::anyhow!("context_lines out of range"))?,
        pagination,
        score_min,
        auto_merge,
        merge_threshold: merge_threshold
            .try_into()
            .map_err(|_| anyhow::anyhow!("merge_threshold out of range"))?,
        max_files: max_files
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_files out of range"))?,
        max_containers_per_file: max_containers_per_file
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_containers_per_file out of range"))?,
        max_symbols_per_container: max_symbols_per_container
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_symbols_per_container out of range"))?,
        max_total_symbols: max_total_symbols
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_total_symbols out of range"))?,
        file_target_tokens: file_target_tokens
            .try_into()
            .map_err(|_| anyhow::anyhow!("file_target_tokens out of range"))?,
        container_target_tokens: container_target_tokens
            .try_into()
            .map_err(|_| anyhow::anyhow!("container_target_tokens out of range"))?,
        symbol_target_tokens: symbol_target_tokens
            .try_into()
            .map_err(|_| anyhow::anyhow!("symbol_target_tokens out of range"))?,
        context_cluster_target_tokens: context_cluster_target_tokens
            .try_into()
            .map_err(|_| anyhow::anyhow!("context_cluster_target_tokens out of range"))?,
        include_file_context,
        include_container_context,
        expand_files,
    })
}

/// Validate `sqry_ask` tool arguments (P2-18)
///
/// Deserializes and validates the natural language query parameters.
/// Returns a validated `SqryAskParams` ready for execution.
#[cfg(any(test, fuzzing))]
pub fn validate_sqry_ask_args(args: &Value) -> Result<super::params::SqryAskParams> {
    let query = args
        .get("query")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("Missing required field: query"))?;
    if query.trim().is_empty() {
        bail!("query cannot be empty");
    }
    ensure!(
        query.len() <= 4096,
        "query exceeds maximum length of 4096 characters"
    );

    // Validate path type - must be string if provided, fail on type mismatch
    let path = match args.get("path") {
        Some(v) if v.is_string() => v.as_str().unwrap(),
        Some(v) if v.is_null() => ".", // null is acceptable, defaults to "."
        Some(_) => bail!("path must be a string"),
        None => ".",
    };

    let execute = match args.get("execute") {
        Some(v) if v.is_boolean() => v.as_bool().unwrap_or(false),
        Some(v) if v.is_null() => false,
        Some(_) => bail!("execute must be a boolean"),
        None => false,
    };

    Ok(super::params::SqryAskParams {
        query: query.to_string(),
        path: path.to_string(),
        execute,
    })
}

/// Validate `find_duplicates` arguments.
///
/// # Errors
///
/// Returns an error if values are out of range.
#[cfg(any(test, fuzzing))]
pub fn validate_find_duplicates_args(args: &Value) -> Result<FindDuplicatesArgs> {
    let path = args.get("path").and_then(|v| v.as_str()).unwrap_or(".");

    let duplicate_type = match args
        .get("duplicate_type")
        .and_then(|v| v.as_str())
        .unwrap_or("body")
    {
        "body" => DuplicateType::Body,
        "signature" => DuplicateType::Signature,
        "struct" => DuplicateType::Struct,
        other => bail!("Invalid duplicate_type: {other}. Use: body, signature, struct"),
    };

    let threshold = args
        .get("threshold")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(80);
    ensure!(
        (0..=100).contains(&threshold),
        "threshold must be between 0 and 100"
    );

    let exact = args
        .get("exact")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false);

    let max_results = args
        .get("max_results")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(100);
    ensure!(
        (1..=1000).contains(&max_results),
        "max_results must be between 1 and 1000"
    );

    let pagination = parse_pagination(args, 50, 500)?;

    Ok(FindDuplicatesArgs {
        path: path.to_string(),
        duplicate_type,
        threshold: threshold
            .try_into()
            .map_err(|_| anyhow::anyhow!("threshold out of range"))?,
        exact,
        max_results: max_results
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_results out of range"))?,
        pagination,
    })
}

/// Validate `find_cycles` arguments.
///
/// # Errors
///
/// Returns an error if values are out of range.
#[cfg(any(test, fuzzing))]
pub fn validate_find_cycles_args(args: &Value) -> Result<FindCyclesArgs> {
    let path = args.get("path").and_then(|v| v.as_str()).unwrap_or(".");

    let cycle_type = match args
        .get("cycle_type")
        .and_then(|v| v.as_str())
        .unwrap_or("calls")
    {
        "calls" => CycleType::Calls,
        "imports" => CycleType::Imports,
        "modules" => CycleType::Modules,
        other => bail!("Invalid cycle_type: {other}. Use: calls, imports, modules"),
    };

    let min_depth = args
        .get("min_depth")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(2);
    ensure!(min_depth >= 2, "min_depth must be at least 2");

    let max_depth = args.get("max_depth").and_then(serde_json::Value::as_i64);
    if let Some(max) = max_depth {
        ensure!(max >= 2, "max_depth must be at least 2");
        ensure!(max >= min_depth, "max_depth must be >= min_depth");
    }

    let include_self_loops = args
        .get("include_self_loops")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false);

    let max_results = args
        .get("max_results")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(100);
    ensure!(
        (1..=500).contains(&max_results),
        "max_results must be between 1 and 500"
    );

    let pagination = parse_pagination(args, 50, 200)?;

    Ok(FindCyclesArgs {
        path: path.to_string(),
        cycle_type,
        min_depth: min_depth
            .try_into()
            .map_err(|_| anyhow::anyhow!("min_depth out of range"))?,
        max_depth: max_depth
            .map(|v| {
                v.try_into()
                    .map_err(|_| anyhow::anyhow!("max_depth out of range"))
            })
            .transpose()?,
        include_self_loops,
        max_results: max_results
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_results out of range"))?,
        pagination,
    })
}

/// Validate `find_unused` arguments.
///
/// # Errors
///
/// Returns an error if values are out of range.
#[cfg(any(test, fuzzing))]
pub fn validate_find_unused_args(args: &Value) -> Result<FindUnusedArgs> {
    let path = args.get("path").and_then(|v| v.as_str()).unwrap_or(".");

    let scope = match args.get("scope").and_then(|v| v.as_str()).unwrap_or("all") {
        "public" => UnusedScope::Public,
        "private" => UnusedScope::Private,
        "function" => UnusedScope::Function,
        "struct" => UnusedScope::Struct,
        "all" => UnusedScope::All,
        other => bail!("Invalid scope: {other}. Use: public, private, function, struct, all"),
    };

    let languages = args
        .get("language")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(|s| s.trim().to_string()))
                .filter(|s| !s.is_empty())
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();

    let kinds = args
        .get("symbol_kind")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(|s| s.trim().to_string()))
                .filter(|s| !s.is_empty())
                .collect::<Vec<_>>()
        })
        .unwrap_or_default();

    let max_results = args
        .get("max_results")
        .and_then(serde_json::Value::as_i64)
        .unwrap_or(100);
    ensure!(
        (1..=1000).contains(&max_results),
        "max_results must be between 1 and 1000"
    );

    let pagination = parse_pagination(args, 50, 500)?;

    Ok(FindUnusedArgs {
        path: path.to_string(),
        scope,
        languages,
        kinds,
        max_results: max_results
            .try_into()
            .map_err(|_| anyhow::anyhow!("max_results out of range"))?,
        pagination,
    })
}

// ============================================================================
// New Graph-Based Tool Args Types
// ============================================================================

/// Arguments for `is_node_in_cycle` tool.
#[derive(Debug, Clone)]
pub struct IsNodeInCycleArgs {
    /// Symbol to check
    pub symbol: String,
    /// Workspace path
    pub path: String,
    /// Type of cycle to check
    pub cycle_type: CycleType,
    /// Minimum cycle depth to consider
    pub min_depth: usize,
    /// Maximum cycle depth to consider (None = unbounded)
    pub max_depth: Option<usize>,
    /// Whether to include self-loops as cycles
    pub include_self_loops: bool,
}

/// Arguments for `pattern_search` tool.
#[derive(Debug, Clone)]
pub struct PatternSearchArgs {
    /// Search pattern (substring match)
    pub pattern: String,
    /// Workspace path
    pub path: String,
    /// Maximum results
    pub max_results: usize,
    /// Pagination
    pub pagination: PaginationArgs,
    /// Whether to include classpath (external dependency) results.
    /// Defaults to `false` — only workspace results are returned.
    pub include_classpath: bool,
}

/// Arguments for `direct_callers` tool.
#[derive(Debug, Clone)]
pub struct DirectCallersArgs {
    /// Symbol to find callers for
    pub symbol: String,
    /// Workspace path
    pub path: String,
    /// Maximum results
    pub max_results: usize,
    /// Pagination
    pub pagination: PaginationArgs,
}

/// Arguments for `direct_callees` tool.
#[derive(Debug, Clone)]
pub struct DirectCalleesArgs {
    /// Symbol to find callees for
    pub symbol: String,
    /// Workspace path
    pub path: String,
    /// Maximum results
    pub max_results: usize,
    /// Pagination
    pub pagination: PaginationArgs,
}

// ============================================================================
// Introspection Tool Args
// ============================================================================

/// Arguments for `list_files` tool.
#[derive(Debug, Clone)]
pub struct ListFilesArgs {
    /// Workspace path
    pub path: String,
    /// Optional language filter
    pub language: Option<String>,
    /// Maximum results
    pub max_results: usize,
    /// Pagination
    pub pagination: PaginationArgs,
}

/// Arguments for `list_symbols` tool.
#[derive(Debug, Clone)]
pub struct ListSymbolsArgs {
    /// Workspace path
    pub path: String,
    /// Optional kind filter (function, class, method, etc.)
    pub kind: Option<String>,
    /// Optional language filter
    pub language: Option<String>,
    /// Maximum results
    pub max_results: usize,
    /// Pagination
    pub pagination: PaginationArgs,
}

/// Arguments for `get_graph_stats` tool.
#[derive(Debug, Clone)]
pub struct GetGraphStatsArgs {
    /// Workspace path
    pub path: String,
}

// ============================================================================
// Navigation Tool Args
// ============================================================================

/// Arguments for `get_definition` tool.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct GetDefinitionArgs {
    /// Symbol name to look up
    pub symbol: String,
    /// Workspace path (reserved for multi-workspace support)
    pub path: String,
}

/// Arguments for `get_references` tool.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct GetReferencesArgs {
    /// Symbol name to find references for
    pub symbol: String,
    /// Workspace path (reserved for multi-workspace support)
    pub path: String,
    /// Whether to include the declaration
    pub include_declaration: bool,
    /// Maximum results
    pub max_results: usize,
    /// Pagination (reserved for paginated results)
    pub pagination: PaginationArgs,
}

/// Arguments for `get_hover_info` tool.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct GetHoverInfoArgs {
    /// Symbol name to get info for
    pub symbol: String,
    /// Workspace path (reserved for multi-workspace support)
    pub path: String,
}

/// Arguments for `get_document_symbols` tool.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct GetDocumentSymbolsArgs {
    /// File path to get symbols from
    pub file_path: String,
    /// Workspace path (reserved for multi-workspace support)
    pub path: String,
}

/// Arguments for `get_workspace_symbols` tool.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct GetWorkspaceSymbolsArgs {
    /// Query to search for
    pub query: String,
    /// Workspace path (reserved for multi-workspace support)
    pub path: String,
    /// Maximum results
    pub max_results: usize,
    /// Pagination (reserved for paginated results)
    pub pagination: PaginationArgs,
}

// ============================================================================
// Insights Tool Arguments
// ============================================================================

/// Arguments for `get_insights` tool.
#[derive(Debug, Clone)]
pub struct GetInsightsArgs {
    /// Workspace path
    pub path: String,
}

/// Arguments for `complexity_metrics` tool.
#[derive(Debug, Clone)]
pub struct ComplexityMetricsArgs {
    /// Workspace path
    pub path: String,
    /// Optional target file or symbol to filter
    pub target: Option<String>,
    /// Minimum complexity to report
    pub min_complexity: u32,
    /// Sort by complexity descending
    pub sort_by_complexity: bool,
    /// Maximum results
    pub max_results: usize,
}

/// Arguments for `expand_cache_status` tool.
#[derive(Debug, Clone)]
pub struct ExpandCacheStatusArgs {
    /// Workspace path
    pub path: String,
}

/// Arguments for `rebuild_index` tool.
#[derive(Debug, Clone)]
pub struct RebuildIndexArgs {
    /// Workspace path
    pub path: String,
    /// Force rebuild even if index exists
    pub force: bool,
}

/// Direction for call hierarchy traversal.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CallHierarchyDirection {
    /// Find callers (incoming calls)
    Incoming,
    /// Find callees (outgoing calls)
    Outgoing,
}

impl CallHierarchyDirection {
    pub fn as_str(self) -> &'static str {
        match self {
            CallHierarchyDirection::Incoming => "incoming",
            CallHierarchyDirection::Outgoing => "outgoing",
        }
    }
}

/// Arguments for `call_hierarchy` tool.
#[derive(Debug, Clone)]
pub struct CallHierarchyArgs {
    /// Symbol name or qualified identifier
    pub symbol: String,
    /// Optional file path to disambiguate
    pub file_path: Option<String>,
    /// Direction of the call hierarchy
    pub direction: CallHierarchyDirection,
    /// Workspace path
    pub path: String,
    /// Maximum depth of the call tree
    pub max_depth: usize,
    /// Maximum results
    pub max_results: usize,
    /// Pagination args
    pub pagination: PaginationArgs,
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_abs_diff_eq;
    use serde_json::json;

    #[test]
    fn semantic_search_defaults_are_applied() {
        let args = json!({ "query": "kind:function" });
        let parsed = validate_semantic_search_args(&args).unwrap();
        assert_eq!(parsed.path, ".");
        assert_eq!(parsed.max_results, 200);
        assert_eq!(parsed.context_lines, 3);
        assert_eq!(parsed.pagination.offset, 0);
        assert_eq!(parsed.pagination.size, 50);
    }

    #[test]
    fn semantic_search_filters_and_pagination() {
        let args = json!({
            "query": "kind:function",
            "filters": {
                "language": ["rust", "typescript"],
                "visibility": "public",
                "symbol_kind": ["method", "function"],
                "score_min": 0.4
            },
            "page_token": "10",
            "page_size": 20
        });
        let parsed = validate_semantic_search_args(&args).unwrap();
        assert_eq!(parsed.filters.languages, vec!["rust", "typescript"]);
        assert_eq!(parsed.filters.visibility, Some(Visibility::Public));
        assert_eq!(parsed.filters.kinds, vec!["method", "function"]);
        assert_eq!(parsed.filters.min_score, Some(0.4));
        assert_eq!(parsed.pagination.offset, 10);
        assert_eq!(parsed.pagination.size, 20);
    }

    #[test]
    fn semantic_search_supports_nested_pagination() {
        let args = json!({
            "query": "kind:function",
            "pagination": {
                "cursor": "offset:5",
                "page_size": 15
            }
        });
        let parsed = validate_semantic_search_args(&args).unwrap();
        assert_eq!(parsed.pagination.offset, 5);
        assert_eq!(parsed.pagination.size, 15);
    }

    #[test]
    fn relation_query_defaults() {
        let args = json!({
            "symbol": "helper",
            "relation_type": "callers"
        });
        let parsed = validate_relation_query_args(&args).unwrap();
        assert_eq!(parsed.relation, RelationType::Callers);
        assert_eq!(parsed.max_depth, 1);
        assert_eq!(parsed.max_results, 200);
    }

    #[test]
    fn relation_query_rejects_invalid_relation() {
        let args = json!({
            "symbol": "helper",
            "relation_type": "unknown"
        });
        assert!(validate_relation_query_args(&args).is_err());
    }

    #[test]
    fn explain_code_defaults_flags() {
        let args = json!({
            "file_path": "src/main.rs",
            "symbol_name": "main"
        });
        let parsed = validate_explain_code_args(&args).unwrap();
        assert!(parsed.include_context);
        assert!(parsed.include_relations);
    }

    #[test]
    fn get_dependencies_requires_target() {
        let args = json!({ "path": "." });
        assert!(validate_show_dependencies_args(&args).is_err());
    }

    #[test]
    fn index_status_defaults_to_workspace() {
        let args = json!({});
        let parsed = validate_get_index_status_args(&args);
        assert_eq!(parsed.path, ".");
    }

    #[test]
    fn find_similar_requires_reference() {
        let args = json!({});
        assert!(validate_search_similar_args(&args).is_err());
    }

    #[test]
    fn find_similar_defaults() {
        let args = json!({
            "reference": {
                "file_path": "sqry-mcp/src/server.rs",
                "symbol_name": "SqryServer"
            }
        });
        let parsed = validate_search_similar_args(&args).unwrap();
        assert_eq!(parsed.path, ".");
        assert_abs_diff_eq!(parsed.similarity_threshold, 0.7, epsilon = 1e-10);
        assert_eq!(parsed.max_results, 20);
        assert_eq!(parsed.pagination.size, 20);
    }

    // ===== sqry_ask validation tests (P2-18) =====

    #[test]
    fn sqry_ask_valid_query_and_path() {
        let args = json!({
            "query": "find all public functions",
            "path": "src/"
        });
        let parsed = validate_sqry_ask_args(&args).unwrap();
        assert_eq!(parsed.query, "find all public functions");
        assert_eq!(parsed.path, "src/");
    }

    #[test]
    fn sqry_ask_defaults_path_to_dot() {
        let args = json!({
            "query": "find functions"
        });
        let parsed = validate_sqry_ask_args(&args).unwrap();
        assert_eq!(parsed.query, "find functions");
        assert_eq!(parsed.path, ".");
    }

    #[test]
    fn sqry_ask_null_path_defaults_to_dot() {
        let args = json!({
            "query": "find functions",
            "path": null
        });
        let parsed = validate_sqry_ask_args(&args).unwrap();
        assert_eq!(parsed.path, ".");
    }

    #[test]
    fn sqry_ask_rejects_numeric_path() {
        let args = json!({
            "query": "find functions",
            "path": 123
        });
        let result = validate_sqry_ask_args(&args);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("path must be a string"), "Error was: {err}");
    }

    #[test]
    fn sqry_ask_rejects_object_path() {
        let args = json!({
            "query": "find functions",
            "path": { "dir": "src" }
        });
        let result = validate_sqry_ask_args(&args);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("path must be a string"), "Error was: {err}");
    }

    #[test]
    fn sqry_ask_requires_query() {
        let args = json!({
            "path": "."
        });
        let result = validate_sqry_ask_args(&args);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("query"), "Error was: {err}");
    }

    #[test]
    fn sqry_ask_rejects_empty_query() {
        let args = json!({
            "query": "   ",
            "path": "."
        });
        let result = validate_sqry_ask_args(&args);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("empty"), "Error was: {err}");
    }

    #[test]
    fn sqry_ask_rejects_oversized_query() {
        let long_query = "a".repeat(5000);
        let args = json!({
            "query": long_query,
            "path": "."
        });
        let result = validate_sqry_ask_args(&args);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("maximum length") || err.contains("4096"),
            "Error was: {err}"
        );
    }

    #[test]
    fn sqry_ask_execute_true() {
        let args = json!({
            "query": "find functions",
            "execute": true
        });
        let parsed = validate_sqry_ask_args(&args).unwrap();
        assert!(parsed.execute);
    }

    #[test]
    fn sqry_ask_execute_null_defaults_false() {
        let args = json!({
            "query": "find functions",
            "execute": null
        });
        let parsed = validate_sqry_ask_args(&args).unwrap();
        assert!(!parsed.execute);
    }

    #[test]
    fn sqry_ask_execute_missing_defaults_false() {
        let args = json!({
            "query": "find functions"
        });
        let parsed = validate_sqry_ask_args(&args).unwrap();
        assert!(!parsed.execute);
    }

    #[test]
    fn sqry_ask_rejects_non_bool_execute() {
        let args = json!({
            "query": "find functions",
            "execute": "yes"
        });
        let result = validate_sqry_ask_args(&args);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("execute must be a boolean"),
        );
    }

    // ========================================================================
    // Filter error message tests (U08)
    // ========================================================================

    #[test]
    fn string_filter_produces_helpful_error() {
        let args = json!({
            "query": "kind:function",
            "filters": "lang:rust"
        });
        let result = validate_semantic_search_args(&args);
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("JSON object"),
            "Error should mention 'JSON object', got: {msg}"
        );
        assert!(
            msg.contains("query"),
            "Error should reference the `query` parameter, got: {msg}"
        );
    }

    #[test]
    fn object_filter_with_query_predicate_works_together() {
        let args = json!({
            "query": "kind:function vis:public",
            "filters": {
                "language": ["rust"]
            }
        });
        let parsed = validate_semantic_search_args(&args).unwrap();
        assert_eq!(parsed.query, "kind:function vis:public");
        assert_eq!(parsed.filters.languages, vec!["rust"]);
    }

    #[test]
    fn hierarchical_string_filter_produces_helpful_error() {
        let args = json!({
            "query": "kind:class",
            "filters": "lang:typescript"
        });
        let result = validate_hierarchical_search_args(&args);
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("JSON object"),
            "Error should mention 'JSON object', got: {msg}"
        );
    }
}