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
//! Data types for MCP tool execution responses.
//!
//! This module contains the response data structures used by the MCP tool handlers.

use serde::Serialize;
use serde_json::Value;

use super::graph_cache;

// ============================================================================
// Classpath Provenance Types
// ============================================================================

/// Provenance information for symbols originating from external classpath JARs.
///
/// Only present in tool results when the symbol comes from a classpath dependency
/// (e.g., a Maven/Gradle library). Workspace symbols do not carry provenance.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ProvenanceData {
    /// Source type — always `"classpath"` for JAR-sourced symbols.
    pub source: &'static str,
    /// Maven coordinates (e.g., `"com.google.guava:guava:33.0.0"`).
    /// `None` when the JAR has no embedded POM metadata.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub coordinates: Option<String>,
    /// Whether this is a direct (vs. transitive) dependency.
    pub is_direct: bool,
    /// JAR file path this symbol was extracted from.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub jar_path: Option<String>,
}

/// Result wrapper for tool executions
pub struct ToolExecution<T>
where
    T: Serialize,
{
    pub data: T,
    pub used_index: bool,
    pub used_graph: bool,
    pub graph_metadata: Option<GraphMetadata>,
    pub execution_ms: u64,
    pub next_page_token: Option<String>,
    pub total: Option<u64>,
    pub truncated: Option<bool>,
    pub candidates_scanned: Option<u64>,
    pub workspace_path: String,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GraphMetadata {
    pub total_nodes: u64,
    pub total_edges: u64,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub languages: Vec<String>,
    pub cross_language_edges: u64,
    pub graph_version: String,
    pub rebuild_epoch_ms: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache: Option<GraphCacheMetadata>,
    /// Per-language confidence metadata from the graph manifest.
    /// Maps language name (e.g., "rust") to confidence level and limitations.
    #[serde(default, skip_serializing_if = "std::collections::HashMap::is_empty")]
    pub confidence: std::collections::HashMap<String, sqry_core::confidence::ConfidenceMetadata>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GraphCacheMetadata {
    pub strategy: GraphCacheStrategyMetadata,
    pub trace_path: CacheMetricsSummary,
    pub subgraph: CacheMetricsSummary,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub current_request: Option<CacheRequestEvent>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GraphCacheStrategyMetadata {
    pub policy: &'static str,
    pub ttl_seconds: u64,
    pub trace_path_capacity: usize,
    pub subgraph_capacity: usize,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CacheMetricsSummary {
    pub hits: u64,
    pub misses: u64,
    pub evictions: u64,
    pub expired: u64,
    pub hit_rate: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub warm_latency: Option<graph_cache::LatencyStatsSnapshot>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cold_latency: Option<graph_cache::LatencyStatsSnapshot>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_event: Option<graph_cache::CacheEvent>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CacheRequestEvent {
    pub tool: &'static str,
    pub state: graph_cache::CacheState,
    pub latency_ms: u64,
    pub timestamp_ms: u64,
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct CacheRequestContext {
    pub tool: &'static str,
    pub state: graph_cache::CacheState,
    pub latency_ms: u64,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RangeData {
    pub start: PositionData,
    pub end: PositionData,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PositionData {
    pub line: u32,
    pub character: u32,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CodeContext {
    pub code: String,
    pub lines_before: usize,
    pub lines_after: usize,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NodeRefData {
    pub name: String,
    #[serde(rename = "qualifiedName")]
    pub qualified_name: String,
    pub kind: String,
    pub language: String,
    #[serde(rename = "fileUri")]
    pub file_uri: String,
    pub range: RangeData,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SearchHit {
    pub name: String,
    #[serde(rename = "qualifiedName")]
    pub qualified_name: String,
    pub kind: String,
    pub language: String,
    #[serde(rename = "fileUri")]
    pub file_uri: String,
    pub range: RangeData,
    pub score: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context: Option<CodeContext>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub relations: Option<SearchHitRelations>,
    /// Macro boundary metadata (only present when the node has macro-related info)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub macro_metadata: Option<MacroMetadataResponse>,
    /// Classpath provenance (only present for symbols from external JARs)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provenance: Option<ProvenanceData>,
}

#[derive(Debug, Clone, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct SearchHitRelations {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub callers: Vec<NodeRefData>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub callees: Vec<NodeRefData>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SemanticSearchData {
    pub results: Vec<SearchHit>,
    pub total: u64,
    pub truncated: bool,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IndexStatusData {
    pub has_index: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub root_path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub indexed_symbols: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub files_indexed: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub index_version: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub has_relations: Option<bool>,
}

/// Response data for `rebuild_index` tool.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RebuildIndexData {
    /// Whether the rebuild was successful
    pub success: bool,
    /// Root path of the index
    pub root_path: String,
    /// Number of nodes (symbols) in the rebuilt index
    pub node_count: u64,
    /// Number of edges (relations) in the rebuilt index
    pub edge_count: u64,
    /// Number of files indexed
    pub files_indexed: u64,
    /// Timestamp when the index was built (RFC3339)
    pub built_at: String,
    /// Message describing the rebuild result
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RelationEdgeData {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from: Option<NodeRefData>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to: Option<NodeRefData>,
    #[serde(rename = "type")]
    pub relation_type: String,
    pub depth: u32,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RelationQueryData {
    pub relation_type: String,
    pub relations: Vec<RelationEdgeData>,
    pub total: u64,
}

/// A node in the call hierarchy tree.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CallHierarchyNode {
    /// The symbol at this node
    pub symbol: NodeRefData,
    /// Child nodes (callers or callees depending on direction)
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub children: Vec<CallHierarchyNode>,
    /// Call site ranges (where the call occurs)
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub call_ranges: Vec<RangeData>,
}

/// Response data for call hierarchy tool.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CallHierarchyData {
    /// The root symbol being analyzed
    pub root: NodeRefData,
    /// Direction of the hierarchy
    pub direction: String,
    /// The hierarchy nodes (callers or callees)
    pub items: Vec<CallHierarchyNode>,
    /// Total number of items found
    pub total: u64,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExplainRelations {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub callers: Option<Vec<NodeRefData>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub callees: Option<Vec<NodeRefData>>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExplainCodeData {
    pub symbol: NodeRefData,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub documentation: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context: Option<CodeContext>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub relations: Option<ExplainRelations>,
    /// Classpath provenance (only present for symbols from external JARs)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provenance: Option<ProvenanceData>,
}

#[derive(Debug, Clone, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct DependencyGraphData {
    pub nodes: Vec<NodeRefData>,
    pub edges: Vec<RelationEdgeData>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rendered: Option<String>,
}

impl DependencyGraphData {
    /// Create an empty graph (used as fallback when computation fails).
    #[must_use]
    pub fn empty() -> Self {
        Self::default()
    }
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PathStep {
    pub symbol: NodeRefData,
    pub edge_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confidence: Option<f64>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CallPath {
    pub steps: Vec<PathStep>,
    pub length: u32,
    pub score: f64,
    pub cross_language: bool,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TracePathData {
    pub paths: Vec<CallPath>,
    pub from_symbol: String,
    pub to_symbol: String,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CrossLanguageEdgesData {
    pub edges: Vec<RelationEdgeData>,
    pub total: u64,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SimilarSymbolData {
    pub symbol: NodeRefData,
    pub similarity: f64,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FindSimilarData {
    pub reference: NodeRefData,
    pub results: Vec<SimilarSymbolData>,
    pub total: u64,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ImpactedSymbol {
    pub symbol: NodeRefData,
    pub depth: u32,
    pub impact_type: String,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DependencyImpactData {
    pub target_symbol: String,
    pub impacted_symbols: Vec<ImpactedSymbol>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub affected_files: Option<Vec<String>>,
    pub total: u64,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NodeChange {
    pub symbol_name: String,
    pub qualified_name: String,
    pub kind: String,
    pub change_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub base_location: Option<NodeRefData>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_location: Option<NodeRefData>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature_before: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature_after: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SemanticDiffData {
    pub base_ref: String,
    pub target_ref: String,
    pub changes: Vec<NodeChange>,
    pub summary: DiffSummary,
    pub total: u64,
}

#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DiffSummary {
    pub added: u64,
    pub removed: u64,
    pub modified: u64,
    pub renamed: u64,
    pub signature_changed: u64,
    pub unchanged: u64,
}

/// Disambiguation option for natural language translation (P2-18)
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NlDisambiguationOption {
    /// The command for this option
    pub command: String,
    /// The detected intent
    pub intent: String,
    /// Human-readable description
    pub description: String,
    /// Confidence score for this option
    pub confidence: f32,
}

/// Response data for natural language translation (P2-18)
///
/// The MCP server performs translation only - command execution is
/// the responsibility of the MCP client.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NlTranslationData {
    /// The type of response: execute, confirm, disambiguate, reject
    pub response_type: String,
    /// The translated command (if available)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,
    /// Translation confidence score (0.0-1.0)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confidence: Option<f32>,
    /// Detected intent type
    #[serde(skip_serializing_if = "Option::is_none")]
    pub intent: Option<String>,
    /// User-facing prompt (for confirm/disambiguate)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompt: Option<String>,
    /// Rejection reason (for reject)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    /// Suggestions for improvement
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub suggestions: Vec<String>,
    /// Disambiguation options (for disambiguate)
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub options: Vec<NlDisambiguationOption>,
    /// Captured stdout from command execution (if execute=true)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_output: Option<String>,
}

// ============================================================================
// Duplicate Detection Types
// ============================================================================

/// Symbol info in a duplicate group
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DuplicateSymbolData {
    /// Symbol name
    pub name: String,
    /// Fully qualified name
    pub qualified_name: String,
    /// Symbol kind (function, method, struct, etc.)
    pub kind: String,
    /// File URI
    pub file_uri: String,
    /// Start line (1-indexed)
    pub line: u32,
    /// Language
    pub language: String,
}

/// A group of duplicate symbols
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DuplicateGroupData {
    /// Group identifier as hex string.
    ///
    /// For body duplicates with 128-bit `body_hash`, this is a 32-character
    /// lowercase hexadecimal string (e.g., "000000000000000012345678abcdef01").
    /// For signature/struct duplicates, this is a 16-character hex string.
    pub group_id: String,
    /// Number of duplicates in this group
    pub count: usize,
    /// Symbols in this group
    pub symbols: Vec<DuplicateSymbolData>,
}

/// Response data for `find_duplicates` tool
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FindDuplicatesData {
    /// Type of duplicates found
    pub duplicate_type: String,
    /// Threshold used
    pub threshold: u32,
    /// Groups of duplicate symbols
    pub groups: Vec<DuplicateGroupData>,
    /// Total number of groups found
    pub total: u64,
}

// ============================================================================
// Cycle Detection Types
// ============================================================================

/// A single symbol in a cycle
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CycleNodeData {
    /// Symbol name
    pub name: String,
    /// Fully qualified name
    pub qualified_name: String,
    /// File URI
    pub file_uri: String,
    /// Start line (1-indexed)
    pub line: u32,
}

/// A detected cycle
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CycleData {
    /// Cycle depth (number of nodes)
    pub depth: usize,
    /// Nodes in the cycle (A → B → C → A becomes [A, B, C])
    pub nodes: Vec<CycleNodeData>,
    /// Human-readable cycle chain (e.g., "A → B → C → A")
    pub chain: String,
}

/// Response data for `find_cycles` tool
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FindCyclesData {
    /// Type of cycles found
    pub cycle_type: String,
    /// Detected cycles
    pub cycles: Vec<CycleData>,
    /// Total number of cycles found
    pub total: u64,
}

// ============================================================================
// Unused Code Detection Types
// ============================================================================

/// An unused symbol
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UnusedSymbolData {
    /// Symbol name
    pub name: String,
    /// Fully qualified name
    pub qualified_name: String,
    /// Symbol kind (function, method, struct, etc.)
    pub kind: String,
    /// File URI
    pub file_uri: String,
    /// Start line (1-indexed)
    pub line: u32,
    /// Language
    pub language: String,
    /// Visibility (public, private, etc.)
    pub visibility: String,
}

/// Response data for `find_unused` tool
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FindUnusedData {
    /// Scope used for analysis
    pub scope: String,
    /// Unused symbols
    pub symbols: Vec<UnusedSymbolData>,
    /// Total number of unused symbols found
    pub total: u64,
}

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

/// Response data for `is_node_in_cycle` tool
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NodeInCycleData {
    /// Symbol that was checked
    pub symbol: String,
    /// Whether the symbol is in a cycle
    pub in_cycle: bool,
    /// Type of cycle checked (calls, imports, modules)
    pub cycle_type: String,
    /// If in a cycle, the cycle containing this symbol
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cycle: Option<Vec<String>>,
}

/// Response data for `pattern_search` tool
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PatternSearchData {
    /// Search pattern used
    pub pattern: String,
    /// Matching symbols
    pub matches: Vec<PatternMatchData>,
    /// Total matches found
    pub total: u64,
}

/// A single pattern match result
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PatternMatchData {
    /// Symbol name
    pub name: String,
    /// Fully qualified name
    pub qualified_name: String,
    /// Symbol kind
    pub kind: String,
    /// File URI
    pub file_uri: String,
    /// Line number
    pub line: u32,
    /// Language
    pub language: String,
    /// Classpath provenance (only present for symbols from external JARs)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provenance: Option<ProvenanceData>,
}

/// Response data for `direct_callers` tool
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DirectCallersData {
    /// Target symbol that was queried
    pub target: String,
    /// Symbols that call the target
    pub callers: Vec<CallerCalleeData>,
    /// Total number of callers
    pub total: u64,
}

/// Response data for `direct_callees` tool
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DirectCalleesData {
    /// Source symbol that was queried
    pub source: String,
    /// Symbols called by the source
    pub callees: Vec<CallerCalleeData>,
    /// Total number of callees
    pub total: u64,
}

/// A caller or callee symbol
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CallerCalleeData {
    /// Symbol name
    pub name: String,
    /// Fully qualified name
    pub qualified_name: String,
    /// Symbol kind
    pub kind: String,
    /// File URI
    pub file_uri: String,
    /// Line number
    pub line: u32,
    /// Language
    pub language: String,
}

// ============================================================================
// Introspection Tool Response Types
// ============================================================================

/// A file entry for `list_files` tool
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FileEntryData {
    /// File path relative to workspace
    pub path: String,
    /// Language of the file
    #[serde(skip_serializing_if = "Option::is_none")]
    pub language: Option<String>,
}

/// Response data for `list_files` tool
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ListFilesData {
    /// Files in the workspace
    pub files: Vec<FileEntryData>,
    /// Total number of files
    pub total: u64,
}

/// A symbol entry for `list_symbols` tool
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SymbolEntryData {
    /// Symbol name
    pub name: String,
    /// Fully qualified name
    pub qualified_name: String,
    /// Symbol kind
    pub kind: String,
    /// File path relative to workspace
    pub file_path: String,
    /// Start line (1-indexed)
    pub line: u32,
    /// Language
    pub language: String,
}

/// Response data for `list_symbols` tool
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ListSymbolsData {
    /// Symbols in the workspace
    pub symbols: Vec<SymbolEntryData>,
    /// Total number of symbols
    pub total: u64,
}

/// Response data for `get_graph_stats` tool
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GraphStatsData {
    /// Total number of nodes
    pub total_nodes: u64,
    /// Total number of edges
    pub total_edges: u64,
    /// Total number of files
    pub total_files: u64,
    /// Number of workspace (non-external) nodes
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workspace_nodes: Option<u64>,
    /// Number of classpath (external) nodes
    #[serde(skip_serializing_if = "Option::is_none")]
    pub classpath_nodes: Option<u64>,
    /// Number of workspace (non-external) files
    #[serde(skip_serializing_if = "Option::is_none")]
    pub workspace_files: Option<u64>,
    /// Number of classpath (external) files
    #[serde(skip_serializing_if = "Option::is_none")]
    pub classpath_files: Option<u64>,
    /// Symbol counts by kind
    pub nodes_by_kind: std::collections::HashMap<String, u64>,
    /// File counts by language
    pub files_by_language: std::collections::HashMap<String, u64>,
    /// Graph version/epoch
    pub graph_epoch: u64,
}

// ============================================================================
// Navigation Tool Response Types
// ============================================================================

/// Response data for `get_definition` tool
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DefinitionData {
    /// Symbol name
    pub name: String,
    /// Fully qualified name
    pub qualified_name: String,
    /// Symbol kind
    pub kind: String,
    /// File path
    pub file_path: String,
    /// Line number (1-indexed)
    pub line: u32,
    /// Column number (1-indexed)
    pub column: u32,
    /// Language
    pub language: String,
    /// Preview of the definition
    #[serde(skip_serializing_if = "Option::is_none")]
    pub preview: Option<String>,
    /// Macro boundary metadata (only present when the node has macro-related info)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub macro_metadata: Option<MacroMetadataResponse>,
    /// Classpath provenance (only present for symbols from external JARs)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provenance: Option<ProvenanceData>,
}

/// Response data for `get_definition` tool (may have multiple results)
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetDefinitionData {
    /// Found definitions
    pub definitions: Vec<DefinitionData>,
    /// Total count
    pub total: u64,
}

/// Reference location data
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ReferenceLocationData {
    /// File path
    pub file_path: String,
    /// Line number (1-indexed)
    pub line: u32,
    /// Column number (1-indexed)
    pub column: u32,
    /// Preview of the reference context
    #[serde(skip_serializing_if = "Option::is_none")]
    pub preview: Option<String>,
    /// Is this the declaration?
    pub is_declaration: bool,
    /// Classpath provenance (only present for references in external JARs)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provenance: Option<ProvenanceData>,
}

/// Response data for `get_references` tool
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetReferencesData {
    /// Symbol that was searched
    pub symbol: String,
    /// References found
    pub references: Vec<ReferenceLocationData>,
    /// Total count
    pub total: u64,
    /// Macro boundary metadata for the searched symbol (only present when available)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub macro_metadata: Option<MacroMetadataResponse>,
}

/// Response data for `get_hover_info` tool
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HoverInfoData {
    /// Symbol name
    pub name: String,
    /// Fully qualified name
    pub qualified_name: String,
    /// Symbol kind
    pub kind: String,
    /// File path
    pub file_path: String,
    /// Line number
    pub line: u32,
    /// Language
    pub language: String,
    /// Type signature
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
    /// Documentation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub documentation: Option<String>,
    /// Classpath provenance (only present for symbols from external JARs)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub provenance: Option<ProvenanceData>,
}

/// Document symbol with children
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DocumentSymbolData {
    /// Symbol name
    pub name: String,
    /// Symbol kind
    pub kind: String,
    /// Start line (1-indexed)
    pub line: u32,
    /// End line (1-indexed)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_line: Option<u32>,
    /// Child symbols
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub children: Vec<DocumentSymbolData>,
    /// Macro boundary metadata (only present when the node has macro-related info)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub macro_metadata: Option<MacroMetadataResponse>,
}

/// Response data for `get_document_symbols` tool
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetDocumentSymbolsData {
    /// File path
    pub file_path: String,
    /// Symbols in the document
    pub symbols: Vec<DocumentSymbolData>,
    /// Total count
    pub total: u64,
}

/// Workspace symbol search result
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkspaceSymbolData {
    /// Symbol name
    pub name: String,
    /// Fully qualified name
    pub qualified_name: String,
    /// Symbol kind
    pub kind: String,
    /// File path
    pub file_path: String,
    /// Line number
    pub line: u32,
    /// Language
    pub language: String,
    /// Match score (0.0 - 1.0)
    pub score: f64,
}

/// Response data for `get_workspace_symbols` tool
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetWorkspaceSymbolsData {
    /// Query that was searched
    pub query: String,
    /// Matching symbols
    pub symbols: Vec<WorkspaceSymbolData>,
    /// Total count
    pub total: u64,
}

// ============================================================================
// Insights Tool Data Types
// ============================================================================

/// Language statistics for insights
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LanguageStatsData {
    /// Language name
    pub language: String,
    /// Number of files
    pub files: usize,
    /// Number of symbols
    pub symbols: usize,
}

/// Symbol kind statistics for insights
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct KindStatsData {
    /// Kind name
    pub kind: String,
    /// Count
    pub count: usize,
}

/// Health indicators for insights
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HealthIndicatorsData {
    /// Number of cycles detected
    pub cycles: usize,
    /// Number of unused symbols
    pub unused_symbols: usize,
    /// Number of duplicate groups
    pub duplicate_groups: usize,
    /// Number of cross-language edges
    pub cross_language_edges: usize,
}

/// Response data for `get_insights` tool
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetInsightsData {
    /// Total number of files
    pub total_files: usize,
    /// Total number of symbols
    pub total_symbols: usize,
    /// Total number of edges
    pub total_edges: usize,
    /// Statistics by language
    pub languages: Vec<LanguageStatsData>,
    /// Statistics by symbol kind
    pub symbol_kinds: Vec<KindStatsData>,
    /// Health indicators
    pub health: HealthIndicatorsData,
    /// Macro boundary statistics (only present when metadata store is non-empty)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub macro_boundaries: Option<MacroBoundariesStatsData>,
}

/// Complexity metric for a single function/method
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ComplexityMetricData {
    /// Symbol name
    pub name: String,
    /// Fully qualified name
    pub qualified_name: String,
    /// Symbol kind
    pub kind: String,
    /// File path
    pub file_path: String,
    /// Estimated complexity
    pub complexity: u32,
    /// Line count
    pub lines: u32,
}

/// Response data for `complexity_metrics` tool
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ComplexityMetricsData {
    /// Complexity metrics for each function/method
    pub metrics: Vec<ComplexityMetricData>,
    /// Total count
    pub total: usize,
    /// Average complexity
    pub average_complexity: f64,
    /// Maximum complexity
    pub max_complexity: u32,
}

// ============================================================================
// Macro Boundary Response Types
// ============================================================================

/// Macro boundary metadata attached to search/navigation responses.
///
/// Only included when a node has macro-relevant metadata. Uses
/// `skip_serializing_if` so absent fields don't appear in JSON.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MacroMetadataResponse {
    /// Whether this symbol was generated by macro expansion
    #[serde(skip_serializing_if = "Option::is_none")]
    pub macro_generated: Option<bool>,
    /// Qualified name of the macro that generated this symbol
    #[serde(skip_serializing_if = "Option::is_none")]
    pub macro_source: Option<String>,
    /// The cfg predicate string (e.g., `"test"`, `"feature = \"serde\""`)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cfg_condition: Option<String>,
    /// Whether this cfg is active (`None` = unknown)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cfg_active: Option<bool>,
    /// Proc-macro kind for proc-macro function nodes
    #[serde(skip_serializing_if = "Option::is_none")]
    pub proc_macro_kind: Option<String>,
    /// Whether expansion data came from cache vs live `cargo expand`
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expansion_cached: Option<bool>,
    /// Unresolved attribute paths
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub unresolved_attributes: Vec<String>,
}

/// Macro boundaries statistics for `get_insights` responses.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MacroBoundariesStatsData {
    /// Number of attribute macros detected on items
    pub attribute_macros_detected: usize,
    /// Number of symbols gated by `cfg/cfg_attr`
    pub cfg_gated_symbols: usize,
    /// Number of symbols generated by macro expansion
    pub macro_generated_symbols: usize,
    /// Number of unresolved attribute paths across all nodes
    pub unresolved_attributes: usize,
    /// Expand cache status: "fresh", "stale", or "absent"
    pub expand_cache_status: String,
}

/// Response data for `expand_cache_status` tool.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExpandCacheStatusData {
    /// Whether the expand cache directory exists
    pub cache_exists: bool,
    /// Path to the expand cache directory
    pub cache_path: String,
    /// Number of cache files found
    pub cache_files: usize,
    /// Total size of cache files in bytes
    pub total_size_bytes: u64,
    /// Per-crate cache info (crate name to status)
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub crates: Vec<CrateCacheEntry>,
    /// Overall freshness: "fresh", "stale", or "absent"
    pub status: String,
}

/// Per-crate expand cache entry.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CrateCacheEntry {
    /// Crate name
    pub crate_name: String,
    /// Cache file path (relative)
    pub file_name: String,
    /// File size in bytes
    pub size_bytes: u64,
    /// Number of generated symbols in this cache entry
    pub generated_symbols: usize,
    /// Confidence level
    pub confidence: String,
}

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

    // ========== PositionData tests ==========

    #[test]
    fn test_position_data_creation() {
        let pos = PositionData {
            line: 10,
            character: 5,
        };
        assert_eq!(pos.line, 10);
        assert_eq!(pos.character, 5);
    }

    #[test]
    fn test_position_data_serialization() {
        let pos = PositionData {
            line: 42,
            character: 15,
        };
        let json = serde_json::to_string(&pos).unwrap();
        assert!(json.contains("\"line\":42"));
        assert!(json.contains("\"character\":15"));
    }

    // ========== RangeData tests ==========

    #[test]
    fn test_range_data_creation() {
        let range = RangeData {
            start: PositionData {
                line: 1,
                character: 0,
            },
            end: PositionData {
                line: 10,
                character: 20,
            },
        };
        assert_eq!(range.start.line, 1);
        assert_eq!(range.end.line, 10);
    }

    #[test]
    fn test_range_data_serialization() {
        let range = RangeData {
            start: PositionData {
                line: 5,
                character: 10,
            },
            end: PositionData {
                line: 5,
                character: 25,
            },
        };
        let json = serde_json::to_string(&range).unwrap();
        assert!(json.contains("\"start\""));
        assert!(json.contains("\"end\""));
    }

    // ========== CodeContext tests ==========

    #[test]
    fn test_code_context_creation() {
        let ctx = CodeContext {
            code: "fn main() {}".to_string(),
            lines_before: 3,
            lines_after: 3,
        };
        assert_eq!(ctx.code, "fn main() {}");
        assert_eq!(ctx.lines_before, 3);
        assert_eq!(ctx.lines_after, 3);
    }

    #[test]
    fn test_code_context_serialization() {
        let ctx = CodeContext {
            code: "let x = 1;".to_string(),
            lines_before: 2,
            lines_after: 2,
        };
        let json = serde_json::to_string(&ctx).unwrap();
        assert!(json.contains("\"code\""));
        assert!(json.contains("\"linesBefore\""));
        assert!(json.contains("\"linesAfter\""));
    }

    // ========== DependencyGraphData tests ==========

    #[test]
    fn test_dependency_graph_data_empty() {
        let graph = DependencyGraphData::empty();
        assert!(graph.nodes.is_empty());
        assert!(graph.edges.is_empty());
        assert!(graph.rendered.is_none());
    }

    #[test]
    fn test_dependency_graph_data_default() {
        let graph = DependencyGraphData::default();
        assert!(graph.nodes.is_empty());
        assert!(graph.edges.is_empty());
        assert!(graph.rendered.is_none());
    }

    #[test]
    fn test_dependency_graph_data_serialization_empty() {
        let graph = DependencyGraphData::empty();
        let json = serde_json::to_string(&graph).unwrap();
        assert!(json.contains("\"nodes\":[]"));
        assert!(json.contains("\"edges\":[]"));
        // rendered should be skipped when None
        assert!(!json.contains("\"rendered\""));
    }

    // ========== SearchHitRelations tests ==========

    #[test]
    fn test_search_hit_relations_default() {
        let relations = SearchHitRelations::default();
        assert!(relations.callers.is_empty());
        assert!(relations.callees.is_empty());
    }

    #[test]
    fn test_search_hit_relations_serialization_empty() {
        let relations = SearchHitRelations::default();
        let json = serde_json::to_string(&relations).unwrap();
        // Empty vectors should be skipped
        assert_eq!(json, "{}");
    }

    // ========== DiffSummary tests ==========

    #[test]
    fn test_diff_summary_creation() {
        let summary = DiffSummary {
            added: 10,
            removed: 5,
            modified: 3,
            renamed: 1,
            signature_changed: 2,
            unchanged: 100,
        };
        assert_eq!(summary.added, 10);
        assert_eq!(summary.removed, 5);
        assert_eq!(summary.modified, 3);
        assert_eq!(summary.renamed, 1);
        assert_eq!(summary.signature_changed, 2);
        assert_eq!(summary.unchanged, 100);
    }

    #[test]
    fn test_diff_summary_serialization() {
        let summary = DiffSummary {
            added: 1,
            removed: 2,
            modified: 3,
            renamed: 0,
            signature_changed: 1,
            unchanged: 50,
        };
        let json = serde_json::to_string(&summary).unwrap();
        assert!(json.contains("\"added\":1"));
        assert!(json.contains("\"removed\":2"));
        assert!(json.contains("\"signatureChanged\":1"));
    }

    // ========== NlDisambiguationOption tests ==========

    #[test]
    #[allow(clippy::float_cmp)] // Approximate threshold comparison
    fn test_nl_disambiguation_option_creation() {
        let option = NlDisambiguationOption {
            command: "query kind:function".to_string(),
            intent: "search".to_string(),
            description: "Search for functions".to_string(),
            confidence: 0.85,
        };
        assert_eq!(option.command, "query kind:function");
        assert_eq!(option.intent, "search");
        assert_eq!(option.confidence, 0.85);
    }

    #[test]
    fn test_nl_disambiguation_option_serialization() {
        let option = NlDisambiguationOption {
            command: "test".to_string(),
            intent: "execute".to_string(),
            description: "Run tests".to_string(),
            confidence: 0.9,
        };
        let json = serde_json::to_string(&option).unwrap();
        assert!(json.contains("\"command\":\"test\""));
        assert!(json.contains("\"confidence\":0.9"));
    }

    // ========== NlTranslationData tests ==========

    #[test]
    fn test_nl_translation_data_execute() {
        let data = NlTranslationData {
            response_type: "execute".to_string(),
            command: Some("query kind:function".to_string()),
            confidence: Some(0.95),
            intent: Some("search".to_string()),
            prompt: None,
            reason: None,
            suggestions: vec![],
            options: vec![],
            execution_output: None,
        };
        assert_eq!(data.response_type, "execute");
        assert!(data.command.is_some());
    }

    #[test]
    fn test_nl_translation_data_reject() {
        let data = NlTranslationData {
            response_type: "reject".to_string(),
            command: None,
            confidence: None,
            intent: None,
            prompt: None,
            reason: Some("Query too vague".to_string()),
            suggestions: vec!["Be more specific".to_string()],
            options: vec![],
            execution_output: None,
        };
        assert_eq!(data.response_type, "reject");
        assert_eq!(data.reason, Some("Query too vague".to_string()));
    }

    #[test]
    fn test_nl_translation_data_serialization_skips_none() {
        let data = NlTranslationData {
            response_type: "execute".to_string(),
            command: Some("test".to_string()),
            confidence: None,
            intent: None,
            prompt: None,
            reason: None,
            suggestions: vec![],
            options: vec![],
            execution_output: None,
        };
        let json = serde_json::to_string(&data).unwrap();
        // Optional fields should be skipped when None
        assert!(!json.contains("\"confidence\""));
        assert!(!json.contains("\"suggestions\""));
    }

    // ========== CallPath tests ==========

    #[test]
    #[allow(clippy::float_cmp)] // Approximate threshold comparison
    fn test_call_path_creation() {
        let path = CallPath {
            steps: vec![],
            length: 3,
            score: 0.85,
            cross_language: false,
        };
        assert_eq!(path.length, 3);
        assert_eq!(path.score, 0.85);
        assert!(!path.cross_language);
    }

    #[test]
    fn test_call_path_cross_language() {
        let path = CallPath {
            steps: vec![],
            length: 5,
            score: 0.7,
            cross_language: true,
        };
        assert!(path.cross_language);
    }

    // ========== ImpactedSymbol tests ==========

    #[test]
    fn test_impacted_symbol_creation() {
        let symbol = ImpactedSymbol {
            symbol: NodeRefData {
                name: "test_fn".to_string(),
                qualified_name: "module::test_fn".to_string(),
                kind: "function".to_string(),
                language: "rust".to_string(),
                file_uri: "file:///test.rs".to_string(),
                range: RangeData {
                    start: PositionData {
                        line: 1,
                        character: 0,
                    },
                    end: PositionData {
                        line: 5,
                        character: 1,
                    },
                },
                metadata: None,
            },
            depth: 2,
            impact_type: "caller".to_string(),
        };
        assert_eq!(symbol.depth, 2);
        assert_eq!(symbol.impact_type, "caller");
    }

    // ========== GraphMetadata tests ==========

    #[test]
    fn test_graph_metadata_creation() {
        let metadata = GraphMetadata {
            total_nodes: 1000,
            total_edges: 5000,
            languages: vec!["rust".to_string(), "python".to_string()],
            cross_language_edges: 50,
            graph_version: "2.0.0".to_string(),
            #[allow(clippy::unreadable_literal)] // Threshold constant
            rebuild_epoch_ms: 1704067200000,
            cache: None,
            confidence: std::collections::HashMap::new(),
        };
        assert_eq!(metadata.total_nodes, 1000);
        assert_eq!(metadata.total_edges, 5000);
        assert_eq!(metadata.languages.len(), 2);
    }

    #[test]
    fn test_graph_metadata_serialization() {
        let metadata = GraphMetadata {
            total_nodes: 100,
            total_edges: 200,
            languages: vec![],
            cross_language_edges: 0,
            graph_version: "1.0.0".to_string(),
            rebuild_epoch_ms: 0,
            cache: None,
            confidence: std::collections::HashMap::new(),
        };
        let json = serde_json::to_string(&metadata).unwrap();
        assert!(json.contains("\"totalNodes\":100"));
        assert!(json.contains("\"graphVersion\":\"1.0.0\""));
        // Empty languages should be skipped
        assert!(!json.contains("\"languages\""));
        // Empty confidence should be skipped
        assert!(!json.contains("\"confidence\""));
    }

    #[test]
    fn test_graph_metadata_with_confidence() {
        use sqry_core::confidence::{ConfidenceLevel, ConfidenceMetadata};

        let mut confidence = std::collections::HashMap::new();
        confidence.insert(
            "rust".to_string(),
            ConfidenceMetadata {
                level: ConfidenceLevel::AstOnly,
                limitations: vec!["No type inference".to_string()],
                unavailable_features: vec!["rust-analyzer".to_string()],
            },
        );

        let metadata = GraphMetadata {
            total_nodes: 100,
            total_edges: 200,
            languages: vec!["rust".to_string()],
            cross_language_edges: 0,
            graph_version: "2.8.0".to_string(),
            rebuild_epoch_ms: 0,
            cache: None,
            confidence,
        };

        let json = serde_json::to_string(&metadata).unwrap();
        // Confidence should be included when non-empty
        assert!(json.contains("\"confidence\""), "confidence field missing");
        assert!(json.contains("\"rust\""), "rust language key missing");
        assert!(json.contains("\"level\""), "level field missing");
        assert!(
            json.contains("\"ast_only\""),
            "ast_only value missing in: {json}"
        );
        assert!(json.contains("\"No type inference\""), "limitation missing");
    }

    // ========== IndexStatusData tests ==========

    #[test]
    fn test_index_status_data_no_index() {
        let status = IndexStatusData {
            has_index: false,
            root_path: None,
            indexed_symbols: None,
            files_indexed: None,
            index_version: None,
            created_at: None,
            updated_at: None,
            has_relations: None,
        };
        assert!(!status.has_index);
    }

    #[test]
    fn test_index_status_data_with_index() {
        let status = IndexStatusData {
            has_index: true,
            root_path: Some("/project".to_string()),
            indexed_symbols: Some(5000),
            files_indexed: Some(100),
            index_version: Some("2.0.0".to_string()),
            created_at: Some("2024-01-01T00:00:00Z".to_string()),
            updated_at: Some("2024-01-02T00:00:00Z".to_string()),
            has_relations: Some(true),
        };
        assert!(status.has_index);
        assert_eq!(status.indexed_symbols, Some(5000));
    }

    // ===== MacroMetadataResponse tests =====

    #[test]
    fn test_macro_metadata_response_serialization_skips_empty_fields() {
        let response = MacroMetadataResponse {
            macro_generated: Some(true),
            macro_source: None,
            cfg_condition: None,
            cfg_active: None,
            proc_macro_kind: None,
            expansion_cached: None,
            unresolved_attributes: vec![],
        };
        let json = serde_json::to_value(&response).unwrap();
        assert_eq!(json.get("macroGenerated").unwrap(), true);
        assert!(json.get("macroSource").is_none());
        assert!(json.get("cfgCondition").is_none());
        assert!(json.get("unresolvedAttributes").is_none());
    }

    #[test]
    fn test_macro_metadata_response_full_serialization() {
        let response = MacroMetadataResponse {
            macro_generated: Some(true),
            macro_source: Some("derive_Debug".to_string()),
            cfg_condition: Some("test".to_string()),
            cfg_active: Some(true),
            proc_macro_kind: Some("derive".to_string()),
            expansion_cached: Some(false),
            unresolved_attributes: vec!["custom_attr".to_string()],
        };
        let json = serde_json::to_value(&response).unwrap();
        assert_eq!(json.get("macroGenerated").unwrap(), true);
        assert_eq!(json.get("macroSource").unwrap(), "derive_Debug");
        assert_eq!(json.get("cfgCondition").unwrap(), "test");
        assert_eq!(json.get("cfgActive").unwrap(), true);
        assert_eq!(json.get("procMacroKind").unwrap(), "derive");
        assert_eq!(json.get("expansionCached").unwrap(), false);
        let attrs = json
            .get("unresolvedAttributes")
            .unwrap()
            .as_array()
            .unwrap();
        assert_eq!(attrs.len(), 1);
        assert_eq!(attrs[0], "custom_attr");
    }

    #[test]
    fn test_macro_boundaries_stats_data_serialization() {
        let stats = MacroBoundariesStatsData {
            attribute_macros_detected: 5,
            cfg_gated_symbols: 3,
            macro_generated_symbols: 10,
            unresolved_attributes: 2,
            expand_cache_status: "fresh".to_string(),
        };
        let json = serde_json::to_value(&stats).unwrap();
        assert_eq!(json.get("attributeMacrosDetected").unwrap(), 5);
        assert_eq!(json.get("cfgGatedSymbols").unwrap(), 3);
        assert_eq!(json.get("macroGeneratedSymbols").unwrap(), 10);
        assert_eq!(json.get("unresolvedAttributes").unwrap(), 2);
        assert_eq!(json.get("expandCacheStatus").unwrap(), "fresh");
    }

    #[test]
    fn test_expand_cache_status_data_serialization() {
        let data = ExpandCacheStatusData {
            cache_exists: true,
            cache_path: ".sqry/expand-cache".to_string(),
            cache_files: 2,
            total_size_bytes: 4096,
            crates: vec![CrateCacheEntry {
                crate_name: "my_crate".to_string(),
                file_name: "my_crate.json".to_string(),
                size_bytes: 2048,
                generated_symbols: 5,
                confidence: "heuristic".to_string(),
            }],
            status: "fresh".to_string(),
        };
        let json = serde_json::to_value(&data).unwrap();
        assert_eq!(json.get("cacheExists").unwrap(), true);
        assert_eq!(json.get("cacheFiles").unwrap(), 2);
        assert_eq!(json.get("status").unwrap(), "fresh");
        let crates = json.get("crates").unwrap().as_array().unwrap();
        assert_eq!(crates.len(), 1);
        assert_eq!(crates[0].get("crateName").unwrap(), "my_crate");
        assert_eq!(crates[0].get("generatedSymbols").unwrap(), 5);
    }

    #[test]
    fn test_expand_cache_status_data_empty_crates_skipped() {
        let data = ExpandCacheStatusData {
            cache_exists: false,
            cache_path: ".sqry/expand-cache".to_string(),
            cache_files: 0,
            total_size_bytes: 0,
            crates: vec![],
            status: "absent".to_string(),
        };
        let json = serde_json::to_value(&data).unwrap();
        assert!(json.get("crates").is_none());
        assert_eq!(json.get("status").unwrap(), "absent");
    }

    #[test]
    fn test_definition_data_with_macro_metadata() {
        let def = DefinitionData {
            name: "my_fn".to_string(),
            qualified_name: "crate::my_fn".to_string(),
            kind: "Function".to_string(),
            file_path: "src/lib.rs".to_string(),
            line: 10,
            column: 1,
            language: "rust".to_string(),
            preview: None,
            macro_metadata: Some(MacroMetadataResponse {
                macro_generated: Some(true),
                macro_source: Some("derive_Debug".to_string()),
                cfg_condition: None,
                cfg_active: None,
                proc_macro_kind: None,
                expansion_cached: None,
                unresolved_attributes: vec![],
            }),
            provenance: None,
        };
        let json = serde_json::to_value(&def).unwrap();
        let mm = json.get("macroMetadata").unwrap();
        assert_eq!(mm.get("macroGenerated").unwrap(), true);
        assert_eq!(mm.get("macroSource").unwrap(), "derive_Debug");
    }

    #[test]
    fn test_definition_data_without_macro_metadata() {
        let def = DefinitionData {
            name: "my_fn".to_string(),
            qualified_name: "crate::my_fn".to_string(),
            kind: "Function".to_string(),
            file_path: "src/lib.rs".to_string(),
            line: 10,
            column: 1,
            language: "rust".to_string(),
            preview: None,
            macro_metadata: None,
            provenance: None,
        };
        let json = serde_json::to_value(&def).unwrap();
        assert!(json.get("macroMetadata").is_none());
    }

    #[test]
    fn test_get_insights_data_with_macro_boundaries() {
        let data = GetInsightsData {
            total_files: 10,
            total_symbols: 100,
            total_edges: 50,
            languages: vec![],
            symbol_kinds: vec![],
            health: HealthIndicatorsData {
                cycles: 0,
                unused_symbols: 5,
                duplicate_groups: 2,
                cross_language_edges: 0,
            },
            macro_boundaries: Some(MacroBoundariesStatsData {
                attribute_macros_detected: 3,
                cfg_gated_symbols: 7,
                macro_generated_symbols: 12,
                unresolved_attributes: 1,
                expand_cache_status: "stale".to_string(),
            }),
        };
        let json = serde_json::to_value(&data).unwrap();
        let mb = json.get("macroBoundaries").unwrap();
        assert_eq!(mb.get("attributeMacrosDetected").unwrap(), 3);
        assert_eq!(mb.get("expandCacheStatus").unwrap(), "stale");
    }

    #[test]
    fn test_get_insights_data_without_macro_boundaries() {
        let data = GetInsightsData {
            total_files: 10,
            total_symbols: 100,
            total_edges: 50,
            languages: vec![],
            symbol_kinds: vec![],
            health: HealthIndicatorsData {
                cycles: 0,
                unused_symbols: 0,
                duplicate_groups: 0,
                cross_language_edges: 0,
            },
            macro_boundaries: None,
        };
        let json = serde_json::to_value(&data).unwrap();
        assert!(json.get("macroBoundaries").is_none());
    }
}