1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
//! Client/server routing, document-open preparation, and capability gating
//! shared by every LSP-round-trip tool-call handler.
use std::path::{Path, PathBuf};
use super::Translator;
use crate::bridge::lock_std;
use crate::bridge::state::detect_language;
use crate::config::{ServerId, ToolKind, base_language_id};
use crate::error::{Error, Result};
use crate::lsp::LspClient;
/// Maximum allowed position value for validation.
pub(super) const MAX_POSITION_VALUE: u32 = 1_000_000;
/// Maximum allowed range size in lines.
pub(super) const MAX_RANGE_LINES: u32 = 10_000;
/// Validate that `path` is within one of `workspace_roots`.
///
/// Free function (rather than a `Translator` method) so callers that only need
/// path validation — e.g. cache-only MCP handlers — can validate against a
/// cloned, lock-free snapshot of the workspace roots instead of locking the
/// full `Arc<Mutex<Translator>>`, which may be held elsewhere across a slow
/// in-flight LSP round-trip.
///
/// # Errors
///
/// Returns `Error::NoWorkspaceRoots` if `workspace_roots` is empty -- fails
/// closed rather than allowing unrestricted access -- and
/// `Error::PathOutsideWorkspace` if the path is outside all configured
/// workspace roots.
pub fn validate_path_against_roots(path: &Path, workspace_roots: &[PathBuf]) -> Result<PathBuf> {
// Checked before canonicalizing so a rootless embedder can't use the
// canonicalize/FileIo error split to probe file existence.
if workspace_roots.is_empty() {
return Err(Error::NoWorkspaceRoots(path.to_path_buf()));
}
let canonical = path.canonicalize().map_err(|e| Error::FileIo {
path: path.to_path_buf(),
source: e,
})?;
// Check if path is within any workspace root
for root in workspace_roots {
if let Ok(canonical_root) = root.canonicalize()
&& canonical.starts_with(&canonical_root)
{
return Ok(canonical);
}
}
Err(Error::PathOutsideWorkspace(path.to_path_buf()))
}
/// Whether a [`Translator::prepare_gated_document`] call site also needs
/// [`Translator::wait_for_indexing_ready`] applied, declared explicitly at
/// the same place capability-gating is declared so a newly added (or newly
/// gated) tool can't silently ship without an indexing-readiness decision
/// either way.
///
/// This only covers call sites that actually go through
/// `prepare_gated_document` -- two production handlers bypass that
/// chokepoint entirely and so make no `IndexingGate` decision at all:
/// - `handle_workspace_symbol` (`workspace_symbol_search`) has no per-file
/// document to resolve or open (it resolves via `resolve_any` instead), so
/// it cannot be routed through this chokepoint as-is. Whether/how to gate
/// it on indexing readiness was deferred as a separate open question (spec
/// FR-008) and remains a known, deliberate limitation -- see #423.
/// - `handle_diagnostics` calls the ungated `Translator::prepare_document`
/// sibling directly, so it gets neither an indexing-readiness decision nor
/// a capability check. The indexing-readiness half of that is deliberate,
/// not an oversight (#445): unlike `handle_incoming_calls`/`handle_outgoing_calls`
/// (#423), it reads from the notification-cache poll path rather than
/// issuing a live whole-workspace LSP request, so blocking it on
/// `wait_for_indexing_ready` the way `Required` does for the other
/// handlers would be the wrong fix shape (it would stall a cache read on a
/// signal the cache itself doesn't need). Instead, the `get_diagnostics`
/// MCP tool (`mcp::server::get_diagnostics`) independently resolves the
/// file's diagnostics-route server and reports its indexing state as an
/// explicit `indexingInProgress` flag on the response
/// (`mcp::server::DiagnosticsResponse`), so a mid-index pull (which can
/// read as "no errors" while rust-analyzer is still loading) is flagged
/// rather than silently trusted. The missing capability check was not
/// analyzed as part of #445 and remains an open question.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum IndexingGate {
/// This tool's answer depends on whole-workspace analysis (e.g. hover,
/// definition, references, rename, completions, code actions, call
/// hierarchy incoming/outgoing calls).
Required,
/// This tool's answer is valid even mid-index (single-file analysis),
/// e.g. `document_symbols`. `handle_call_hierarchy_prepare` also uses
/// this variant, but not for the same reason: unlike `document_symbols`,
/// `prepareCallHierarchy` does perform position-based name resolution
/// (the same class of query as `textDocument/definition`, which *is*
/// [`Self::Required`]) -- leaving it ungated is a deliberate scope
/// decision for #423 (mid-index it degrades to an empty `prepare`
/// result rather than an explicit error), not a claim that it is
/// single-file analysis like `document_symbols`. The incoming/outgoing
/// calls that follow `prepare` use [`Self::Required`].
NotRequired,
}
/// An LSP server capability mcpls gates a tool on before dispatching its
/// request, tying the [`ServerCapabilities`](lsp_types::ServerCapabilities)
/// field name (used only for the error message, via [`Self::name`]) to the
/// predicate that actually checks it (via [`Self::is_supported`]) so the two
/// cannot drift apart the way two independent, hand-picked call-site values
/// could.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Capability {
/// `completionProvider` (`textDocument/completion`).
Completions,
/// `signatureHelpProvider` (`textDocument/signatureHelp`).
SignatureHelp,
/// `inlayHintProvider` (`textDocument/inlayHint`).
InlayHints,
/// `hoverProvider` (`textDocument/hover`).
Hover,
/// `definitionProvider` (`textDocument/definition`).
Definition,
/// `referencesProvider` (`textDocument/references`).
References,
/// `implementationProvider` (`textDocument/implementation`).
Implementation,
/// `typeDefinitionProvider` (`textDocument/typeDefinition`).
TypeDefinition,
/// `callHierarchyProvider` (`textDocument/prepareCallHierarchy`,
/// `callHierarchy/incomingCalls`, `callHierarchy/outgoingCalls`).
CallHierarchy,
/// `renameProvider` (`textDocument/rename`).
Rename,
/// `documentFormattingProvider` (`textDocument/formatting`).
FormatDocument,
/// `codeActionProvider` (`textDocument/codeAction`).
CodeActions,
/// `documentSymbolProvider` (`textDocument/documentSymbol`).
DocumentSymbols,
/// `workspaceSymbolProvider` (`workspace/symbol`).
WorkspaceSymbols,
}
impl Capability {
/// The `ServerCapabilities` field name, as reported to the MCP caller in
/// [`Error::CapabilityNotSupported`].
pub(crate) const fn name(self) -> &'static str {
match self {
Self::Completions => "completionProvider",
Self::SignatureHelp => "signatureHelpProvider",
Self::InlayHints => "inlayHintProvider",
Self::Hover => "hoverProvider",
Self::Definition => "definitionProvider",
Self::References => "referencesProvider",
Self::Implementation => "implementationProvider",
Self::TypeDefinition => "typeDefinitionProvider",
Self::CallHierarchy => "callHierarchyProvider",
Self::Rename => "renameProvider",
Self::FormatDocument => "documentFormattingProvider",
Self::CodeActions => "codeActionProvider",
Self::DocumentSymbols => "documentSymbolProvider",
Self::WorkspaceSymbols => "workspaceSymbolProvider",
}
}
/// Whether `caps` advertises support for this capability.
pub(crate) const fn is_supported(self, caps: &lsp_types::ServerCapabilities) -> bool {
match self {
Self::Completions => caps.completion_provider.is_some(),
Self::SignatureHelp => caps.signature_help_provider.is_some(),
Self::InlayHints => matches!(
caps.inlay_hint_provider,
Some(
lsp_types::InlayHintProvider::Bool(true)
| lsp_types::InlayHintProvider::InlayHintOptions(_)
| lsp_types::InlayHintProvider::InlayHintRegistrationOptions(_)
)
),
Self::Hover => matches!(
caps.hover_provider,
Some(
lsp_types::HoverProvider::Bool(true)
| lsp_types::HoverProvider::HoverOptions(_)
)
),
Self::Definition => matches!(
caps.definition_provider,
Some(
lsp_types::DefinitionProvider::Bool(true)
| lsp_types::DefinitionProvider::DefinitionOptions(_)
)
),
Self::References => matches!(
caps.references_provider,
Some(
lsp_types::ReferencesProvider::Bool(true)
| lsp_types::ReferencesProvider::ReferenceOptions(_)
)
),
Self::Implementation => matches!(
caps.implementation_provider,
Some(
lsp_types::ImplementationProvider::Bool(true)
| lsp_types::ImplementationProvider::ImplementationOptions(_)
| lsp_types::ImplementationProvider::ImplementationRegistrationOptions(_)
)
),
Self::TypeDefinition => matches!(
caps.type_definition_provider,
Some(
lsp_types::TypeDefinitionProvider::Bool(true)
| lsp_types::TypeDefinitionProvider::TypeDefinitionOptions(_)
| lsp_types::TypeDefinitionProvider::TypeDefinitionRegistrationOptions(_)
)
),
Self::CallHierarchy => matches!(
caps.call_hierarchy_provider,
Some(
lsp_types::CallHierarchyProvider::Bool(true)
| lsp_types::CallHierarchyProvider::CallHierarchyOptions(_)
| lsp_types::CallHierarchyProvider::CallHierarchyRegistrationOptions(_)
)
),
Self::Rename => matches!(
caps.rename_provider,
Some(
lsp_types::RenameProvider::Bool(true)
| lsp_types::RenameProvider::RenameOptions(_)
)
),
Self::FormatDocument => matches!(
caps.document_formatting_provider,
Some(
lsp_types::DocumentFormattingProvider::Bool(true)
| lsp_types::DocumentFormattingProvider::DocumentFormattingOptions(_)
)
),
Self::CodeActions => matches!(
caps.code_action_provider,
Some(
lsp_types::CodeActionProvider::Bool(true)
| lsp_types::CodeActionProvider::CodeActionOptions(_)
)
),
Self::DocumentSymbols => matches!(
caps.document_symbol_provider,
Some(
lsp_types::DocumentSymbolProvider::Bool(true)
| lsp_types::DocumentSymbolProvider::DocumentSymbolOptions(_)
)
),
Self::WorkspaceSymbols => matches!(
caps.workspace_symbol_provider,
Some(
lsp_types::WorkspaceSymbolProvider::Bool(true)
| lsp_types::WorkspaceSymbolProvider::WorkspaceSymbolOptions(_)
)
),
}
}
}
impl std::fmt::Display for Capability {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.name())
}
}
impl Translator {
/// Validate that a path is within allowed workspace boundaries.
///
/// # Errors
///
/// Returns `Error::NoWorkspaceRoots` if no workspace roots are
/// configured (fails closed), or `Error::PathOutsideWorkspace` if the
/// path is outside all configured workspace roots.
pub(crate) fn validate_path(&self, path: &Path) -> Result<PathBuf> {
validate_path_against_roots(path, &self.workspace_roots)
}
/// Resolve the client and routing identity for `path`/`tool`, giving the
/// resolved server a chance to be respawned first if its process has
/// died.
///
/// Thin async wrapper around [`Self::client_for_file`] (kept
/// synchronous so its existing unit tests don't need a runtime): this is
/// the entry point async handlers call instead, so a dead server is
/// transparently replaced before its stale client is handed back.
pub(super) async fn resolve_client_for_file(
&self,
path: &Path,
tool: ToolKind,
) -> Result<(ServerId, LspClient)> {
let (id, client) = self.client_for_file(path, tool)?;
self.respawn_if_dead(&id).await?;
let client = lock_std(&self.lsp_clients)
.get(&id)
.cloned()
.unwrap_or(client);
Ok((id, client))
}
/// Resolve the server that should handle `tool` for the file at `path`,
/// returning both its routing identity and a cloned client.
///
/// Tries the file's detected language first, then (if that has no route)
/// its React base language (`.tsx` falling back from `typescriptreact` to
/// `typescript`, and similarly for `.jsx`) -- in that order, so an
/// explicit `typescriptreact` server still wins over the `typescript`
/// fallback when both are configured.
///
/// Locks `router`, `lsp_clients`, and (on the not-yet-registered path)
/// `expected_servers` only for their respective lookups — every guard is
/// dropped before this method returns.
pub(super) fn client_for_file(
&self,
path: &Path,
tool: ToolKind,
) -> Result<(ServerId, LspClient)> {
let language = detect_language(path, &self.extension_map);
let mut candidates: Vec<&str> = vec![language.as_str()];
if let Some(base) = base_language_id(&language) {
candidates.push(base);
}
for lang in &candidates {
let resolved = lock_std(&self.router).resolve(lang, tool).cloned();
let Some(id) = resolved else { continue };
let found = lock_std(&self.lsp_clients).get(&id).cloned();
if let Some(client) = found {
return Ok((id, client));
}
// A route naming a server that is still initializing (e.g. a
// large Unity solution loading via OmniSharp) -- tell the caller
// to wait and retry rather than implying no server is configured.
if lock_std(&self.expected_servers).contains(&id) {
return Err(Error::ServerInitializing { server_id: id });
}
// Unreachable once registration has rebound the router
// (`Translator::rebind_router`) -- a route can only name a
// registered server after that point. Logged rather than
// `debug_assert!`-panicked: this method is reachable by any
// library consumer calling `with_router` without registering
// matching clients, not just internal misuse.
tracing::error!(
"router route names server '{id}' for tool '{tool}' that is neither \
registered nor expected"
);
return Err(Error::NoServerForTool {
language_id: (*lang).to_string(),
tool,
});
}
let has_language = {
let router = lock_std(&self.router);
candidates.iter().any(|lang| router.has_language(lang))
};
if has_language {
Err(Error::NoServerForTool {
language_id: language,
tool,
})
} else {
Err(Error::NoServerForLanguage(language))
}
}
/// Resolve the routing identity of the diagnostics-route server for
/// `path`'s detected language, without requiring that server to be
/// currently registered.
///
/// Mirrors [`Self::client_for_file`]'s language-candidate order (the
/// detected language, then its React base language) but only queries the
/// router: a cache-only caller (`get_cached_diagnostics`) has no LSP
/// round trip to gate a resolved server's registration on, and only
/// needs the id to check [`crate::bridge::NotificationCache::is_push_degraded`]
/// (#359) -- the id itself is stable across a respawn (the routing
/// identity doesn't change, only the registered client behind it does),
/// unlike `NotificationCache::diagnostics_owner`, which a respawn clears
/// along with the crashed server's stale entries.
#[must_use]
pub(crate) fn diagnostics_route_id_for_path(&self, path: &Path) -> Option<ServerId> {
let language = detect_language(path, &self.extension_map);
let mut candidates: Vec<&str> = vec![language.as_str()];
if let Some(base) = base_language_id(&language) {
candidates.push(base);
}
let router = lock_std(&self.router);
candidates
.iter()
.find_map(|lang| router.resolve(lang, ToolKind::Diagnostics).cloned())
}
/// Validate `file_path`, then resolve its routed client via
/// [`Self::resolve_client_for_file`] (respawn-aware), without opening
/// the document.
///
/// Split out from [`Self::prepare_document`] so [`Self::prepare_gated_document`]
/// can check the routed server's capabilities *before* `ensure_open` sends
/// `textDocument/didOpen` -- a server rejected by the gate should never
/// observe an open notification for a request it can't service.
async fn resolve_validated_client_for_file(
&self,
file_path: &str,
tool: ToolKind,
) -> Result<(ServerId, LspClient, PathBuf)> {
let validated_path = self.validate_path(Path::new(file_path))?;
let (server_id, client) = self.resolve_client_for_file(&validated_path, tool).await?;
Ok((server_id, client, validated_path))
}
/// As [`Self::resolve_validated_client_for_file`], but for a caller that
/// already has a `&Path` it validated itself (e.g. `parse_file_uri`'s
/// return value). `path` is trusted to already be validated -- this does
/// *not* re-`canonicalize`/re-check it against workspace roots, unlike
/// the `&str` overload above, which always validates an untrusted MCP
/// input from scratch.
async fn resolve_validated_client_for_path(
&self,
path: &Path,
tool: ToolKind,
) -> Result<(ServerId, LspClient, PathBuf)> {
let (server_id, client) = self.resolve_client_for_file(path, tool).await?;
Ok((server_id, client, path.to_path_buf()))
}
/// Resolve the LSP client and ensure the document is open.
///
/// This is the "prepare" phase shared by every LSP-round-trip handler:
/// it validates the path, selects the client via
/// [`Self::resolve_validated_client_for_file`] (respawn-aware), and
/// calls `ensure_open`, which locks the document tracker's state only
/// for the given path. The returned client and URI are owned values, so
/// the caller can issue the actual LSP request (the "execute" phase)
/// without holding any lock across the network round trip.
///
/// `ensure_open`'s own awaits (a `stat`, optionally a re-read of the
/// file, and the `textDocument/didOpen`/`didChange` notify) run under a
/// lock scoped to `validated_path` alone — see [`DocumentTracker::ensure_open`]
/// — so a slow or wedged language server cannot stall `prepare_document`
/// calls for unrelated files. (Per-tool routing, #228, means the same
/// file can be routed to more than one server; a wedged server-A notify
/// still holds this path's lock and can therefore delay a healthy
/// server-B call for that *same* file.)
pub(super) async fn prepare_document(
&self,
file_path: &str,
tool: ToolKind,
) -> Result<(ServerId, LspClient, lsp_types::Uri)> {
let (server_id, client, validated_path) = self
.resolve_validated_client_for_file(file_path, tool)
.await?;
// Drained unconditionally, before propagating `ensure_open`'s
// result: even on its error path (e.g. a `didOpen`/`didChange`
// notify failure), `DocumentTracker::open` may already have evicted
// a *different*, unrelated document and queued its `didClose` --
// returning early via `?` before this would lose that queued close,
// leaving the tracker desynced from that server (#495 S5).
let result = self
.document_tracker
.ensure_open(&validated_path, &server_id, &client)
.await;
self.notify_evicted_documents().await;
let uri = result?;
Ok((server_id, client, uri))
}
/// Like [`Self::prepare_document`], but checks `capability` against the
/// routed server's `ServerCapabilities` *before* opening the document --
/// see [`Self::resolve_client_for_file`]'s doc comment for why the
/// ordering matters. When `indexing_gate` is
/// [`IndexingGate::Required`], also waits for
/// [`Self::wait_for_indexing_ready`] before opening the document, so a
/// server still indexing never receives (or answers from) an opened
/// document it would otherwise be asked about.
///
/// # Errors
///
/// Returns [`Error::CapabilityNotSupported`] if the routed server's
/// `ServerCapabilities` explicitly does not advertise `capability`, or
/// [`Error::WorkspaceIndexing`] if `indexing_gate` is
/// [`IndexingGate::Required`] and the server is still indexing.
pub(super) async fn prepare_gated_document(
&self,
file_path: &str,
tool: ToolKind,
capability: Capability,
indexing_gate: IndexingGate,
) -> Result<(ServerId, LspClient, lsp_types::Uri)> {
let (server_id, client, validated_path) = self
.resolve_validated_client_for_file(file_path, tool)
.await?;
self.finish_prepare_gated_document(
server_id,
client,
validated_path,
capability,
indexing_gate,
)
.await
}
/// As [`Self::prepare_gated_document`], but for a caller that already
/// has a `&Path` it validated itself (e.g. `handle_incoming_calls`/`handle_outgoing_calls`,
/// via `parse_file_uri`) -- see [`Self::resolve_validated_client_for_path`]'s
/// doc for why this skips re-validation.
pub(super) async fn prepare_gated_document_for_path(
&self,
path: &Path,
tool: ToolKind,
capability: Capability,
indexing_gate: IndexingGate,
) -> Result<(ServerId, LspClient, lsp_types::Uri)> {
let (server_id, client, validated_path) =
self.resolve_validated_client_for_path(path, tool).await?;
self.finish_prepare_gated_document(
server_id,
client,
validated_path,
capability,
indexing_gate,
)
.await
}
/// Shared tail of [`Self::prepare_gated_document`] and
/// [`Self::prepare_gated_document_for_path`], once each has resolved and
/// validated its own path: capability-gate, indexing-gate, then open.
async fn finish_prepare_gated_document(
&self,
server_id: ServerId,
client: LspClient,
validated_path: PathBuf,
capability: Capability,
indexing_gate: IndexingGate,
) -> Result<(ServerId, LspClient, lsp_types::Uri)> {
self.require_capability(&server_id, capability)?;
if indexing_gate == IndexingGate::Required {
self.wait_for_indexing_ready(&server_id).await?;
}
// See `prepare_document`'s matching comment (#495 S5): drained
// unconditionally, before propagating the result, so a queued
// eviction from this call is never lost on `ensure_open`'s error path.
let result = self
.document_tracker
.ensure_open(&validated_path, &server_id, &client)
.await;
self.notify_evicted_documents().await;
let uri = result?;
Ok((server_id, client, uri))
}
/// Sends `textDocument/didClose` to every server that had a document
/// [`DocumentTracker::open`]'s LRU eviction just reclaimed (#495), so a
/// server's own open-document set does not keep growing even though
/// mcpls's own tracking has stopped counting it.
///
/// `DocumentTracker` has no access to any server's [`LspClient`] --
/// `self.lsp_clients` is the registry for that, kept one layer up in
/// `Translator` -- so this is the chokepoint that reconciles
/// [`DocumentTracker::take_evicted`]'s queue against it. Called after
/// every `ensure_open` that could have triggered eviction (both
/// `prepare_document` and `finish_prepare_gated_document`) --
/// unconditionally, even when `ensure_open` itself returned an error, so
/// a different, already-evicted document's queued close is never lost
/// on that path (#495 S5).
///
/// Best-effort: a failed notify is logged and otherwise ignored, exactly
/// like `sync_phase`'s own `didOpen`/`didChange` failures are handled
/// one layer down -- the request that triggered the eviction must not
/// fail just because a *different*, already-evicted document's close
/// notification could not be delivered. A failure here does leave a
/// residual desync, though: mcpls has already forgotten the document
/// (it's out of `document_tracker`), but the server never learned it
/// was closed, so a later `ensure_open` for the same path sends a fresh
/// `didOpen` for a document the server (as far as it knows) already has
/// open. In practice this self-heals whenever that server is later
/// respawned (`forget_server` clears its whole sync history).
async fn notify_evicted_documents(&self) {
for doc in self.document_tracker.take_evicted() {
for server_id in &doc.synced_servers {
let Some(client) = lock_std(&self.lsp_clients).get(server_id).cloned() else {
continue;
};
if let Err(err) = client
.notify_typed::<lsp_types::DidCloseTextDocumentNotification>(
lsp_types::DidCloseTextDocumentParams {
text_document: lsp_types::TextDocumentIdentifier {
uri: doc.uri.clone(),
},
},
)
.await
{
tracing::warn!(
%server_id,
path = %doc.path.display(),
error = %err,
"failed to notify evicted document's server of textDocument/didClose"
);
}
}
}
}
/// Verify the routed server advertises support for a capability before
/// dispatching a capability-gated LSP request.
///
/// Production always registers an [`LspServer`] alongside its
/// [`LspClient`] in the same `register_servers` step (see `lib.rs`), so in
/// practice a registered client always has known capabilities. If no
/// `LspServer` is registered for `server_id` regardless -- a client
/// registered without its server, which only happens in tests, or a
/// narrow window during registration where the two maps are inserted
/// under separate locks -- the capability is assumed supported rather
/// than blocking the request: this mirrors the graceful-degradation
/// stance used elsewhere in `Translator` when capability information is
/// unavailable rather than known-absent.
///
/// Note: this checks the `ServerCapabilities` snapshot captured at
/// `initialize` time. A server that advertises a capability later via
/// `client/registerCapability` (dynamic registration) is not reflected
/// here and will be incorrectly rejected; mcpls does not currently apply
/// dynamic registrations back onto the stored capabilities.
///
/// # Errors
///
/// Returns [`Error::CapabilityNotSupported`] if the registered server's
/// `ServerCapabilities` explicitly does not advertise `capability`.
pub(super) fn require_capability(
&self,
server_id: &ServerId,
capability: Capability,
) -> Result<()> {
let servers = lock_std(&self.lsp_servers);
match servers.get(server_id) {
Some(server) if !capability.is_supported(server.capabilities()) => {
Err(Error::CapabilityNotSupported {
server_id: server_id.clone(),
capability: capability.name(),
})
}
_ => Ok(()),
}
}
/// Returns true when the routed server's `codeActionProvider` capability
/// advertises `resolveProvider: true` (per LSP 3.16, `CodeActionOptions`),
/// meaning it will actually answer a `codeAction/resolve` follow-up
/// request rather than merely receiving mcpls's client-side
/// `resolve_support` advertisement (`lsp/lifecycle.rs`) with no server
/// implementation behind it (#432).
///
/// Unlike [`Self::require_capability`], an unregistered server (only
/// possible in tests, see that method's doc comment) is treated as
/// *not* supporting resolve rather than assumed-supported: resolve is a
/// best-effort enhancement, so the safe default when capability
/// information is unavailable is to skip the extra round-trip, not to
/// risk it against a server that may not implement it.
pub(super) fn code_action_resolve_supported(&self, server_id: &ServerId) -> bool {
let servers = lock_std(&self.lsp_servers);
matches!(
servers
.get(server_id)
.map(crate::lsp::LspServer::capabilities)
.and_then(|caps| caps.code_action_provider.as_ref()),
Some(lsp_types::CodeActionProvider::CodeActionOptions(
lsp_types::CodeActionOptions {
resolve_provider: Some(true),
..
}
))
)
}
/// Parse and validate a file URI, returning the validated path.
///
/// # Errors
///
/// Returns an error if:
/// - The URI doesn't have a file:// scheme, carries an authority, or
/// otherwise cannot be converted to a path (see
/// [`crate::bridge::state::uri_to_path`])
/// - The path is outside workspace boundaries
pub(super) fn parse_file_uri(&self, uri: &lsp_types::Uri) -> Result<PathBuf> {
let path = crate::bridge::state::uri_to_path(uri).ok_or_else(|| {
Error::InvalidToolParams(format!(
"Invalid URI, expected an absolute file:// URI but got: {}",
uri.as_ref()
))
})?;
// Validate path is within workspace
self.validate_path(&path)
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use std::collections::{HashMap, HashSet};
use std::fs;
use std::sync::Arc;
use tempfile::TempDir;
use tokio::io::BufReader;
use tokio::sync::Mutex;
use tokio::time::{Duration, timeout};
use url::Url;
use super::*;
use crate::bridge::NotificationCache;
use crate::bridge::translator::assist::MAX_TRIGGER_CHARACTER_BYTES;
use crate::bridge::translator::dto::Position;
use crate::bridge::translator::edits::MAX_NEW_NAME_LENGTH;
use crate::bridge::translator::testing::*;
use crate::config::{LspServerConfig, ToolRouter};
use crate::error::Error;
use crate::lsp::LspServer;
type JsonValue = serde_json::Value;
#[test]
fn test_client_for_file_server_initializing_when_expected() {
// A configured/applicable language whose LSP client has not registered
// yet (large solution still loading via OmniSharp) must surface
// ServerInitializing — "wait and retry" — not NoServerForLanguage.
let path = PathBuf::from("/ws/Assets/Scripts/Player.cs");
let lang = detect_language(&path, &HashMap::new());
let id = ServerId::from(lang.clone());
let translator = Translator::new().with_router(ToolRouter::catch_all([(id.clone(), lang)]));
let mut expected = HashSet::new();
expected.insert(id.clone());
translator.set_expected_servers(expected);
let err = translator
.client_for_file(&path, ToolKind::Hover)
.unwrap_err();
assert!(matches!(err, Error::ServerInitializing { server_id } if server_id == id));
}
#[test]
fn test_client_for_file_no_server_when_not_expected() {
// When no route is configured for the language at all, the error
// stays NoServerForLanguage.
let translator = Translator::new();
let path = PathBuf::from("/ws/Assets/Scripts/Player.cs");
let lang = detect_language(&path, &translator.extension_map);
let err = translator
.client_for_file(&path, ToolKind::Hover)
.unwrap_err();
assert!(matches!(err, Error::NoServerForLanguage(ref l) if *l == lang));
}
#[test]
fn test_validate_path_no_workspace_roots_rejects_any_path() {
let translator = Translator::new();
let temp_dir = TempDir::new().unwrap();
let test_file = temp_dir.path().join("test.rs");
fs::write(&test_file, "fn main() {}").unwrap();
// With no workspace roots configured, access is rejected (fail closed)
let result = translator.validate_path(&test_file);
assert!(matches!(result, Err(Error::NoWorkspaceRoots(_))));
}
#[test]
fn test_validate_path_within_workspace() {
let mut translator = Translator::new();
let temp_dir = TempDir::new().unwrap();
let workspace_root = temp_dir.path().to_path_buf();
translator.set_workspace_roots(vec![workspace_root]);
let test_file = temp_dir.path().join("test.rs");
fs::write(&test_file, "fn main() {}").unwrap();
let result = translator.validate_path(&test_file);
assert!(result.is_ok());
}
#[test]
fn test_validate_path_outside_workspace() {
let mut translator = Translator::new();
let temp_dir1 = TempDir::new().unwrap();
let temp_dir2 = TempDir::new().unwrap();
// Set workspace root to temp_dir1
translator.set_workspace_roots(vec![temp_dir1.path().to_path_buf()]);
// Create file in temp_dir2 (outside workspace)
let test_file = temp_dir2.path().join("test.rs");
fs::write(&test_file, "fn main() {}").unwrap();
let result = translator.validate_path(&test_file);
assert!(matches!(result, Err(Error::PathOutsideWorkspace(_))));
}
/// Regression guard: `prepare_gated_document`'s `&str` overload (used by
/// `handle_hover` and nearly every other gated handler) must still
/// reject an out-of-workspace path end-to-end, i.e.
/// `resolve_validated_client_for_file` must validate independently
/// rather than ever delegating to the `&Path` overload (whose
/// `resolve_validated_client_for_path` sibling trusts its caller to have
/// already validated and does not check workspace roots itself). Pins
/// down a near-miss caught during the #423/#425 refactor, where
/// `prepare_gated_document` briefly delegated through the `&Path`
/// overload and would have silently skipped this check for every
/// `&str`-based handler.
#[tokio::test]
async fn test_handle_hover_blocked_when_path_outside_workspace() {
let workspace_dir = TempDir::new().unwrap();
let outside_dir = TempDir::new().unwrap();
let server_id = ServerId::from("rust");
let (translator, _server) = translator_with_capabilities(
&workspace_dir,
&server_id,
lsp_types::ServerCapabilities {
hover_provider: Some(lsp_types::HoverProvider::Bool(true)),
..Default::default()
},
);
let outside_path = outside_dir.path().join("outside.rs");
fs::write(&outside_path, "fn outside() {}").unwrap();
let result = translator
.handle_hover(outside_path.to_string_lossy().to_string(), pos(1, 1))
.await;
assert!(matches!(result, Err(Error::PathOutsideWorkspace(_))));
}
#[tokio::test]
async fn test_parse_file_uri_invalid_scheme() {
let translator = Translator::new();
let uri: lsp_types::Uri = lsp_types::Uri::from("http://example.com/file.rs");
let result = translator.parse_file_uri(&uri);
assert!(matches!(result, Err(Error::InvalidToolParams(_))));
}
#[tokio::test]
async fn test_parse_file_uri_valid_scheme() {
let mut translator = Translator::new();
let temp_dir = TempDir::new().unwrap();
translator.set_workspace_roots(vec![temp_dir.path().to_path_buf()]);
let test_file = temp_dir.path().join("test.rs");
fs::write(&test_file, "fn main() {}").unwrap();
// Use url crate for cross-platform file URI creation
let file_url = Url::from_file_path(&test_file).unwrap();
let uri: lsp_types::Uri = lsp_types::Uri::from(file_url.as_str());
let result = translator.parse_file_uri(&uri);
assert!(result.is_ok());
}
/// #411 regression: a raw-sliced (non-decoded) URI keeps `%20`/`%C3%A9`
/// literally in the path, so `canonicalize()` fails with `ENOENT` for
/// any file whose path contains a space or a non-ASCII character, even
/// though the file exists. `parse_file_uri` must percent-decode first.
#[tokio::test]
async fn test_parse_file_uri_percent_decodes_space_and_non_ascii() {
let mut translator = Translator::new();
let temp_dir = TempDir::new().unwrap();
translator.set_workspace_roots(vec![temp_dir.path().to_path_buf()]);
let test_file = temp_dir.path().join("my file café.rs");
fs::write(&test_file, "fn main() {}").unwrap();
let file_url = Url::from_file_path(&test_file).unwrap();
assert!(
file_url.as_str().contains("%20"),
"test fixture must exercise percent-encoding"
);
let uri: lsp_types::Uri = lsp_types::Uri::from(file_url.as_str());
let result = translator.parse_file_uri(&uri).unwrap();
assert_eq!(result, test_file.canonicalize().unwrap());
}
/// #411: an authority-bearing `file://` URI (e.g. `file://host/path`)
/// must be rejected, not silently resolved to a path relative to the
/// process's cwd -- see `uri_to_path`'s authority check.
#[tokio::test]
async fn test_parse_file_uri_rejects_authority() {
let translator = Translator::new();
let uri: lsp_types::Uri = lsp_types::Uri::from("file://host/some/path.rs");
let result = translator.parse_file_uri(&uri);
assert!(matches!(result, Err(Error::InvalidToolParams(_))));
}
#[test]
fn test_client_for_file_uses_custom_extension() {
let temp_dir = TempDir::new().unwrap();
let test_file = temp_dir.path().join("script.nu");
fs::write(&test_file, "echo hello").unwrap();
let mut extension_map = HashMap::new();
extension_map.insert("nu".to_string(), "nushell".to_string());
let translator = Translator::new().with_extensions(extension_map);
let result = translator.client_for_file(&test_file, ToolKind::Hover);
assert!(result.is_err());
if let Err(Error::NoServerForLanguage(lang)) = result {
assert_eq!(lang, "nushell");
} else {
panic!("Expected NoServerForLanguage(nushell) error");
}
}
#[test]
fn test_client_for_file_falls_back_to_default() {
let temp_dir = TempDir::new().unwrap();
let test_file = temp_dir.path().join("unknown.xyz");
fs::write(&test_file, "content").unwrap();
let mut extension_map = HashMap::new();
extension_map.insert("rs".to_string(), "rust".to_string());
let translator = Translator::new().with_extensions(extension_map);
let result = translator.client_for_file(&test_file, ToolKind::Hover);
assert!(result.is_err());
if let Err(Error::NoServerForLanguage(lang)) = result {
assert_eq!(lang, "plaintext");
} else {
panic!("Expected NoServerForLanguage(plaintext) error");
}
}
#[test]
fn test_client_for_file_routes_tsx_to_typescript_server() {
let temp_dir = TempDir::new().unwrap();
let test_file = temp_dir.path().join("component.tsx");
fs::write(&test_file, "export const Component = () => <div />").unwrap();
let mut extension_map = HashMap::new();
extension_map.insert("tsx".to_string(), "typescriptreact".to_string());
let translator = Translator::new()
.with_extensions(extension_map)
.with_router(ToolRouter::catch_all([(
ServerId::from("typescript"),
"typescript".to_string(),
)]));
translator.register_client(
"typescript".to_string(),
LspClient::new(crate::config::LspServerConfig::typescript()),
);
let (_id, client) = translator
.client_for_file(&test_file, ToolKind::Hover)
.unwrap();
assert_eq!(client.language_id(), "typescript");
}
#[test]
fn test_client_for_file_prefers_exact_react_server() {
let temp_dir = TempDir::new().unwrap();
let test_file = temp_dir.path().join("component.tsx");
fs::write(&test_file, "export const Component = () => <div />").unwrap();
let mut extension_map = HashMap::new();
extension_map.insert("tsx".to_string(), "typescriptreact".to_string());
let typescript_react_config = crate::config::LspServerConfig {
language_id: "typescriptreact".to_string(),
command: "typescript-language-server".to_string(),
args: vec!["--stdio".to_string()],
env: HashMap::new(),
file_patterns: vec!["**/*.tsx".to_string()],
initialization_options: None,
timeout_seconds: 30,
request_timeout_seconds: 30,
heuristics: None,
name: None,
handles: None,
indexing: crate::bridge::IndexingPolicy::Auto,
};
let translator = Translator::new()
.with_extensions(extension_map)
.with_router(ToolRouter::catch_all([
(ServerId::from("typescript"), "typescript".to_string()),
(
ServerId::from("typescriptreact"),
"typescriptreact".to_string(),
),
]));
translator.register_client(
"typescript".to_string(),
LspClient::new(crate::config::LspServerConfig::typescript()),
);
translator.register_client(
"typescriptreact".to_string(),
LspClient::new(typescript_react_config),
);
let (_id, client) = translator
.client_for_file(&test_file, ToolKind::Hover)
.unwrap();
assert_eq!(client.language_id(), "typescriptreact");
}
/// #359: `diagnostics_route_id_for_path` must resolve the same id
/// `is_diagnostics_route`/the router would, without requiring a
/// registered client -- `get_cached_diagnostics` relies on this to look
/// up `NotificationCache::is_push_degraded` even when the file's server
/// is currently down (mid-respawn or crash-looping).
#[test]
fn test_diagnostics_route_id_for_path_resolves_without_registered_client() {
let temp_dir = TempDir::new().unwrap();
let test_file = temp_dir.path().join("main.rs");
fs::write(&test_file, "fn main() {}").unwrap();
let mut extension_map = HashMap::new();
extension_map.insert("rs".to_string(), "rust".to_string());
let id = ServerId::from("rust");
let translator = Translator::new()
.with_extensions(extension_map)
.with_router(ToolRouter::catch_all([(id.clone(), "rust".to_string())]));
// Deliberately no `register_client`/`register_server`: this must not
// require a live registration, unlike `client_for_file`.
assert_eq!(
translator.diagnostics_route_id_for_path(&test_file),
Some(id)
);
}
/// A file whose language has no configured route resolves to `None`
/// rather than panicking or falling back to some default server.
#[test]
fn test_diagnostics_route_id_for_path_returns_none_for_unrouted_language() {
let temp_dir = TempDir::new().unwrap();
let test_file = temp_dir.path().join("unknown.xyz");
fs::write(&test_file, "content").unwrap();
let translator = Translator::new();
assert_eq!(translator.diagnostics_route_id_for_path(&test_file), None);
}
#[test]
fn test_client_for_file_routes_jsx_to_javascript_server() {
let temp_dir = TempDir::new().unwrap();
let test_file = temp_dir.path().join("component.jsx");
fs::write(&test_file, "export const Component = () => <div />").unwrap();
let mut extension_map = HashMap::new();
extension_map.insert("jsx".to_string(), "javascriptreact".to_string());
let javascript_config = crate::config::LspServerConfig {
language_id: "javascript".to_string(),
command: "typescript-language-server".to_string(),
args: vec!["--stdio".to_string()],
env: HashMap::new(),
file_patterns: vec!["**/*.js".to_string(), "**/*.jsx".to_string()],
initialization_options: None,
timeout_seconds: 30,
request_timeout_seconds: 30,
heuristics: None,
name: None,
handles: None,
indexing: crate::bridge::IndexingPolicy::Auto,
};
let translator = Translator::new()
.with_extensions(extension_map)
.with_router(ToolRouter::catch_all([(
ServerId::from("javascript"),
"javascript".to_string(),
)]));
translator.register_client("javascript".to_string(), LspClient::new(javascript_config));
let (_id, client) = translator
.client_for_file(&test_file, ToolKind::Hover)
.unwrap();
assert_eq!(client.language_id(), "javascript");
}
#[tokio::test]
async fn test_serve_initializes_translator_with_extensions() {
use crate::bridge::indexing::DEFAULT_INDEXING_READY_TIMEOUT_SECS;
use crate::bridge::state::{DEFAULT_MAX_DOCUMENTS, DEFAULT_MAX_FILE_SIZE};
use crate::config::{LanguageExtensionMapping, WorkspaceConfig};
let language_extensions = vec![
LanguageExtensionMapping {
extensions: vec!["nu".to_string()],
language_id: "nushell".to_string(),
},
LanguageExtensionMapping {
extensions: vec!["rs".to_string()],
language_id: "rust".to_string(),
},
];
let config = crate::config::ServerConfig {
mcp: crate::config::McpConfig::default(),
workspace: WorkspaceConfig {
roots: vec![PathBuf::from("/tmp/test-workspace")],
position_encodings: vec!["utf-8".to_string()],
language_extensions: language_extensions.clone(),
heuristics_max_depth: 10,
max_documents: DEFAULT_MAX_DOCUMENTS,
max_file_size: DEFAULT_MAX_FILE_SIZE,
indexing_ready_timeout_seconds: DEFAULT_INDEXING_READY_TIMEOUT_SECS,
},
lsp_servers: vec![],
project_config_ignored: false,
};
let extension_map = config.build_effective_extension_map();
assert_eq!(extension_map.get("nu"), Some(&"nushell".to_string()));
assert_eq!(extension_map.get("rs"), Some(&"rust".to_string()));
// serve() starts in protocol-only mode when no LSP servers are configured;
// it may return a transport error but must not return NoServersAvailable.
let result = crate::serve(config).await;
if let Err(ref err) = result {
assert!(
!matches!(err, crate::error::Error::NoServersAvailable(_)),
"serve() must not return NoServersAvailable for empty lsp_servers config"
);
}
}
#[tokio::test]
async fn test_concurrent_handlers_on_different_files_do_not_serialize() {
// Before the fix, Translator was shared as Arc<Mutex<Translator>>, so
// handling one LSP request held that lock across the `.await` on the
// response -- blocking every other tool call, even for a completely
// different file and language server, until the first request
// completed or timed out (up to 30s). With interior mutability, a
// concurrent call for a different file must complete without waiting
// on an unrelated in-flight request.
let dir = TempDir::new().unwrap();
let mut extensions = HashMap::new();
extensions.insert("aa".to_string(), "lang_a".to_string());
extensions.insert("bb".to_string(), "lang_b".to_string());
let mut translator =
Translator::new()
.with_extensions(extensions)
.with_router(ToolRouter::catch_all([
(ServerId::from("lang_a"), "lang_a".to_string()),
(ServerId::from("lang_b"), "lang_b".to_string()),
]));
translator.set_workspace_roots(vec![dir.path().to_path_buf()]);
let (client_a, mut server_a) = fake_lsp_client();
let (client_b, mut server_b) = fake_lsp_client();
translator.register_client("lang_a".to_string(), client_a);
translator.register_client("lang_b".to_string(), client_b);
let path_a = dir.path().join("file.aa");
let path_b = dir.path().join("file.bb");
fs::write(&path_a, "content a").unwrap();
fs::write(&path_b, "content b").unwrap();
let translator = Arc::new(translator);
// `server_a` is never given a response, simulating a slow server. If
// any translator-held lock still spanned the LSP round trip, this
// task blocking forever would also block the "fast" call below.
let slow = {
let translator = Arc::clone(&translator);
let path = path_a.to_string_lossy().to_string();
tokio::spawn(async move {
translator
.handle_hover(
path,
Position {
line: 1,
character: 1,
},
)
.await
})
};
// Wait for the slow task to actually reach its LSP request (i.e. the
// request bytes were written to the wire) before treating it as
// "in-flight", so the test doesn't race the spawned task's startup.
let mut wire_a = BufReader::new(&mut server_a.write_stdout);
let opened_a = read_framed_message(&mut wire_a).await;
assert_eq!(opened_a["method"], "textDocument/didOpen");
let hover_request_a = read_framed_message(&mut wire_a).await;
assert_eq!(hover_request_a["method"], "textDocument/hover");
// The fast path: a concurrent call for a different file/server.
let fast = {
let translator = Arc::clone(&translator);
let path = path_b.to_string_lossy().to_string();
tokio::spawn(async move {
translator
.handle_hover(
path,
Position {
line: 1,
character: 1,
},
)
.await
})
};
let mut wire_b = BufReader::new(&mut server_b.write_stdout);
let opened_b = read_framed_message(&mut wire_b).await;
assert_eq!(opened_b["method"], "textDocument/didOpen");
let hover_request_b = read_framed_message(&mut wire_b).await;
assert_eq!(hover_request_b["method"], "textDocument/hover");
write_response(
&mut server_b.read_half_stdin,
&hover_request_b["id"],
JsonValue::Null,
)
.await;
let fast_result = timeout(Duration::from_secs(2), fast)
.await
.expect("fast call must not be blocked by the slow in-flight request")
.unwrap();
assert!(fast_result.is_ok());
assert!(
!slow.is_finished(),
"slow call should still be waiting on its (never-sent) response"
);
slow.abort();
}
#[tokio::test]
async fn test_concurrent_ensure_open_same_path_sends_single_did_open() {
// Regression test: concurrent handler calls for the SAME path must
// serialize on that path's `ensure_open` lock (see `DocumentTracker::lock_path`)
// so they can't both observe "not open yet" and both send didOpen.
let dir = TempDir::new().unwrap();
let mut extensions = HashMap::new();
extensions.insert("aa".to_string(), "lang_a".to_string());
let mut translator =
Translator::new()
.with_extensions(extensions)
.with_router(ToolRouter::catch_all([(
ServerId::from("lang_a"),
"lang_a".to_string(),
)]));
translator.set_workspace_roots(vec![dir.path().to_path_buf()]);
let (client, mut server) = fake_lsp_client();
translator.register_client("lang_a".to_string(), client);
let path = dir.path().join("file.aa");
fs::write(&path, "content").unwrap();
let concurrent_calls = 4;
let translator = Arc::new(translator);
let path_str = path.to_string_lossy().to_string();
let handles: Vec<_> = (0..concurrent_calls)
.map(|_| {
let translator = Arc::clone(&translator);
let path_str = path_str.clone();
tokio::spawn(async move {
translator
.handle_hover(
path_str,
Position {
line: 1,
character: 1,
},
)
.await
})
})
.collect();
let mut wire = BufReader::new(&mut server.write_stdout);
let opened = read_framed_message(&mut wire).await;
assert_eq!(opened["method"], "textDocument/didOpen");
for _ in 0..concurrent_calls {
let request = read_framed_message(&mut wire).await;
assert_eq!(
request["method"], "textDocument/hover",
"no second didOpen must appear ahead of the hover requests"
);
write_response(&mut server.read_half_stdin, &request["id"], JsonValue::Null).await;
}
for handle in handles {
let result = timeout(Duration::from_secs(2), handle)
.await
.expect("handler call should not hang")
.unwrap();
assert!(result.is_ok());
}
}
/// #495: once `DocumentTracker::open`'s LRU eviction reclaims a document
/// to make room under `max_documents`, `prepare_document` must notify
/// that document's server with `textDocument/didClose` -- `DocumentTracker`
/// itself has no `LspClient` access to do this, so it's `Translator`'s
/// job (`notify_evicted_documents`) once `ensure_open` returns.
#[tokio::test]
async fn test_prepare_document_sends_didclose_for_evicted_document() {
use crate::bridge::state::ResourceLimits;
let dir = TempDir::new().unwrap();
let mut extensions = HashMap::new();
extensions.insert("aa".to_string(), "lang_a".to_string());
let mut translator = Translator::new()
.with_extensions(extensions)
.with_router(ToolRouter::catch_all([(
ServerId::from("lang_a"),
"lang_a".to_string(),
)]))
.with_resource_limits(ResourceLimits {
max_documents: 1,
max_file_size: 0,
});
translator.set_workspace_roots(vec![dir.path().to_path_buf()]);
let (client, mut server) = fake_lsp_client();
translator.register_client("lang_a".to_string(), client);
let path_a = dir.path().join("a.aa");
fs::write(&path_a, "content a").unwrap();
let path_b = dir.path().join("b.aa");
fs::write(&path_b, "content b").unwrap();
translator
.prepare_document(&path_a.to_string_lossy(), ToolKind::Hover)
.await
.unwrap();
let mut wire = BufReader::new(&mut server.write_stdout);
let opened_a = read_framed_message(&mut wire).await;
assert_eq!(opened_a["method"], "textDocument/didOpen");
translator
.prepare_document(&path_b.to_string_lossy(), ToolKind::Hover)
.await
.unwrap();
let opened_b = read_framed_message(&mut wire).await;
assert_eq!(opened_b["method"], "textDocument/didOpen");
let closed_a = read_framed_message(&mut wire).await;
assert_eq!(
closed_a["method"], "textDocument/didClose",
"evicting `a` to make room for `b` under max_documents: 1 must notify its server"
);
assert_eq!(
closed_a["params"]["textDocument"]["uri"], opened_a["params"]["textDocument"]["uri"],
"the didClose must name the evicted document, not the newly opened one"
);
}
/// #495 S5: even when `ensure_open` itself fails for the document being
/// opened (here: its own `didOpen` notify fails), a `didClose` already
/// queued for a *different* document evicted earlier in that same call
/// must still be sent -- `prepare_document` must not lose it by
/// returning early via `?` before draining `take_evicted`. Uses two
/// separate servers (`lang_a` stays healthy, `lang_b`'s connection is
/// broken) so the evicted document's own `didClose` delivery can be
/// observed independently of the failure that aborts this call.
#[tokio::test]
async fn test_prepare_document_still_sends_didclose_when_ensure_open_itself_fails() {
use crate::bridge::state::ResourceLimits;
let dir = TempDir::new().unwrap();
let mut extensions = HashMap::new();
extensions.insert("aa".to_string(), "lang_a".to_string());
extensions.insert("bb".to_string(), "lang_b".to_string());
let mut translator = Translator::new()
.with_extensions(extensions)
.with_router(ToolRouter::catch_all([
(ServerId::from("lang_a"), "lang_a".to_string()),
(ServerId::from("lang_b"), "lang_b".to_string()),
]))
.with_resource_limits(ResourceLimits {
max_documents: 1,
max_file_size: 0,
});
translator.set_workspace_roots(vec![dir.path().to_path_buf()]);
let (client_a, mut server_a) = fake_lsp_client();
translator.register_client("lang_a".to_string(), client_a);
let (client_b, _server_b) = fake_lsp_client();
translator.register_client("lang_b".to_string(), client_b.clone());
let path_a = dir.path().join("a.aa");
fs::write(&path_a, "content a").unwrap();
let path_b = dir.path().join("b.bb");
fs::write(&path_b, "content b").unwrap();
translator
.prepare_document(&path_a.to_string_lossy(), ToolKind::Hover)
.await
.unwrap();
let mut wire_a = BufReader::new(&mut server_a.write_stdout);
let opened_a = read_framed_message(&mut wire_a).await;
assert_eq!(opened_a["method"], "textDocument/didOpen");
// Break only `lang_b`'s connection -- see
// `test_first_open_self_heals_when_did_open_notify_fails` (state.rs)
// for why shutting down a clone deterministically fails the next
// `notify()` on any other clone of the same client.
client_b.shutdown().await.unwrap();
let err = translator
.prepare_document(&path_b.to_string_lossy(), ToolKind::Hover)
.await
.unwrap_err();
assert!(matches!(err, Error::ServerTerminated));
// `a` was evicted (LRU, to make room for `b`) before `b`'s own
// notify failed, and its didClose must still have gone out on
// `lang_a`'s still-healthy connection.
let closed_a = read_framed_message(&mut wire_a).await;
assert_eq!(closed_a["method"], "textDocument/didClose");
assert_eq!(
closed_a["params"]["textDocument"]["uri"],
opened_a["params"]["textDocument"]["uri"]
);
}
/// #174 §12's own headline dispatch scenario: "pyright/pylsp fixture --
/// hover -> pyright, diagnostics -> pylsp, rename (unclaimed) ->
/// `NoServerForTool`", exercised through `Translator`'s public handlers
/// end to end rather than through `ToolRouter`'s unit tests alone.
#[tokio::test]
async fn test_dispatch_routes_hover_and_diagnostics_to_different_servers() {
let dir = TempDir::new().unwrap();
let mut extensions = HashMap::new();
extensions.insert("py".to_string(), "python".to_string());
let pyright_id = ServerId::from("pyright");
let pylsp_id = ServerId::from("pylsp");
let configs = vec![
LspServerConfig {
language_id: "python".to_string(),
command: "pyright-langserver".to_string(),
args: vec![],
env: HashMap::new(),
file_patterns: vec![],
initialization_options: None,
timeout_seconds: 30,
request_timeout_seconds: 30,
heuristics: None,
name: Some("pyright".to_string()),
handles: Some(vec![ToolKind::Hover]),
indexing: crate::bridge::IndexingPolicy::Auto,
},
LspServerConfig {
language_id: "python".to_string(),
command: "pylsp".to_string(),
args: vec![],
env: HashMap::new(),
file_patterns: vec![],
initialization_options: None,
timeout_seconds: 30,
request_timeout_seconds: 30,
heuristics: None,
name: Some("pylsp".to_string()),
handles: Some(vec![ToolKind::Diagnostics]),
indexing: crate::bridge::IndexingPolicy::Auto,
},
];
let router = ToolRouter::from_configs(&configs).unwrap();
let mut translator = Translator::new()
.with_extensions(extensions)
.with_router(router);
translator.set_workspace_roots(vec![dir.path().to_path_buf()]);
let (client_pyright, mut server_pyright) = fake_lsp_client();
let (client_pylsp, mut server_pylsp) = fake_lsp_client();
translator.register_client(pyright_id, client_pyright);
translator.register_client(pylsp_id, client_pylsp);
let path = dir.path().join("main.py");
fs::write(&path, "x = 1").unwrap();
let path_str = path.to_string_lossy().to_string();
let translator = Arc::new(translator);
// rename is claimed by neither server -> NoServerForTool, checked
// first so it can't be masked by either server's wire state.
let rename_result = translator
.handle_rename(path_str.clone(), pos(1, 1), "renamed".to_string())
.await;
assert!(
matches!(
rename_result,
Err(Error::NoServerForTool {
tool: ToolKind::Rename,
..
})
),
"expected NoServerForTool for rename, got {rename_result:?}"
);
// hover must route to pyright: didOpen + hover request on its wire.
let hover = {
let translator = Arc::clone(&translator);
let path_str = path_str.clone();
tokio::spawn(async move { translator.handle_hover(path_str, pos(1, 1)).await })
};
let mut wire_pyright = BufReader::new(&mut server_pyright.write_stdout);
let opened = read_framed_message(&mut wire_pyright).await;
assert_eq!(opened["method"], "textDocument/didOpen");
let hover_request = read_framed_message(&mut wire_pyright).await;
assert_eq!(hover_request["method"], "textDocument/hover");
write_response(
&mut server_pyright.read_half_stdin,
&hover_request["id"],
JsonValue::Null,
)
.await;
hover
.await
.unwrap()
.expect("hover routed to pyright must succeed");
// diagnostics must route to pylsp, independently of pyright: its own
// didOpen (a second server's first sync of the same path) followed
// by the diagnostic request on pylsp's wire, never pyright's.
let diagnostics = {
let translator = Arc::clone(&translator);
let notification_cache = Arc::new(Mutex::new(NotificationCache::new()));
tokio::spawn(async move {
translator
.handle_diagnostics(path_str, ¬ification_cache)
.await
})
};
let mut wire_pylsp = BufReader::new(&mut server_pylsp.write_stdout);
let opened = read_framed_message(&mut wire_pylsp).await;
assert_eq!(opened["method"], "textDocument/didOpen");
let diag_request = read_framed_message(&mut wire_pylsp).await;
assert_eq!(diag_request["method"], "textDocument/diagnostic");
// Routing is proven by the request landing on pylsp's wire; abort
// rather than crafting a well-formed DocumentDiagnosticReportResult.
diagnostics.abort();
}
/// No `LspServer` registered for `server_id` (only a raw `LspClient`, as
/// most tests in this module do) -- capability is unknown, so the gate
/// must not block the request.
#[test]
fn test_require_capability_ok_when_server_not_registered() {
let translator = Translator::new();
let result = translator.require_capability(&ServerId::from("rust"), Capability::Rename);
assert!(result.is_ok());
}
#[tokio::test]
async fn test_require_capability_ok_when_capability_present() {
let translator = Translator::new();
let server_id = ServerId::from("rust");
let caps = lsp_types::ServerCapabilities {
rename_provider: Some(lsp_types::RenameProvider::Bool(true)),
..Default::default()
};
translator.register_server(server_id.clone(), LspServer::new_for_test(caps));
let result = translator.require_capability(&server_id, Capability::Rename);
assert!(result.is_ok());
}
#[tokio::test]
async fn test_require_capability_err_when_capability_absent() {
let translator = Translator::new();
let server_id = ServerId::from("rust");
let caps = lsp_types::ServerCapabilities::default();
translator.register_server(server_id.clone(), LspServer::new_for_test(caps));
let result = translator.require_capability(&server_id, Capability::Rename);
assert!(matches!(
result,
Err(Error::CapabilityNotSupported {
capability: "renameProvider",
..
})
));
}
/// #309: an oversized `new_name` must be rejected before any server
/// routing is attempted, so no LSP server needs to be registered here.
#[tokio::test]
async fn test_handle_rename_rejects_oversized_new_name() {
let translator = Translator::new();
let new_name = "a".repeat(MAX_NEW_NAME_LENGTH + 1);
let result = translator
.handle_rename(
"/main.rs".to_string(),
Position {
line: 1,
character: 1,
},
new_name,
)
.await;
assert!(matches!(result, Err(Error::InvalidToolParams(_))));
}
#[tokio::test]
async fn test_handle_rename_blocked_when_capability_not_supported() {
let dir = TempDir::new().unwrap();
let server_id = ServerId::from("rust");
let (translator, _server) = translator_with_capabilities(
&dir,
&server_id,
lsp_types::ServerCapabilities::default(),
);
let path = dir.path().join("main.rs");
fs::write(&path, "fn main() {}").unwrap();
let result = translator
.handle_rename(
path.to_string_lossy().to_string(),
Position {
line: 1,
character: 1,
},
"renamed".to_string(),
)
.await;
assert!(matches!(
result,
Err(Error::CapabilityNotSupported {
capability: "renameProvider",
..
})
));
}
#[tokio::test]
async fn test_handle_code_actions_blocked_when_capability_not_supported() {
let dir = TempDir::new().unwrap();
let server_id = ServerId::from("rust");
let (translator, _server) = translator_with_capabilities(
&dir,
&server_id,
lsp_types::ServerCapabilities::default(),
);
let path = dir.path().join("main.rs");
fs::write(&path, "fn main() {}").unwrap();
let result = translator
.handle_code_actions(
path.to_string_lossy().to_string(),
Position {
line: 1,
character: 1,
},
Position {
line: 1,
character: 5,
},
None,
)
.await;
assert!(matches!(
result,
Err(Error::CapabilityNotSupported {
capability: "codeActionProvider",
..
})
));
}
#[tokio::test]
async fn test_handle_signature_help_blocked_when_capability_not_supported() {
let dir = TempDir::new().unwrap();
let server_id = ServerId::from("rust");
let (translator, _server) = translator_with_capabilities(
&dir,
&server_id,
lsp_types::ServerCapabilities::default(),
);
let path = dir.path().join("main.rs");
fs::write(&path, "fn main() {}").unwrap();
let result = translator
.handle_signature_help(
path.to_string_lossy().to_string(),
Position {
line: 1,
character: 1,
},
)
.await;
assert!(matches!(
result,
Err(Error::CapabilityNotSupported {
capability: "signatureHelpProvider",
..
})
));
}
/// `handle_incoming_calls` resolves its server via `client_for_file`
/// directly (not `prepare_document`), a separate code path from the other
/// gated handlers -- exercise it explicitly.
#[tokio::test]
async fn test_handle_incoming_calls_blocked_when_capability_not_supported() {
let dir = TempDir::new().unwrap();
let server_id = ServerId::from("rust");
let (translator, _server) = translator_with_capabilities(
&dir,
&server_id,
lsp_types::ServerCapabilities::default(),
);
let path = dir.path().join("main.rs");
fs::write(&path, "fn main() {}").unwrap();
let uri = Url::from_file_path(&path).unwrap().to_string();
let item = serde_json::json!({
"name": "test_function",
"kind": 12,
"uri": uri,
"range": {
"start": {"line": 1, "character": 1},
"end": {"line": 1, "character": 10}
},
"selectionRange": {
"start": {"line": 1, "character": 1},
"end": {"line": 1, "character": 10}
}
});
let result = translator.handle_incoming_calls(item).await;
assert!(matches!(
result,
Err(Error::CapabilityNotSupported {
capability: "callHierarchyProvider",
..
})
));
}
#[tokio::test]
async fn test_handle_outgoing_calls_blocked_when_capability_not_supported() {
let dir = TempDir::new().unwrap();
let server_id = ServerId::from("rust");
let (translator, _server) = translator_with_capabilities(
&dir,
&server_id,
lsp_types::ServerCapabilities::default(),
);
let path = dir.path().join("main.rs");
fs::write(&path, "fn main() {}").unwrap();
let uri = Url::from_file_path(&path).unwrap().to_string();
let item = serde_json::json!({
"name": "test_function",
"kind": 12,
"uri": uri,
"range": {
"start": {"line": 1, "character": 1},
"end": {"line": 1, "character": 10}
},
"selectionRange": {
"start": {"line": 1, "character": 1},
"end": {"line": 1, "character": 10}
}
});
let result = translator.handle_outgoing_calls(item).await;
assert!(matches!(
result,
Err(Error::CapabilityNotSupported {
capability: "callHierarchyProvider",
..
})
));
}
#[tokio::test]
async fn test_handle_format_document_blocked_when_capability_not_supported() {
let dir = TempDir::new().unwrap();
let server_id = ServerId::from("rust");
let (translator, _server) = translator_with_capabilities(
&dir,
&server_id,
lsp_types::ServerCapabilities::default(),
);
let path = dir.path().join("main.rs");
fs::write(&path, "fn main() {}").unwrap();
let result = translator
.handle_format_document(path.to_string_lossy().to_string(), 4, true)
.await;
assert!(matches!(
result,
Err(Error::CapabilityNotSupported {
capability: "documentFormattingProvider",
..
})
));
}
#[tokio::test]
async fn test_handle_call_hierarchy_prepare_blocked_when_capability_not_supported() {
let dir = TempDir::new().unwrap();
let server_id = ServerId::from("rust");
let (translator, _server) = translator_with_capabilities(
&dir,
&server_id,
lsp_types::ServerCapabilities::default(),
);
let path = dir.path().join("main.rs");
fs::write(&path, "fn main() {}").unwrap();
let result = translator
.handle_call_hierarchy_prepare(
path.to_string_lossy().to_string(),
Position {
line: 1,
character: 1,
},
)
.await;
assert!(matches!(
result,
Err(Error::CapabilityNotSupported {
capability: "callHierarchyProvider",
..
})
));
}
#[tokio::test]
async fn test_handle_inlay_hints_blocked_when_capability_not_supported() {
let dir = TempDir::new().unwrap();
let server_id = ServerId::from("rust");
let (translator, _server) = translator_with_capabilities(
&dir,
&server_id,
lsp_types::ServerCapabilities::default(),
);
let path = dir.path().join("main.rs");
fs::write(&path, "fn main() {}").unwrap();
let result = translator
.handle_inlay_hints(
path.to_string_lossy().to_string(),
Position {
line: 1,
character: 1,
},
Position {
line: 10,
character: 1,
},
)
.await;
assert!(matches!(
result,
Err(Error::CapabilityNotSupported {
capability: "inlayHintProvider",
..
})
));
}
#[tokio::test]
async fn test_handle_hover_blocked_when_capability_not_supported() {
let dir = TempDir::new().unwrap();
let server_id = ServerId::from("rust");
let (translator, _server) = translator_with_capabilities(
&dir,
&server_id,
lsp_types::ServerCapabilities::default(),
);
let path = dir.path().join("main.rs");
fs::write(&path, "fn main() {}").unwrap();
let result = translator
.handle_hover(
path.to_string_lossy().to_string(),
Position {
line: 1,
character: 1,
},
)
.await;
assert!(matches!(
result,
Err(Error::CapabilityNotSupported {
capability: "hoverProvider",
..
})
));
}
#[tokio::test]
async fn test_handle_definition_blocked_when_capability_not_supported() {
let dir = TempDir::new().unwrap();
let server_id = ServerId::from("rust");
let (translator, _server) = translator_with_capabilities(
&dir,
&server_id,
lsp_types::ServerCapabilities::default(),
);
let path = dir.path().join("main.rs");
fs::write(&path, "fn main() {}").unwrap();
let result = translator
.handle_definition(
path.to_string_lossy().to_string(),
Position {
line: 1,
character: 1,
},
)
.await;
assert!(matches!(
result,
Err(Error::CapabilityNotSupported {
capability: "definitionProvider",
..
})
));
}
#[tokio::test]
async fn test_handle_references_blocked_when_capability_not_supported() {
let dir = TempDir::new().unwrap();
let server_id = ServerId::from("rust");
let (translator, _server) = translator_with_capabilities(
&dir,
&server_id,
lsp_types::ServerCapabilities::default(),
);
let path = dir.path().join("main.rs");
fs::write(&path, "fn main() {}").unwrap();
let result = translator
.handle_references(
path.to_string_lossy().to_string(),
Position {
line: 1,
character: 1,
},
false,
)
.await;
assert!(matches!(
result,
Err(Error::CapabilityNotSupported {
capability: "referencesProvider",
..
})
));
}
/// #309 M3: an oversized `trigger` must be rejected before any server
/// routing is attempted.
#[tokio::test]
async fn test_handle_completions_rejects_oversized_trigger() {
let translator = Translator::new();
let trigger = "a".repeat(MAX_TRIGGER_CHARACTER_BYTES + 1);
let result = translator
.handle_completions(
"/main.rs".to_string(),
Position {
line: 1,
character: 1,
},
Some(trigger),
)
.await;
assert!(matches!(result, Err(Error::InvalidToolParams(_))));
}
#[tokio::test]
async fn test_handle_completions_blocked_when_capability_not_supported() {
let dir = TempDir::new().unwrap();
let server_id = ServerId::from("rust");
let (translator, _server) = translator_with_capabilities(
&dir,
&server_id,
lsp_types::ServerCapabilities::default(),
);
let path = dir.path().join("main.rs");
fs::write(&path, "fn main() {}").unwrap();
let result = translator
.handle_completions(
path.to_string_lossy().to_string(),
Position {
line: 1,
character: 1,
},
None,
)
.await;
assert!(matches!(
result,
Err(Error::CapabilityNotSupported {
capability: "completionProvider",
..
})
));
}
#[tokio::test]
async fn test_handle_document_symbols_blocked_when_capability_not_supported() {
let dir = TempDir::new().unwrap();
let server_id = ServerId::from("rust");
let (translator, _server) = translator_with_capabilities(
&dir,
&server_id,
lsp_types::ServerCapabilities::default(),
);
let path = dir.path().join("main.rs");
fs::write(&path, "fn main() {}").unwrap();
let result = translator
.handle_document_symbols(path.to_string_lossy().to_string())
.await;
assert!(matches!(
result,
Err(Error::CapabilityNotSupported {
capability: "documentSymbolProvider",
..
})
));
}
#[tokio::test]
async fn test_handle_workspace_symbol_blocked_when_capability_not_supported() {
let dir = TempDir::new().unwrap();
let server_id = ServerId::from("rust");
let (translator, _server) = translator_with_capabilities(
&dir,
&server_id,
lsp_types::ServerCapabilities::default(),
);
let result = translator
.handle_workspace_symbol("main".to_string(), None, 100)
.await;
assert!(matches!(
result,
Err(Error::CapabilityNotSupported {
capability: "workspaceSymbolProvider",
..
})
));
}
#[tokio::test]
async fn test_handle_implementation_blocked_when_capability_not_supported() {
let dir = TempDir::new().unwrap();
let server_id = ServerId::from("rust");
let (translator, _server) = translator_with_capabilities(
&dir,
&server_id,
lsp_types::ServerCapabilities::default(),
);
let path = dir.path().join("main.rs");
fs::write(&path, "fn main() {}").unwrap();
let result = translator
.handle_implementation(
path.to_string_lossy().to_string(),
Position {
line: 1,
character: 1,
},
)
.await;
assert!(matches!(
result,
Err(Error::CapabilityNotSupported {
capability: "implementationProvider",
..
})
));
}
#[tokio::test]
async fn test_handle_type_definition_blocked_when_capability_not_supported() {
let dir = TempDir::new().unwrap();
let server_id = ServerId::from("rust");
let (translator, _server) = translator_with_capabilities(
&dir,
&server_id,
lsp_types::ServerCapabilities::default(),
);
let path = dir.path().join("main.rs");
fs::write(&path, "fn main() {}").unwrap();
let result = translator
.handle_type_definition(
path.to_string_lossy().to_string(),
Position {
line: 1,
character: 1,
},
)
.await;
assert!(matches!(
result,
Err(Error::CapabilityNotSupported {
capability: "typeDefinitionProvider",
..
})
));
}
/// Explicit `Some(RenameProvider::Bool(false))` -- as distinct from an absent
/// (`None`) field -- must also be rejected: some servers advertise a
/// provider field with an explicit `false` rather than omitting it.
#[tokio::test]
async fn test_require_capability_err_when_capability_explicitly_false() {
let translator = Translator::new();
let server_id = ServerId::from("rust");
let caps = lsp_types::ServerCapabilities {
rename_provider: Some(lsp_types::RenameProvider::Bool(false)),
..Default::default()
};
translator.register_server(server_id.clone(), LspServer::new_for_test(caps));
let result = translator.require_capability(&server_id, Capability::Rename);
assert!(matches!(
result,
Err(Error::CapabilityNotSupported {
capability: "renameProvider",
..
})
));
}
/// Positive path: when the routed server *does* advertise the gated
/// capability, the gate must let the request proceed into dispatch rather
/// than short-circuiting with `CapabilityNotSupported`. Drives the fake
/// wire to answer the request so the call completes quickly instead of
/// idling out its internal 30s request timeout.
#[tokio::test]
async fn test_handle_rename_proceeds_when_capability_supported() {
let dir = TempDir::new().unwrap();
let server_id = ServerId::from("rust");
let caps = lsp_types::ServerCapabilities {
rename_provider: Some(lsp_types::RenameProvider::Bool(true)),
..Default::default()
};
let (translator, mut server) = translator_with_capabilities(&dir, &server_id, caps);
let path = dir.path().join("main.rs");
fs::write(&path, "fn main() {}").unwrap();
let path_str = path.to_string_lossy().to_string();
let translator = Arc::new(translator);
let handle = {
let translator = Arc::clone(&translator);
tokio::spawn(async move {
translator
.handle_rename(
path_str,
Position {
line: 1,
character: 1,
},
"renamed".to_string(),
)
.await
})
};
let mut wire = BufReader::new(&mut server.write_stdout);
let opened = read_framed_message(&mut wire).await;
assert_eq!(opened["method"], "textDocument/didOpen");
let rename_request = read_framed_message(&mut wire).await;
assert_eq!(rename_request["method"], "textDocument/rename");
write_response(
&mut server.read_half_stdin,
&rename_request["id"],
JsonValue::Null,
)
.await;
let result = timeout(Duration::from_secs(2), handle)
.await
.expect("handler call should not hang")
.unwrap();
assert!(
!matches!(result, Err(Error::CapabilityNotSupported { .. })),
"capability is supported, gate must not block dispatch, got {result:?}"
);
assert!(
result.is_ok(),
"fake server answered, expected Ok: {result:?}"
);
}
}