mcpls-core 0.8.0

Core library for MCP to LSP protocol translation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
//! Error types for mcpls-core.
//!
//! This module defines the canonical error type for the library,
//! following the Microsoft Rust Guidelines for error handling.

use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

use serde::Serialize;

use crate::bridge::resources::ResourceUriError;
use crate::bridge::{
    Capability, InvalidClientPath, InvalidHierarchyItem, InvalidPosition, InvalidRange,
};
use crate::config::{
    BuiltinServer, DuplicateEnvKey, EntrySummary, EnvKey, EnvTooLarge, FileKey, FilePattern,
    InvalidAutoSelection, InvalidEnvValue, InvalidServerArgs, LanguageId, ServerCommand, ServerId,
    ToolKind, UnsupportedFilePattern,
};
use crate::lsp::JsonRpcError;
pub use crate::redaction::RedactedText;
use crate::redaction::Redactions;
pub use crate::util::SizeExceeded;
use crate::util::{
    MAX_ECHOED_NAME_BYTES, MAX_ECHOED_PATH_BYTES, MAX_ERROR_MESSAGE_CALLER_BYTES,
    TRUNCATION_MARKER, escape_bounded, escape_control, truncate_str,
};

/// Explains a `plaintext` routing failure: which extension or file name had no
/// mapping and which `file_patterns` were configured. Empty for any other
/// language.
fn no_server_detail(language: &LanguageId, file: &FileKey, patterns: &[FilePattern]) -> String {
    if *language != LanguageId::PLAINTEXT {
        return String::new();
    }
    let (subject, remedy) = match file {
        FileKey::Extension(ext) => (
            format!("file extension '{ext}' is not mapped to any language"),
            "a `*.EXT` file_patterns entry or workspace.language_extensions".to_owned(),
        ),
        FileKey::Name(name) => (
            format!("file name '{name}' is not mapped to any language"),
            format!("a `**/{name}` file_patterns entry"),
        ),
        FileKey::Unmappable => (
            "the file has no usable extension or name".to_owned(),
            "a `*.EXT` file_patterns entry or workspace.language_extensions".to_owned(),
        ),
    };
    let configured = if patterns.is_empty() {
        "no file_patterns are configured".to_owned()
    } else {
        let list: Vec<&str> = patterns.iter().map(FilePattern::as_str).collect();
        format!("configured file_patterns: {}", list.join(", "))
    };
    format!(" ({subject}; {configured}; map it with {remedy})")
}

/// Host platform, as far as [`NotFoundGuidance`] cares.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Platform {
    Windows,
    Other,
}

impl Platform {
    const CURRENT: Self = if cfg!(windows) {
        Self::Windows
    } else {
        Self::Other
    };
}

/// Display suffix explaining how to fix a missing LSP server executable.
struct NotFoundGuidance<'a>(&'a str, Platform);

impl fmt::Display for NotFoundGuidance<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self(command, platform) = *self;
        if Path::new(command).parent().is_some_and(|p| !p.is_empty()) {
            return f.write_str("; check that the configured path exists");
        }
        write!(
            f,
            "; '{command}' is not on the PATH mcpls runs with -- if it is installed, add its \
             directory to the MCP client's PATH or set `command` to an absolute path"
        )?;
        let Some(builtin) = BuiltinServer::from_command(command) else {
            return Ok(());
        };
        if platform == Platform::Windows && builtin.is_npm_package() {
            write!(
                f,
                " (npm-installed servers need the `.cmd` name, e.g. `{command}.cmd`)"
            )?;
        }
        write!(f, "; otherwise install it: {}", builtin.install_hint())
    }
}

/// Substring rust-analyzer's raw error text carries when a position-based
/// request's `line`/`character` falls outside the target document. Shared
/// between [`sanitize_lsp_server_message`] (rewrites the message shown to the
/// caller) and [`Error::mcp_error_kind`] (classifies this shape of
/// [`Error::LspServerError`] as caller-fault) so the two stay in sync.
const INVALID_OFFSET_MARKER: &str = "Invalid offset LineCol";

/// Whether `response` is rust-analyzer's "position out of range" internal
/// error, which [`Error::mcp_error_kind`] classifies as caller-fault.
pub(crate) fn is_invalid_offset(response: &JsonRpcError) -> bool {
    response.message.contains(INVALID_OFFSET_MARKER)
}

/// Rewrites an LSP server's raw error message for display to the MCP caller,
/// replacing rust-analyzer's "Invalid offset" internal error with a clean,
/// client-appropriate message.
///
/// rust-analyzer returns this `Debug`-formatted internal error (embedding its
/// `LineCol` struct and the line index's byte length, e.g. `"Invalid offset
/// LineCol { line: 2291, col: 0 } (line index length: 100417)"`) when a
/// position-based request's `line` or `character` falls outside the target
/// document. Every other [`Error`] variant produces a clean message; this
/// function keeps [`Error::LspServerError`]'s `Display` impl consistent with
/// that convention instead of forwarding the upstream server's internals
/// verbatim.
///
/// Matches via `contains` rather than `starts_with`: rust-analyzer's error
/// travels through `anyhow`/`lsp_server` before reaching mcpls, so a future
/// upstream `.context(...)` wrapper (or a truncation prefix added on the
/// mcpls side) could prepend text ahead of `"Invalid offset LineCol"` without
/// mcpls's control -- `contains` keeps the guard robust to that at no extra
/// cost. Deliberately not also gated on the JSON-RPC error `code`: this error
/// class has been observed under both `-32603` (internal error) and `-32803`
/// (`RequestFailed`) across rust-analyzer versions, so a code condition would
/// make the guard more fragile, not less.
fn sanitize_lsp_server_message(message: &str) -> String {
    if message.contains(INVALID_OFFSET_MARKER) {
        "position out of range for this document".to_string()
    } else {
        escape_control(message).into_owned()
    }
}

/// The raw LSP error behind a position-out-of-range rewrite, carried as the
/// JSON-RPC `data` of the resulting `-32602` error.
///
/// [`Error::LspServerError`]'s `Display` replaces rust-analyzer's internal
/// "Invalid offset" text with a clean message; this keeps the original
/// reachable for the caller. The fields are private so the message can only
/// be built through [`Self::new`], which bounds it.
///
/// # Examples
///
/// ```
/// use mcpls_core::error::RewrittenServerError;
///
/// let raw = RewrittenServerError::new(-32603, "Invalid offset LineCol { line: 9, col: 0 }");
/// assert_eq!(raw.code(), -32603);
/// assert_eq!(
///     serde_json::to_value(&raw).unwrap(),
///     serde_json::json!({"code": -32603, "raw_message": "Invalid offset LineCol { line: 9, col: 0 }"})
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct RewrittenServerError {
    code: i32,
    raw_message: String,
}

impl RewrittenServerError {
    /// Build from the server's JSON-RPC `code` and raw message, truncating
    /// the message to the budget used for text forwarded to MCP callers.
    #[must_use]
    pub fn new(code: i32, raw_message: &str) -> Self {
        Self {
            code,
            raw_message: truncate_str(raw_message, MAX_ERROR_MESSAGE_CALLER_BYTES),
        }
    }

    /// The server's JSON-RPC error code.
    #[must_use]
    pub const fn code(&self) -> i32 {
        self.code
    }

    /// The server's raw message, bounded by [`Self::new`].
    #[must_use]
    pub fn raw_message(&self) -> &str {
        &self.raw_message
    }
}

/// Why a configured LSP server never registered during startup.
///
/// # Examples
///
/// ```
/// use mcpls_core::error::StartupFailure;
///
/// assert!(StartupFailure::InitTaskPanicked.to_string().contains("panicked"));
/// ```
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum StartupFailure {
    /// Spawning or initializing the server failed.
    Spawn(Arc<Error>),
    /// Starting this server, or the background initialization task as a whole,
    /// panicked before the server registered.
    InitTaskPanicked,
    /// The workspace is untrusted and this server was not started.
    RefusedUntrustedWorkspace(UntrustedRefusal),
}

/// An environment variable that names the user's home directory.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum HomeVariable {
    /// `HOME`.
    Home,
    /// `USERPROFILE`.
    UserProfile,
}

impl HomeVariable {
    /// Every home variable untrusted mode manages.
    pub const ALL: [Self; 2] = [Self::Home, Self::UserProfile];

    /// The variable's name in the environment.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Home => "HOME",
            Self::UserProfile => "USERPROFILE",
        }
    }
}

impl fmt::Display for HomeVariable {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

/// What untrusted-workspace mode resolved to a path it could not pass on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResolvedItem {
    /// The server's executable.
    Executable,
    /// The `PATH` handed to the server.
    SearchPath,
}

impl fmt::Display for ResolvedItem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Executable => "executable",
            Self::SearchPath => "PATH",
        })
    }
}

/// A piece of configured launch text that may be shown to callers: an option
/// name or a program name, never a value, an inline program or an
/// assignment's value.
///
/// The text is cut at the first `=` or whitespace, escaped and bounded to
/// 256 bytes (the escaped text is what is bounded), because
/// configured arguments can hold secrets and reach MCP clients unredacted.
///
/// # Examples
///
/// ```
/// use mcpls_core::error::EchoedArgument;
///
/// assert_eq!(EchoedArgument::name("--token=abc").as_str(), "--token");
/// assert_eq!(EchoedArgument::name("API_KEY=abc").as_str(), "API_KEY");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EchoedArgument(String);

impl EchoedArgument {
    /// The option or program name `arg` spells: the text before the first `=`
    /// or whitespace, so an assignment's value or an argument glued to the
    /// name is not echoed. A short cluster is named by its offending letter
    /// (`-x`), built by the caller.
    #[must_use]
    pub fn name(arg: &str) -> Self {
        let name = arg
            .split_once(|c: char| c == '=' || c.is_whitespace())
            .map_or(arg, |(name, _)| name);
        Self(escape_bounded(name, MAX_ECHOED_NAME_BYTES))
    }

    /// The echoed text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// A path the workspace names, shown whole, escaped and bounded.
///
/// The workspace names a program a launcher starts or a symlink target's final
/// component. Unlike [`EchoedArgument`], the text is never cut at a space or an
/// `=`, because a path is not an option with a value. It is bounded to
/// 1024 bytes of escaped text.
///
/// # Examples
///
/// ```
/// use std::path::Path;
///
/// use mcpls_core::error::EchoedPath;
///
/// let path = EchoedPath::new(Path::new("/opt/my tools/a=b/srv"));
/// assert_eq!(path.as_str(), "/opt/my tools/a=b/srv");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EchoedPath(String);

impl EchoedPath {
    /// The whole of `path`, escaped and bounded.
    #[must_use]
    pub fn new(path: &Path) -> Self {
        Self(escape_bounded(
            &path.to_string_lossy(),
            MAX_ECHOED_PATH_BYTES,
        ))
    }

    /// The program an argument names: its whole path, unless the text reads
    /// as an assignment (an `=` before any path separator), which is cut at
    /// the `=` like [`EchoedArgument`] so a value that is not a program is not
    /// echoed.
    #[must_use]
    pub fn program(arg: &str) -> Self {
        let assignment = arg
            .split_once('=')
            .is_some_and(|(name, _)| !name.contains(std::path::is_separator));
        if assignment {
            Self(EchoedArgument::name(arg).0)
        } else {
            Self::new(Path::new(arg))
        }
    }

    /// The echoed text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

/// Renders a path as `{path:?}` does, cut after about 1024 bytes of that text.
///
/// The quoted form is for the paths a caller supplied or a file operation
/// failed on ([`Error::MalformedPath`], [`Error::FileIo`]), where the quotes
/// keep an empty or spaced path unambiguous and non-UTF-8 bytes visible.
/// [`EchoedPath`] is the bare form for paths that read inside a sentence
/// (`NotARegularFile`, `DocumentNotFound`, `PathOutsideWorkspace`,
/// `NoWorkspaceRoots`), lossy for non-UTF-8 bytes. The two differ on purpose.
///
/// The cut is made while the debug text is produced, so the work is bounded by
/// the cut and not by the path, and it never leaves half an escape sequence
/// (`\u{..}`, `\x..`) in front of the truncation marker. Text within the bound
/// is byte-identical to the plain debug form.
struct BoundedDebugPath<'a>(&'a Path);

/// Collects text until `left` bytes are used, then refuses the rest.
struct CutWriter {
    text: String,
    left: usize,
    cut: bool,
}

impl fmt::Write for CutWriter {
    fn write_str(&mut self, piece: &str) -> fmt::Result {
        if self.cut {
            return Err(fmt::Error);
        }
        if piece.len() <= self.left {
            self.text.push_str(piece);
            self.left = self.left.saturating_sub(piece.len());
            return Ok(());
        }
        let keep = piece.floor_char_boundary(self.left);
        self.text.push_str(piece.get(..keep).unwrap_or_default());
        self.cut = true;
        Err(fmt::Error)
    }
}

/// The length of `text` without a trailing incomplete debug escape (`\u{1`,
/// `\x4`, a lone `\`).
fn complete_escapes_len(text: &str) -> usize {
    let mut at = 0;
    while let Some(offset) = text.get(at..).and_then(|tail| tail.find('\\')) {
        let start = at.saturating_add(offset);
        let after = start.saturating_add(1);
        let rest = text.get(after..).unwrap_or_default();
        let escape_len = match rest.chars().next() {
            Some('u') => rest.find('}').map(|end| end.saturating_add(1)),
            Some('x') => (rest.len() >= 3).then_some(3),
            Some(other) => Some(other.len_utf8()),
            None => None,
        };
        let Some(escape_len) = escape_len else {
            return start;
        };
        at = after.saturating_add(escape_len);
    }
    text.len()
}

impl fmt::Display for BoundedDebugPath<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use fmt::Write as _;

        let mut writer = CutWriter {
            text: String::new(),
            left: MAX_ECHOED_PATH_BYTES,
            cut: false,
        };
        // An error only means the writer refused text after the cut.
        #[expect(
            clippy::unnecessary_debug_formatting,
            reason = "the quoted, escaped debug form is the message format"
        )]
        let formatted = write!(writer, "{:?}", self.0);
        debug_assert!(formatted.is_ok() || writer.cut);
        if !writer.cut {
            return f.write_str(&writer.text);
        }
        let whole = complete_escapes_len(&writer.text);
        f.write_str(writer.text.get(..whole).unwrap_or_default())?;
        f.write_str(TRUNCATION_MARKER)
    }
}

impl fmt::Display for EchoedPath {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl fmt::Display for EchoedArgument {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

/// Declares a closed enum of spellings: the variants, `ALL`, `as_str` and
/// `Display`, so a spelling is written once.
macro_rules! spelled_enum {
    (
        $(#[$meta:meta])*
        $name:ident {
            $($(#[$variant_meta:meta])* $variant:ident => $spelling:expr),+ $(,)?
        }
    ) => {
        $(#[$meta])*
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        #[non_exhaustive]
        pub enum $name {
            $($(#[$variant_meta])* $variant),+
        }

        impl $name {
            /// Every variant, in declaration order.
            pub const ALL: [Self; [$(Self::$variant),+].len()] = [$(Self::$variant),+];

            /// The spelling as written on the wire or a command line.
            #[must_use]
            pub const fn as_str(self) -> &'static str {
                match self {
                    $(Self::$variant => $spelling),+
                }
            }
        }

        impl ::std::fmt::Display for $name {
            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
                f.write_str(self.as_str())
            }
        }
    };
}

pub(crate) use spelled_enum;

spelled_enum! {
    /// A subcommand of a runner that starts a program the workspace chooses.
    RunnerSubcommand {
        /// `run`.
        Run => "run",
        /// `x`.
        X => "x",
        /// `task`.
        Task => "task",
        /// `eval`.
        Eval => "eval",
        /// `repl`.
        Repl => "repl",
        /// `tool`.
        Tool => "tool",
        /// `exec`.
        Exec => "exec",
        /// cabal's `v1-run`.
        V1Run => "v1-run",
        /// cabal's `v2-run`.
        V2Run => "v2-run",
        /// cabal's `new-run`.
        NewRun => "new-run",
        /// cabal's `v1-exec`.
        V1Exec => "v1-exec",
        /// cabal's `v2-exec`.
        V2Exec => "v2-exec",
        /// cabal's `new-exec`.
        NewExec => "new-exec",
        /// stack's `runghc`.
        Runghc => "runghc",
        /// stack's `runhaskell`.
        Runhaskell => "runhaskell",
        /// stack's `script`.
        Script => "script",
        /// cargo's `r` shorthand for `run`.
        R => "r",
        /// cargo's `t` shorthand for `test`.
        T => "t",
        /// `test`, which runs the project's tests.
        Test => "test",
        /// cargo's `bench`.
        Bench => "bench",
        /// stack's `ghci`.
        Ghci => "ghci",
        /// cabal's `v1-repl`.
        V1Repl => "v1-repl",
        /// cabal's `v2-repl`.
        V2Repl => "v2-repl",
        /// cabal's `new-repl`.
        NewRepl => "new-repl",
    }
}

spelled_enum! {
    /// The spelling of a long flag that gives a shell a command string.
    LongCommandName {
        /// `--command`.
        Command => "--command",
        /// `--commands`.
        Commands => "--commands",
        /// `--init-command`, which fish runs as a command string.
        InitCommand => "--init-command",
        /// `--execute`, which nushell runs as a command string.
        Execute => "--execute",
    }
}

spelled_enum! {
    /// A PowerShell parameter that gives it a command, however abbreviated.
    PowerShellParameter {
        /// `-Command`.
        Command => "-Command",
        /// `-CommandWithArgs`.
        CommandWithArgs => "-CommandWithArgs",
        /// `-EncodedCommand`.
        EncodedCommand => "-EncodedCommand",
    }
}

/// The flag that gives a shell a command string, as the shell's family
/// spells it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ShellFlag {
    /// `-c`, alone or inside a cluster such as `-lc`.
    DashC,
    /// `+c`, which POSIX shells read like `-c`.
    PlusC,
    /// fish's `-C`, which runs an init command string.
    DashCapitalC,
    /// nushell's `-e`, which executes a command string.
    DashE,
    /// A long flag such as `--command`.
    LongCommand(LongCommandName),
    /// A PowerShell parameter or an abbreviation or alias of it.
    PowerShell(PowerShellParameter),
}

/// How a [`ShellFlag`] is written on a command line.
enum FlagSpelling {
    /// A prefix character and a letter (`-c`, `+c`).
    Short(char, char),
    /// A whole word (`--command`, `-Command`).
    Word(&'static str),
}

impl ShellFlag {
    const fn spelling(self) -> FlagSpelling {
        match self {
            Self::DashC => FlagSpelling::Short('-', 'c'),
            Self::PlusC => FlagSpelling::Short('+', 'c'),
            Self::DashCapitalC => FlagSpelling::Short('-', 'C'),
            Self::DashE => FlagSpelling::Short('-', 'e'),
            Self::LongCommand(name) => FlagSpelling::Word(name.as_str()),
            Self::PowerShell(parameter) => FlagSpelling::Word(parameter.as_str()),
        }
    }

    /// The prefix character and letter of a short flag, or `None` for a flag
    /// written as a whole word.
    ///
    /// This is the one place a short flag's spelling is written, so a flag
    /// cannot be reported with a prefix the user did not use.
    #[must_use]
    pub(crate) const fn short_spelling(self) -> Option<(char, char)> {
        match self.spelling() {
            FlagSpelling::Short(prefix, letter) => Some((prefix, letter)),
            FlagSpelling::Word(_) => None,
        }
    }
}

impl fmt::Display for ShellFlag {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.spelling() {
            FlagSpelling::Short(prefix, letter) => write!(f, "{prefix}{letter}"),
            FlagSpelling::Word(word) => f.write_str(word),
        }
    }
}

spelled_enum! {
    /// The spelling of a long flag that gives an interpreter a program to run.
    LongInlineFlag {
        /// `--eval`.
        Eval => "--eval",
        /// `--print`.
        Print => "--print",
        /// `--import`, given a `data:` URL.
        Import => "--import",
        /// `--loader`, given a `data:` URL.
        Loader => "--loader",
        /// `--experimental-loader`, given a `data:` URL.
        ExperimentalLoader => "--experimental-loader",
        /// php's `--run`, the long form of `-r`.
        Run => "--run",
        /// php's `--process-begin`, the long form of `-B`.
        ProcessBegin => "--process-begin",
        /// php's `--process-code`, the long form of `-R`.
        ProcessCode => "--process-code",
        /// php's `--process-end`, the long form of `-E`.
        ProcessEnd => "--process-end",
        /// php's `--process-file`, the long form of `-F`.
        ProcessFile => "--process-file",
    }
}

/// The flag that gives an interpreter a program to run inline.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum InlineFlag {
    /// A short flag letter (`-e`, `-c`), alone or inside a cluster.
    Short(char),
    /// A long flag such as `--eval`.
    Long(LongInlineFlag),
}

impl fmt::Display for InlineFlag {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Short(letter) => write!(f, "-{letter}"),
            Self::Long(flag) => f.write_str(flag.as_str()),
        }
    }
}

/// A positional operand a wrapper takes before the command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum OperandKind {
    /// `timeout`'s `DURATION`.
    Duration,
}

impl fmt::Display for OperandKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Duration => "DURATION",
        })
    }
}

/// Why a shell or interpreter would read its program from standard input,
/// which carries the LSP frames mcpls writes to the server.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum StdinSource {
    /// No script, module or other program source is given.
    NoProgram,
    /// `-s`, alone or inside a cluster.
    DashS,
    /// The script operand is `-`.
    DashOperand,
    /// The script operand lies under `/dev/` or `/proc/`, where a path can
    /// name the process's standard input.
    DeviceOperand,
    /// The script operand has a `..` component, which can reach a device path.
    ParentTraversal,
    /// The script operand resolves, where the server starts, to a device,
    /// FIFO or socket, so it may be an alias of a device path.
    SpecialFile,
}

impl fmt::Display for StdinSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::NoProgram => "no script is given, so it reads its program from standard input",
            Self::DashS => "`-s` makes it read its program from standard input",
            Self::DashOperand => "a `-` operand makes it read its program from standard input",
            Self::DeviceOperand => {
                "its script is under /dev or /proc, where a path can name standard input"
            }
            Self::ParentTraversal => "its script path has a `..` component, which can reach /dev",
            Self::SpecialFile => {
                "its script is a device, FIFO or socket, which may be an alias of standard input"
            }
        })
    }
}

/// What about a launcher lets the workspace choose the program that runs.
///
/// The values are matched from closed tables, never from configured text.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum LaunchTrigger {
    /// Every use of the program does (a package or task runner, or a wrapper
    /// whose options are not analyzed).
    Always,
    /// This subcommand does.
    Subcommand(RunnerSubcommand),
    /// This flag gives it a command string.
    CommandString(ShellFlag),
    /// A bare argument is read as its command string (Windows PowerShell).
    ImplicitCommandString,
    /// This flag gives an interpreter a program to run inline.
    InlineProgram(InlineFlag),
    /// An argument names an npm package to run (`npm:`).
    NpmSpecifier,
    /// It reads its program from standard input, which carries LSP frames.
    ProgramFromStdin(StdinSource),
}

impl fmt::Display for LaunchTrigger {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Always => f.write_str("every use of it does"),
            Self::Subcommand(name) => write!(f, "its `{name}` subcommand does"),
            Self::CommandString(flag) => {
                write!(
                    f,
                    "`{flag}` gives it a command string, which cannot be analyzed"
                )
            }
            Self::ImplicitCommandString => f.write_str(
                "it reads a bare argument as a command string, which cannot be analyzed",
            ),
            Self::InlineProgram(flag) => write!(f, "`{flag}` gives it a program to run"),
            Self::NpmSpecifier => f.write_str("an `npm:` argument names a package to run"),
            Self::ProgramFromStdin(source) => write!(f, "{source}"),
        }
    }
}

/// Why a launch cannot be analyzed, so untrusted mode cannot tell which
/// program it starts.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum UnanalyzableLaunch {
    /// The wrapper has an option its option table does not list.
    UnknownOption(EchoedArgument),
    /// A listed option that takes a value is the last argument.
    MissingValue(EchoedArgument),
    /// No command follows the wrapper's options.
    MissingCommand,
    /// A positional operand before the command is not of the expected shape.
    MalformedOperand(OperandKind),
    /// `PATH` is assigned, which bypasses the sanitized search path.
    PathAssignment,
    /// A string is split into arguments (`env -S`).
    SplitString,
    /// A relative program follows a directory change.
    RelativeProgramAfterChdir,
    /// A relative script operand follows a directory change.
    RelativeOperandAfterChdir,
    /// The program name is empty.
    BlankProgram,
}

impl fmt::Display for UnanalyzableLaunch {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnknownOption(option) => write!(f, "unknown option '{option}'"),
            Self::MissingValue(option) => write!(f, "option '{option}' has no value"),
            Self::MissingCommand => f.write_str("no command follows its options"),
            Self::MalformedOperand(name) => write!(f, "its {name} operand is malformed"),
            Self::PathAssignment => f.write_str("it assigns PATH"),
            Self::SplitString => f.write_str("it splits a string into arguments"),
            Self::RelativeProgramAfterChdir => {
                f.write_str("it starts a relative program after changing directory")
            }
            Self::RelativeOperandAfterChdir => {
                f.write_str("it reads a relative script after changing directory")
            }
            Self::BlankProgram => f.write_str("the program name is empty"),
        }
    }
}

/// Why a launcher lets the workspace choose the program that runs.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum LauncherRefusal {
    /// A launcher selects workspace code.
    SelectsWorkspaceCode {
        /// The launcher's name.
        program: EchoedPath,
        /// What about it does.
        trigger: LaunchTrigger,
    },
    /// The launch cannot be analyzed, which untrusted mode treats as unsafe.
    Unanalyzable {
        /// The launcher's name.
        program: EchoedPath,
        /// Why it cannot be analyzed.
        reason: UnanalyzableLaunch,
    },
    /// Wrappers are nested deeper than the analysis follows.
    TooDeep,
}

impl fmt::Display for LauncherRefusal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::SelectsWorkspaceCode { program, trigger } => write!(
                f,
                "its launcher '{program}' chooses the server from files in the workspace \
                 ({trigger}), which untrusted mode never runs; install the server globally \
                 and give its absolute path as `command`"
            ),
            Self::Unanalyzable { program, reason } => write!(
                f,
                "its launcher '{program}' cannot be analyzed ({reason}), so untrusted mode \
                 cannot tell which program it starts; give the absolute path of the server \
                 as `command`"
            ),
            Self::TooDeep => f.write_str(
                "its launchers are nested too deeply to analyze, so untrusted mode cannot \
                 tell which program they start; give the absolute path of the server as \
                 `command`",
            ),
        }
    }
}

/// Why untrusted-workspace mode refused to start a server.
///
/// # Examples
///
/// ```
/// use mcpls_core::config::BuiltinServer;
/// use mcpls_core::error::UntrustedRefusal;
///
/// let refusal = UntrustedRefusal::NotAllowed {
///     builtin: Some(BuiltinServer::RustAnalyzer),
/// };
/// assert!(refusal.to_string().contains("Cargo build scripts"));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum UntrustedRefusal {
    /// The server was not named with `--allow-server`.
    NotAllowed {
        /// The built-in server this is, whose workspace-code class is named
        /// in the message; `None` for a custom server.
        builtin: Option<BuiltinServer>,
    },
    /// The server's executable lies inside the workspace. Naming the server
    /// does not consent to running a binary the workspace supplies.
    WorkspaceExecutable {
        /// The canonical path of the executable.
        executable: PathBuf,
    },
    /// The executable was not found on a search path outside the workspace,
    /// so untrusted mode cannot tell what would run.
    UnresolvedExecutable {
        /// The configured `command`.
        command: ServerCommand,
    },
    /// The auto-selected TypeScript command resolved to an executable that is
    /// not typescript-language-server (a `PATH` entry symlinked to another
    /// program), so it cannot be hardened without dropping the tsserver pin.
    AutoSelectionTarget {
        /// The resolved executable the command would have been replaced with.
        executable: ServerCommand,
        /// Why the selection cannot follow the resolved executable.
        cause: InvalidAutoSelection,
    },
    /// The login home directory is unknown and the inherited `HOME` lies
    /// inside the workspace, where rustup, cargo and npm would read their
    /// configuration from.
    WorkspaceHome {
        /// The variable that names the home directory.
        variable: HomeVariable,
        /// The path the server would inherit, inside the workspace.
        home: PathBuf,
    },
    /// The login home directory is unknown and a home variable is empty, so
    /// tools resolve it against the working directory, which is the checkout.
    EmptyHome {
        /// The variable that is empty.
        variable: HomeVariable,
    },
    /// The login home directory is unknown and `HOME` is not set, so tools
    /// would resolve `~` against the working directory, which is the
    /// checkout.
    UnknownHome,
    /// The tsserver the TypeScript server would use lies inside the
    /// workspace.
    WorkspaceTsserver {
        /// The canonical path of the tsserver.
        tsserver: PathBuf,
    },
    /// The configured command is a launcher that chooses the server from
    /// files in the workspace (a package runner, task runner or toolchain
    /// wrapper), so what would run is under the workspace's control.
    ProjectLauncher {
        /// The configured `command`.
        command: ServerCommand,
        /// What about the launch the analysis refused.
        cause: LauncherRefusal,
    },
    /// An argument of the configured command names an executable file inside
    /// the workspace, which whatever launcher precedes it would start.
    WorkspaceExecutableArgument {
        /// The position of the argument in the configured `args`.
        index: usize,
        /// The canonical path of the executable.
        executable: PathBuf,
    },
    /// An argument of the configured command lies inside the workspace and
    /// cannot be read, so untrusted mode cannot tell whether it is an
    /// executable.
    UnreadableWorkspaceArgument {
        /// The position of the argument in the configured `args`.
        index: usize,
        /// The path the argument names, lexically normalized.
        path: PathBuf,
    },
    /// A program an exec wrapper or `env` starts was not found on a search
    /// path outside the workspace, so untrusted mode cannot tell what would
    /// run.
    UnresolvedWrappedProgram {
        /// The wrapped program, as configured.
        program: EchoedPath,
    },
    /// The vetted path of a program that `env` starts contains `=`, which
    /// `env` would read as an assignment, so it cannot be passed on unchanged.
    WrappedProgramPathContainsEquals {
        /// The wrapped program, as configured.
        program: EchoedPath,
    },
    /// The configured command starts the TypeScript server through a launcher
    /// that untrusted mode cannot pin to a binary outside the workspace.
    UnpinnedTypescriptLauncher {
        /// The configured `command`.
        command: ServerCommand,
    },
    /// A resolved path is not valid UTF-8, so untrusted mode cannot pass it
    /// on unchanged.
    NonUtf8Path {
        /// What the path belongs to.
        what: ResolvedItem,
        /// The path, as resolved.
        path: PathBuf,
    },
    /// A resolved path is blank, so there is nothing to start.
    BlankResolvedPath {
        /// What the path belongs to.
        what: ResolvedItem,
    },
    /// A resolved path contains a NUL, which the operating system cannot pass
    /// in a path or environment variable.
    NulInResolvedPath {
        /// What the path belongs to.
        what: ResolvedItem,
    },
    /// No directory outside the workspace is available for the server to
    /// start in.
    NoSafeWorkingDirectory,
    /// The variables untrusted mode sets for the server do not fit in its
    /// `env` table.
    EnvTooLarge {
        /// Which limit the table would be over.
        error: EnvTooLarge,
    },
}

impl fmt::Display for UntrustedRefusal {
    #[allow(
        clippy::too_many_lines,
        reason = "one message per refusal, and the refusals are the table"
    )]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotAllowed {
                builtin: Some(builtin),
            } => write!(
                f,
                "the workspace is untrusted and it may run workspace code ({})",
                builtin.workspace_code()
            ),
            Self::NotAllowed { builtin: None } => f.write_str(
                "the workspace is untrusted and it is not a built-in server, so the workspace \
                 code it may run is unknown",
            ),
            Self::WorkspaceExecutable { executable } => write!(
                f,
                "its executable {} lies inside the workspace, which untrusted mode never runs",
                EchoedPath::new(executable)
            ),
            Self::WorkspaceExecutableArgument { index, executable } => write!(
                f,
                "its argument at index {index}, {}, is an executable inside the workspace, \
                 which untrusted mode never runs",
                EchoedPath::new(executable)
            ),
            Self::UnreadableWorkspaceArgument { index, path } => write!(
                f,
                "its argument at index {index}, {}, lies inside the workspace and cannot be \
                 read, so untrusted mode cannot tell whether it is an executable",
                EchoedPath::new(path)
            ),
            Self::UnresolvedExecutable { command } => write!(
                f,
                "its executable '{command}' was not found on a PATH outside the workspace, \
                 which untrusted mode requires"
            ),
            Self::AutoSelectionTarget { executable, cause } => write!(
                f,
                "its executable resolved to '{executable}' ({cause}), so untrusted mode \
                 cannot pin it; give the absolute path of the server as `command`"
            ),
            Self::UnknownHome => f.write_str(
                "HOME is not set and the login home directory is unknown, so untrusted mode \
                 cannot give it a safe one",
            ),
            Self::EmptyHome { variable } => write!(
                f,
                "its {variable} is empty, which resolves inside the workspace, and the login \
                 home directory is unknown, so untrusted mode cannot give it a safe one"
            ),
            Self::WorkspaceHome { variable, home } => write!(
                f,
                "its {variable}, {}, lies inside the workspace and the login home directory is \
                 unknown, so untrusted mode cannot give it a safe one",
                EchoedPath::new(home)
            ),
            Self::WorkspaceTsserver { tsserver } => write!(
                f,
                "the tsserver it would use, {}, lies inside the workspace, which untrusted \
                 mode never runs",
                EchoedPath::new(tsserver)
            ),
            Self::ProjectLauncher { cause, .. } => cause.fmt(f),
            Self::UnresolvedWrappedProgram { program } => write!(
                f,
                "the program '{program}' its launcher starts was not found where the child \
                 would look it up, which untrusted mode requires"
            ),
            Self::WrappedProgramPathContainsEquals { program } => write!(
                f,
                "the program '{program}' its launcher starts resolves to a path containing \
                 '=', which env reads as an assignment, so untrusted mode cannot pin it; give \
                 a program whose path has no '='"
            ),
            Self::UnpinnedTypescriptLauncher { command } => write!(
                f,
                "its launcher '{command}' starts the TypeScript server in a way untrusted \
                 mode cannot pin to a binary outside the workspace; install the server \
                 globally and give its absolute path as `command`"
            ),
            Self::NonUtf8Path { what, path } => write!(
                f,
                "its {what}, {}, is not valid UTF-8, so untrusted mode cannot pass it on",
                EchoedPath::new(path)
            ),
            Self::BlankResolvedPath { what } => write!(
                f,
                "its {what} resolved to a blank path, which cannot be started"
            ),
            Self::NulInResolvedPath { what } => {
                write!(
                    f,
                    "its {what} resolved to a path containing NUL, which cannot be passed on"
                )
            }
            Self::NoSafeWorkingDirectory => f.write_str(
                "no directory outside the workspace is available to start it in, which \
                 untrusted mode requires",
            ),
            Self::EnvTooLarge { error } => write!(
                f,
                "the variables untrusted mode sets do not fit in its environment: {error}"
            ),
        }
    }
}

impl fmt::Display for StartupFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Spawn(error) => ErrorChain(error.as_ref()).fmt(f),
            Self::InitTaskPanicked => {
                f.write_str("the initialization task panicked (see the mcpls log)")
            }
            Self::RefusedUntrustedWorkspace(refusal) => refusal.fmt(f),
        }
    }
}

/// Details of a single server spawn failure.
#[derive(Debug, Clone)]
pub struct ServerSpawnFailure {
    /// Routing identity of the failed server.
    pub server_id: ServerId,
    /// Language ID of the failed server.
    pub language_id: LanguageId,
    /// Command that was attempted.
    pub command: ServerCommand,
    /// Why the server never registered.
    pub reason: StartupFailure,
}

impl fmt::Display for ServerSpawnFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} [{}] ({}): {}",
            self.server_id, self.language_id, self.command, self.reason
        )
    }
}

impl ServerSpawnFailure {
    /// The caller-facing text of [`Error::ServerFailedToStart`]. A refusal
    /// was a decision, not a failure, so it names the remedy instead of the
    /// startup-failure tail.
    pub(crate) const fn failed_to_start(&self) -> FailedToStart<'_> {
        FailedToStart(self)
    }
}

/// `Display` adapter for [`ServerSpawnFailure::failed_to_start`].
pub(crate) struct FailedToStart<'a>(&'a ServerSpawnFailure);

impl fmt::Display for FailedToStart<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let failure = self.0;
        let (id, language) = (&failure.server_id, &failure.language_id);
        match &failure.reason {
            StartupFailure::RefusedUntrustedWorkspace(refusal) => {
                write!(
                    f,
                    "LSP server '{id}' for language '{language}' was not started: {refusal}"
                )?;
                match refusal {
                    UntrustedRefusal::NotAllowed { .. } => {
                        write!(f, "; restart mcpls with `--allow-server {id}` to start it")
                    }
                    UntrustedRefusal::WorkspaceExecutable { .. }
                    | UntrustedRefusal::WorkspaceExecutableArgument { .. }
                    | UntrustedRefusal::UnreadableWorkspaceArgument { .. }
                    | UntrustedRefusal::UnresolvedExecutable { .. }
                    | UntrustedRefusal::AutoSelectionTarget { .. }
                    | UntrustedRefusal::WorkspaceHome { .. }
                    | UntrustedRefusal::EmptyHome { .. }
                    | UntrustedRefusal::UnknownHome
                    | UntrustedRefusal::WorkspaceTsserver { .. }
                    | UntrustedRefusal::ProjectLauncher { .. }
                    | UntrustedRefusal::UnresolvedWrappedProgram { .. }
                    | UntrustedRefusal::WrappedProgramPathContainsEquals { .. }
                    | UntrustedRefusal::UnpinnedTypescriptLauncher { .. }
                    | UntrustedRefusal::NonUtf8Path { .. }
                    | UntrustedRefusal::BlankResolvedPath { .. }
                    | UntrustedRefusal::NulInResolvedPath { .. }
                    | UntrustedRefusal::NoSafeWorkingDirectory
                    | UntrustedRefusal::EnvTooLarge { .. } => Ok(()),
                }
            }
            reason @ (StartupFailure::Spawn(_) | StartupFailure::InitTaskPanicked) => write!(
                f,
                "LSP server '{id}' for language '{language}' failed to start: {reason}; restart \
                 mcpls after fixing it (startup failures are not retried)"
            ),
        }
    }
}

/// `Display` adapter listing every failure, separated by `; `.
struct FailureList<'a>(&'a [ServerSpawnFailure]);

impl fmt::Display for FailureList<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (index, failure) in self.0.iter().enumerate() {
            if index > 0 {
                f.write_str("; ")?;
            }
            failure.fmt(f)?;
        }
        Ok(())
    }
}

/// Maximum candidates named in the `Display` text of an ambiguity error;
/// the structured payload carries all of them.
const MAX_DISPLAYED_CANDIDATES: usize = 10;

/// One symbol a name resolved to, with enough context to tell it apart from
/// its namesakes and to address it by position instead.
///
/// # Examples
///
/// ```
/// use mcpls_core::error::SymbolCandidate;
///
/// let candidate = SymbolCandidate {
///     name: "new".to_string(),
///     kind: 6,
///     kind_name: "Method".to_string(),
///     container: Some("Config".to_string()),
///     line: 12,
///     character: 8,
/// };
/// assert_eq!(candidate.to_string(), "Method `new` in `Config` at 12:8");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SymbolCandidate {
    /// The symbol's name as the server reports it.
    pub name: String,
    /// Numeric LSP `SymbolKind`.
    pub kind: u32,
    /// Readable name of [`Self::kind`].
    pub kind_name: String,
    /// Enclosing symbol, when the server reports one.
    pub container: Option<String>,
    /// 1-based line of the identifier.
    pub line: u32,
    /// 1-based character of the identifier.
    pub character: u32,
}

impl fmt::Display for SymbolCandidate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} `{}`", self.kind_name, self.name)?;
        if let Some(container) = &self.container {
            write!(f, " in `{container}`")?;
        }
        write!(f, " at {}:{}", self.line, self.character)
    }
}

/// Why a symbol name could not be resolved to exactly one position.
///
/// Carried as the structured `data` of the `INVALID_PARAMS` error, tagged by
/// `resolution`.
///
/// # Examples
///
/// ```
/// use mcpls_core::error::SymbolResolutionData;
///
/// let missing = SymbolResolutionData::NotDefinedInFile { name: "Config".to_string() };
/// assert_eq!(
///     serde_json::to_value(&missing).unwrap(),
///     serde_json::json!({"resolution": "not_defined_in_file", "name": "Config"})
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "resolution", rename_all = "snake_case")]
pub enum SymbolResolutionData {
    /// The name matches several symbols; nothing was picked.
    Ambiguous {
        /// The requested name.
        name: String,
        /// The matching symbols, capped.
        candidates: Vec<SymbolCandidate>,
        /// More symbols match than `candidates` lists.
        truncated: bool,
    },
    /// No symbol of that name (and kind/container) is defined in the file.
    NotFound {
        /// The requested name.
        name: String,
        /// Symbols of that name excluded by the kind or container filter.
        excluded_by_filters: usize,
    },
    /// The name occurs in the file but no symbol defines it there (an import
    /// or a plain reference).
    NotDefinedInFile {
        /// The requested name.
        name: String,
    },
    /// A symbol matched but its identifier position could not be verified
    /// against the document text, so no query was made.
    PositionUnverified {
        /// The requested name.
        name: String,
        /// The symbol that matched.
        candidate: SymbolCandidate,
    },
}

impl fmt::Display for SymbolResolutionData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Ambiguous {
                name,
                candidates,
                truncated,
            } => {
                write!(
                    f,
                    "symbol `{name}` is ambiguous ({} candidates{}): ",
                    candidates.len(),
                    if *truncated { ", more not listed" } else { "" }
                )?;
                for (index, candidate) in
                    candidates.iter().take(MAX_DISPLAYED_CANDIDATES).enumerate()
                {
                    if index > 0 {
                        f.write_str("; ")?;
                    }
                    candidate.fmt(f)?;
                }
                if candidates.len() > MAX_DISPLAYED_CANDIDATES {
                    f.write_str("; ...")?;
                }
                f.write_str(
                    ". Narrow it with `symbol_kind` or `container`, or address it by line and character",
                )
            }
            Self::NotFound {
                name,
                excluded_by_filters,
            } => {
                write!(f, "no symbol named `{name}` is defined in this file")?;
                if *excluded_by_filters > 0 {
                    write!(
                        f,
                        " ({excluded_by_filters} with that name excluded by `symbol_kind`/`container`)"
                    )?;
                }
                f.write_str("; try `workspace_symbol_search` or address it by line and character")
            }
            Self::NotDefinedInFile { name } => write!(
                f,
                "`{name}` is not defined in this file (it only occurs as a reference or import); \
                 find its definition with `workspace_symbol_search` or address it by line and character"
            ),
            Self::PositionUnverified { name, candidate } => write!(
                f,
                "could not verify where the identifier `{name}` is ({candidate}), so nothing was \
                 queried; address it by line and character"
            ),
        }
    }
}

/// `Display` adapter listing server ids, separated by `, `.
struct IdList<'a>(&'a [ServerId]);

impl fmt::Display for IdList<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (index, id) in self.0.iter().enumerate() {
            if index > 0 {
                f.write_str(", ")?;
            }
            write!(f, "'{id}'")?;
        }
        Ok(())
    }
}

/// What a failed server startup wrote to stderr, bounded and sanitized.
///
/// Holds the first and last bytes of the output (or all of it when short), so
/// both the opening banner and the final error survive.
///
/// # Sanitizing
///
/// Control characters other than newline and tab are dropped, as are
/// characters that forge or reorder text in logs and terminals: the Unicode
/// line and paragraph separators, bidirectional controls and zero-width
/// characters.
///
/// # Redaction
///
/// Values that look secret are replaced with `[redacted:NAME]` before the text
/// leaves mcpls. A value counts as secret (and must be at least 8 bytes) when
/// it is:
/// - an environment variable value, from the server's configured `env` or
///   mcpls's own environment, whose name contains `TOKEN`, `KEY`, `SECRET`,
///   `PASSW`, `CRED` or `AUTH` (case-insensitive);
/// - the value of a `--flag=value` or `--flag value` argument whose flag name
///   matches the same patterns;
/// - a string under a matching key of `initialization_options`.
///
/// Other values, such as `RUSTUP_TOOLCHAIN`, stay visible so the cause of a
/// failure can still be read. Matching is by exact value: encoded forms (URL,
/// base64, JSON-escaped) are not found. A secret cut by the head/tail elision
/// is hidden only for the fragment of at least 4 bytes on either side of the
/// cut. Put secrets in a name-matching `env` entry rather than in other
/// places.
///
/// `Display` renders one line: trimmed non-empty lines joined with ` | `,
/// with `...` between head and tail when elided. The raw multi-line text is
/// available through [`Self::head`] and [`Self::tail`].
///
/// # Examples
///
/// ```
/// use mcpls_core::Error;
/// use mcpls_core::error::InitPhase;
///
/// fn server_output(err: &Error) -> Option<String> {
///     match err {
///         Error::LspInitFailed { stderr: Some(stderr), .. }
///         | Error::ServerExitedDuringInit { stderr: Some(stderr), .. } => {
///             Some(stderr.to_string())
///         }
///         _ => None,
///     }
/// }
///
/// let err = Error::LspInitFailed {
///     phase: InitPhase::Initialize,
///     cause: Box::new(Error::ServerTerminated),
///     hint: None,
///     stderr: None,
/// };
/// assert_eq!(server_output(&err), None);
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StderrExcerpt {
    body: ExcerptBody,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum ExcerptBody {
    Complete(Box<str>),
    Elided { head: Box<str>, tail: Box<str> },
}

impl StderrExcerpt {
    /// Excerpt of output that fit entirely in the capture buffer; `None` when
    /// it holds no visible text.
    pub(crate) fn complete(bytes: &[u8], redactions: &Redactions) -> Option<Self> {
        let text = clean_stderr(&String::from_utf8_lossy(bytes), redactions);
        (!text.is_empty()).then(|| Self {
            body: ExcerptBody::Complete(text.into()),
        })
    }

    /// Excerpt of output whose middle was dropped. The cut can split a UTF-8
    /// sequence at the end of `head` and at the start of `tail`; both partial
    /// sequences are discarded rather than shown as replacement characters.
    /// A secret split by the cut is masked as far as `redactions` allows.
    pub(crate) fn elided(head: &[u8], tail: &[u8], redactions: &Redactions) -> Option<Self> {
        let head = clean_stderr(
            &redactions.mask_cut_head(&decode_cut_head(head)),
            redactions,
        );
        let tail_start = tail
            .iter()
            .position(|byte| byte & 0xC0 != 0x80)
            .unwrap_or(tail.len());
        let tail = clean_stderr(
            &redactions.mask_cut_tail(&String::from_utf8_lossy(
                tail.get(tail_start..).unwrap_or_default(),
            )),
            redactions,
        );
        match (head.is_empty(), tail.is_empty()) {
            (true, true) => None,
            (false, true) => Some(Self {
                body: ExcerptBody::Complete(head.into()),
            }),
            (true, false) => Some(Self {
                body: ExcerptBody::Complete(tail.into()),
            }),
            (false, false) => Some(Self {
                body: ExcerptBody::Elided {
                    head: head.into(),
                    tail: tail.into(),
                },
            }),
        }
    }

    /// The start of the output, or all of it when nothing was dropped.
    #[must_use]
    pub fn head(&self) -> &str {
        match &self.body {
            ExcerptBody::Complete(text) => text,
            ExcerptBody::Elided { head, .. } => head,
        }
    }

    /// The end of the output, present only when the middle was dropped.
    #[must_use]
    pub fn tail(&self) -> Option<&str> {
        match &self.body {
            ExcerptBody::Complete(_) => None,
            ExcerptBody::Elided { tail, .. } => Some(tail),
        }
    }

    /// Whether the middle of the output was dropped.
    #[must_use]
    pub const fn is_elided(&self) -> bool {
        matches!(self.body, ExcerptBody::Elided { .. })
    }
}

impl fmt::Display for StderrExcerpt {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fn visible_lines(text: &str) -> impl Iterator<Item = &str> {
            text.lines().map(str::trim).filter(|line| !line.is_empty())
        }

        let mut parts: Vec<&str> = visible_lines(self.head()).collect();
        if let Some(tail) = self.tail() {
            parts.push("...");
            parts.extend(visible_lines(tail));
        }
        f.write_str(&parts.join(" | "))
    }
}

/// Decodes `head`, dropping a UTF-8 sequence cut off at its end.
fn decode_cut_head(head: &[u8]) -> String {
    match std::str::from_utf8(head) {
        Ok(text) => text.to_owned(),
        Err(e) if e.error_len().is_none() => {
            String::from_utf8_lossy(head.get(..e.valid_up_to()).unwrap_or_default()).into_owned()
        }
        Err(_) => String::from_utf8_lossy(head).into_owned(),
    }
}

/// Redacts secrets, drops control and deceptive format characters (other than
/// `\n`/`\t`: they could forge log lines or drive a terminal) and trims.
/// Redaction runs before and after the filter so a dropped character cannot
/// split a secret into a form that escapes it.
fn clean_stderr(text: &str, redactions: &Redactions) -> String {
    let filtered: String = redactions
        .apply(text)
        .chars()
        .filter(|c| {
            (!c.is_control() || matches!(c, '\n' | '\t'))
                && !crate::util::is_deceptive_format_char(*c)
        })
        .collect();
    redactions.apply(&filtered).trim().to_owned()
}

/// `Display` suffix appending a server's stderr excerpt to a startup error.
struct StderrSuffix<'a>(&'a Option<StderrExcerpt>);

impl fmt::Display for StderrSuffix<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0
            .as_ref()
            .map_or(Ok(()), |excerpt| write!(f, "; stderr: {excerpt}"))
    }
}

/// Guidance attached to an `initialize` failure whose likely cause is known.
///
/// # Examples
///
/// ```
/// use mcpls_core::error::InitFailureHint;
///
/// let text = InitFailureHint::NativeTypescriptOnly.to_string();
/// assert!(text.contains("TypeScript 7"));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum InitFailureHint {
    /// typescript-language-server found only TypeScript 7 or later, which
    /// ships no `tsserver` for it to start.
    NativeTypescriptOnly,
}

impl fmt::Display for InitFailureHint {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NativeTypescriptOnly => write!(
                f,
                "typescript-language-server found only TypeScript 7 or later, which ships no \
                 tsserver; install the TypeScript version the server supports next to it (for a \
                 global install: `{}`), or change the `command` of your existing `typescript` \
                 server entry to the absolute path of the `tsc` of a TypeScript 7 install \
                 outside the workspace, with `args = [\"--lsp\", \"--stdio\"]` (a `tsc` from the \
                 workspace, or a bare `tsc` that PATH may resolve into the workspace, is \
                 workspace-supplied code)",
                BuiltinServer::TypescriptLanguageServer.install_hint()
            ),
        }
    }
}

/// `Display` suffix appending an [`InitFailureHint`] to a startup error.
struct HintSuffix<'a>(&'a Option<InitFailureHint>);

impl fmt::Display for HintSuffix<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.map_or(Ok(()), |hint| write!(f, "; {hint}"))
    }
}

/// `Display` suffix for [`Error::ServerExitedDuringInit`] carrying the exit
/// status and, for builtin servers with a known early-exit cause, a hint.
struct EarlyExitDetail<'a>(&'a str, Option<i32>);

impl fmt::Display for EarlyExitDetail<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let Self(command, exit_code) = *self;
        match exit_code {
            Some(code) => write!(f, " with exit code {code}")?,
            None => f.write_str(" (terminated by a signal)")?,
        }
        BuiltinServer::from_command(command)
            .and_then(BuiltinServer::early_exit_hint)
            .map_or(Ok(()), |hint| write!(f, "; {hint}"))
    }
}

/// A background task whose failure surfaces as [`Error::TaskFailed`] or is
/// reported by its supervisor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum BackgroundTask {
    /// The MCP service loop that serves one client connection.
    McpService,
    /// The task that reads an LSP server's messages.
    LspReceiver,
    /// The blocking resolution of `subscriptions/listen` URIs.
    ListenResolution,
    /// The blocking canonicalization of a client path.
    PathValidation,
    /// Opening and verifying a file on the blocking pool.
    FileOpen,
    /// Planning which configured servers to start, on the blocking pool.
    ServerPlanning,
    /// The reaper that expires idle HTTP sessions.
    IdleSessionReaper,
}

impl fmt::Display for BackgroundTask {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::McpService => "MCP service",
            Self::LspReceiver => "LSP receiver",
            Self::ListenResolution => "listen URI resolution",
            Self::PathValidation => "path validation",
            Self::FileOpen => "file open",
            Self::ServerPlanning => "server start planning",
            Self::IdleSessionReaper => "idle HTTP session reaper",
        })
    }
}

/// A standard stream of a spawned LSP server process.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum StdioStream {
    /// Standard input.
    Stdin,
    /// Standard output.
    Stdout,
    /// Standard error.
    Stderr,
}

impl fmt::Display for StdioStream {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Stdin => "stdin",
            Self::Stdout => "stdout",
            Self::Stderr => "stderr",
        })
    }
}

/// A configuration value that is invalid in the context of the entry that holds it.
///
/// Field-level rules live in the types of the fields (a rejected value cannot be
/// built); this enum carries what only the surrounding entry or the whole
/// configuration can add, such as which server a bad value belongs to.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ConfigError {
    /// A server entry lists a `file_patterns` form that maps to no extension.
    #[error("lsp_servers entry '{server}'")]
    UnsupportedFilePattern {
        /// The id of the entry that holds the pattern.
        server: ServerId,
        /// The rejected pattern and the supported forms.
        #[source]
        pattern: UnsupportedFilePattern,
    },

    /// The config file's bytes are not UTF-8.
    #[error("config file is not valid UTF-8")]
    NotUtf8(#[source] std::string::FromUtf8Error),

    /// The config file is over its fixed size limit, which is not configurable.
    #[error("config file is {} bytes, over the fixed {} byte limit", .0.size, .0.max)]
    FileTooLarge(SizeExceeded),

    /// A server's `env` table sets one variable twice, which the host treats as
    /// one name.
    #[error("lsp_servers entry '{server}'")]
    DuplicateEnvKey {
        /// The id of the entry that holds the table.
        server: ServerId,
        /// The colliding keys.
        #[source]
        error: DuplicateEnvKey,
    },

    /// A server's `env` table holds a value the operating system cannot pass.
    #[error("lsp_servers entry '{server}': environment variable '{key}'")]
    InvalidEnvValue {
        /// The id of the entry that holds the table.
        server: ServerId,
        /// The variable whose value is invalid.
        key: EnvKey,
        /// Why the value is invalid.
        #[source]
        error: InvalidEnvValue,
    },

    /// A server's `env` table is too large to pass to a process.
    #[error("lsp_servers entry '{server}'")]
    EnvTooLarge {
        /// The id of the entry that holds the table.
        server: ServerId,
        /// Which size limit the table is over.
        #[source]
        error: EnvTooLarge,
    },

    /// An entry of a server's `args` holds a NUL, which the operating system
    /// cannot pass in an argument.
    #[error("lsp_servers entry '{server}'")]
    ArgContainsNul {
        /// The id of the entry that holds the argument.
        server: ServerId,
        /// Which argument holds the NUL.
        #[source]
        error: InvalidServerArgs,
    },

    /// A config path has no directory to resolve relative entries against.
    #[error("configuration path has no parent directory: {}", .path.display())]
    NoParentDirectory {
        /// The config path.
        path: PathBuf,
    },

    /// `selection = "auto"` on an entry that is not typescript-language-server.
    #[error(
        "selection = \"auto\" is only valid for typescript-language-server entries (language \
         '{language}'); remove `selection` to use `command` as written"
    )]
    SelectionAutoOnNonTypescript {
        /// The language of the offending entry.
        language: LanguageId,
    },

    /// An allowed server id names no configured server.
    #[error(
        "allowed server '{server}' is not a configured server (configured: {})",
        IdList(configured)
    )]
    UnknownAllowedServer {
        /// The allowed id that matches nothing.
        server: ServerId,
        /// The ids of the configured servers.
        configured: Vec<ServerId>,
    },

    /// Two applicable entries share one server id.
    #[error(
        "duplicate server id '{id}' in this workspace (used by both an entry with {first} and \
         one with {second}); add a unique `name` to each `[[lsp_servers]]` entry"
    )]
    DuplicateServerId {
        /// The shared id.
        id: ServerId,
        /// The first entry.
        first: Box<EntrySummary>,
        /// The second entry.
        second: Box<EntrySummary>,
    },

    /// A language has two servers that both omit `handles`.
    #[error(
        "language '{language}' has two catch-all servers ('{existing}' and '{id}'); at most one \
         server per language may omit `handles`"
    )]
    TwoCatchAllServers {
        /// The language both serve.
        language: LanguageId,
        /// The server registered first.
        existing: ServerId,
        /// The server that collides with it.
        id: ServerId,
    },

    /// Two servers of one language claim the same tool in `handles`.
    #[error("tool '{tool}' for language '{language}' is claimed by both '{existing}' and '{id}'")]
    ToolClaimedTwice {
        /// The contested tool.
        tool: ToolKind,
        /// The language both serve.
        language: LanguageId,
        /// The server registered first.
        existing: ServerId,
        /// The server that collides with it.
        id: ServerId,
    },

    /// A configured workspace root cannot be canonicalized.
    #[error(
        "workspace root '{}' resolved relative to '{}' as '{}' could not be canonicalized",
        .written.display(), .base_dir.display(), .probe.display()
    )]
    UnresolvableWorkspaceRoot {
        /// The root as written in the config.
        written: PathBuf,
        /// The directory a relative root is resolved against.
        base_dir: PathBuf,
        /// The path that was canonicalized.
        probe: PathBuf,
        /// Why canonicalization failed.
        #[source]
        source: std::io::Error,
    },
}

/// A step of the LSP initialization handshake.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum InitPhase {
    /// The `initialize` request.
    Initialize,
    /// The `initialized` notification.
    Initialized,
    /// The `workspace/didChangeConfiguration` notification.
    DidChangeConfiguration,
}

impl fmt::Display for InitPhase {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Initialize => "Initialize request failed",
            Self::Initialized => "initialized notification failed",
            Self::DidChangeConfiguration => "workspace/didChangeConfiguration notification failed",
        })
    }
}

/// The main error type for mcpls-core operations.
///
/// This enum is `#[non_exhaustive]`: downstream crates that match on it must
/// include a wildcard arm. New variants (such as [`Error::ServerInitializing`])
/// can then be added without further breaking changes.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// LSP server failed to initialize.
    #[error("LSP server initialization failed: {phase}: {}{}{}", ErrorChain(.cause.as_ref()), HintSuffix(.hint), StderrSuffix(.stderr))]
    LspInitFailed {
        /// The handshake step that failed.
        phase: InitPhase,
        /// Why the step failed, so a timeout and a rejection by the server
        /// stay distinguishable. Rendered by `Display` through
        /// [`ErrorChain`] instead of being exposed through `source()`, so the
        /// chain is not printed twice.
        cause: Box<Self>,
        /// The likely cause and remedy, when one is known.
        hint: Option<InitFailureHint>,
        /// What the server wrote to stderr before failing, if anything.
        stderr: Option<StderrExcerpt>,
    },

    /// LSP server returned an error response.
    ///
    /// The payload keeps the message verbatim for diagnostics (logging,
    /// `Debug`, pattern matching). The `Display` impl rewrites known-internal
    /// upstream text before it reaches an MCP caller, so `message` is not
    /// always what the caller sees.
    #[error("LSP server error: {} - {}", .0.code, sanitize_lsp_server_message(&.0.message))]
    LspServerError(JsonRpcError),

    /// The MCP server could not complete its handshake with the client.
    #[error("failed to start MCP server")]
    McpServerStart(#[source] Box<dyn std::error::Error + Send + Sync>),

    /// A background task panicked or was cancelled.
    #[error("{task} task failed")]
    TaskFailed {
        /// The task that failed.
        task: BackgroundTask,
        /// The join failure, carrying the panic payload or cancellation.
        #[source]
        source: tokio::task::JoinError,
    },

    /// A standard stream of the spawned LSP server could not be captured.
    #[error("failed to capture LSP server {0}")]
    StdioCapture(StdioStream),

    /// The HTTP transport could not bind its listener.
    #[error("failed to bind HTTP listener on {addr}")]
    HttpBind {
        /// Address the listener was asked to bind.
        addr: std::net::SocketAddr,
        /// Underlying I/O error, e.g. `AddrInUse`.
        #[source]
        source: std::io::Error,
    },

    /// Document was not found or could not be opened.
    #[error("document not found: {}", EchoedPath::new(.0))]
    DocumentNotFound(PathBuf),

    /// No LSP server configured for the given language.
    #[error(
        "no LSP server configured for language: {language}{}",
        no_server_detail(.language, .file, .patterns)
    )]
    NoServerForLanguage {
        /// The language detected for the file.
        language: LanguageId,
        /// What identifies the file to the language map: its extension, its
        /// extensionless name, or [`FileKey::Unmappable`].
        file: FileKey,
        /// The `file_patterns` configured across all servers, so the error can
        /// show what was available to map the extension.
        patterns: Arc<[FilePattern]>,
    },

    /// A server is configured for the language, but no server claims this
    /// specific tool (either no server lists it in `handles` and there is no
    /// catch-all, or the server that claimed it failed to spawn with no live
    /// catch-all to rebind to).
    #[error("no server handles tool '{tool}' for language '{language_id}'")]
    NoServerForTool {
        /// Language ID the request was for.
        language_id: LanguageId,
        /// Tool that no server claims.
        tool: ToolKind,
    },

    /// The server configured for this request failed to start and, because
    /// startup failures are never retried, will not become available until
    /// mcpls is restarted.
    ///
    /// Boxed to keep [`Error`] small.
    #[error("{}", .0.failed_to_start())]
    ServerFailedToStart(Box<ServerSpawnFailure>),

    /// LSP server for the language is configured but still initializing.
    #[error(
        "LSP server '{server_id}' is still initializing (large project load in progress); wait and retry the request (this may take a few minutes on large projects)"
    )]
    ServerInitializing {
        /// Routing identity of the server that has not yet registered.
        server_id: ServerId,
    },

    /// The server was restarted on request while this call was in flight or
    /// being routed; the request never reached the replacement.
    #[error(
        "LSP server '{server_id}' was restarted while this request was in flight; retry the request"
    )]
    ServerRestarted {
        /// Routing identity of the restarted server.
        server_id: ServerId,
    },

    /// A symbol name could not be resolved to exactly one position.
    ///
    /// Boxed to keep [`Error`] small.
    #[error("{0}")]
    SymbolResolution(Box<SymbolResolutionData>),

    /// A restart request named servers that are not configured.
    #[error(
        "unknown LSP server(s) {}; configured servers: {}",
        IdList(unknown),
        IdList(configured)
    )]
    UnknownServers {
        /// The requested ids that matched no configured server.
        unknown: Vec<ServerId>,
        /// Every configured server id.
        configured: Vec<ServerId>,
    },

    /// A workspace-wide tool (one with no file to resolve a language from,
    /// e.g. `workspace_symbol_search`) could not be routed because at least
    /// one expected LSP server has not registered yet. Unlike
    /// [`Error::ServerInitializing`], resolution never narrowed down to a
    /// single candidate server, so no `server_id` is available.
    #[error(
        "LSP servers are still initializing (large project load in progress); wait and retry the request (this may take a few minutes on large projects)"
    )]
    WorkspaceServersInitializing,

    /// No LSP server is currently configured.
    #[error("no LSP server configured")]
    NoServerConfigured,

    /// At least one server is configured somewhere in the workspace, but
    /// none of them claims a workspace-wide tool that has no file to
    /// resolve a language from (e.g. `workspace_symbol_search`). The
    /// language-less counterpart of [`Error::NoServerForTool`].
    #[error("no server handles tool '{tool}' (no server's `handles` list or catch-all claims it)")]
    NoServerForWorkspaceTool {
        /// Tool that no server claims anywhere in the workspace.
        tool: ToolKind,
    },

    /// Configuration file not found.
    #[error("configuration file not found: {0}")]
    ConfigNotFound(PathBuf),

    /// Untrusted-workspace mode refused a config file that lies inside the
    /// workspace or the current directory, because the analyzed checkout
    /// controls it. A startup error; never reaches a tool response.
    #[error(
        "config file {} lies inside the workspace or the current directory, which untrusted mode does not trust; move it elsewhere",
        .path.display()
    )]
    ConfigInsideWorkspace {
        /// The canonical path of the config file.
        path: PathBuf,
    },

    /// Invalid configuration.
    #[error(transparent)]
    Config(#[from] ConfigError),

    /// I/O error; displays the OS text once, with no prefix.
    #[error(transparent)]
    Io(#[from] std::io::Error),

    /// JSON serialization/deserialization error.
    #[error("JSON error")]
    Json(#[from] serde_json::Error),

    /// TOML deserialization error.
    ///
    /// Displays the parser's message and position, never the source line it
    /// prints: that line can hold a secret from an `env` table. The parser
    /// error is deliberately not a `source`, so no error chain prints it
    /// either.
    #[error("{0}")]
    TomlDe(TomlParseError),

    /// TOML serialization error.
    #[error(transparent)]
    TomlSer(#[from] toml::ser::Error),

    /// Request timeout, carrying the elapsed limit.
    #[error("request timed out after {0:?}")]
    Timeout(Duration),

    /// LSP server failed to spawn.
    #[error("failed to spawn LSP server '{command}'")]
    ServerSpawnFailed {
        /// Command that failed to spawn.
        command: ServerCommand,
        /// Underlying IO error.
        #[source]
        source: std::io::Error,
    },

    /// LSP server executable was not found.
    ///
    /// Distinct from [`Error::ServerSpawnFailed`] so the message can carry
    /// PATH and install guidance.
    #[error("failed to spawn LSP server '{command}': {io}{}", NotFoundGuidance(.command.as_str(), Platform::CURRENT))]
    ServerNotFound {
        /// Command that could not be found.
        command: ServerCommand,
        /// Underlying IO error. Not a `source()`: the guidance text follows
        /// it, so it is rendered inline to keep the cause before the advice.
        io: std::io::Error,
    },

    /// LSP protocol error during message parsing.
    #[error("LSP protocol error: {}", escape_control(.0.as_str()))]
    LspProtocolError(RedactedText),

    /// None of the resource URIs a `subscriptions/listen` request named
    /// resolves inside the workspace.
    #[error("none of the requested resource URIs resolve inside the workspace")]
    NoResolvableListenUris,

    /// A client-supplied position is out of bounds.
    #[error(transparent)]
    InvalidPositionInput(#[from] InvalidPosition),

    /// A client-supplied range is malformed or too large.
    #[error(transparent)]
    InvalidRangeInput(#[from] InvalidRange),

    /// A client-supplied hierarchy item has an invalid range.
    #[error(transparent)]
    InvalidHierarchyItemInput(#[from] InvalidHierarchyItem),

    /// A client-supplied line lies beyond the end of the tracked document.
    ///
    /// Only the line is checked: an LSP server clamps a character past the
    /// end of its line to the line length (LSP 3.17, `Position`), so such a
    /// character is forwarded unchanged.
    #[error(
        "line {line} is beyond the end of the document (the document ends at line {last_line})"
    )]
    PositionBeyondDocument {
        /// The 1-based line the client supplied.
        line: std::num::NonZeroU32,
        /// The 1-based number of the document's last line.
        last_line: std::num::NonZeroU32,
    },

    /// A client-supplied `lsp-diagnostics://` resource URI was rejected.
    #[error(transparent)]
    ResourceUri(#[from] ResourceUriError),

    /// A path mcpls itself derived could not be represented as a URI.
    #[error("cannot convert path to URI: {}", EchoedPath::new(.0))]
    PathToUri(PathBuf),

    /// Server process terminated unexpectedly.
    #[error("LSP server process terminated unexpectedly")]
    ServerTerminated,

    /// LSP server shutdown did not complete before its deadline.
    #[error("LSP server shutdown did not complete before its deadline")]
    ShutdownTimeout,

    /// LSP server process exited before completing the `initialize`
    /// handshake.
    #[error("LSP server '{command}' exited during initialization{}{}{}", EarlyExitDetail(.command.as_str(), *.exit_code), HintSuffix(.hint), StderrSuffix(.stderr))]
    ServerExitedDuringInit {
        /// Command that was spawned.
        command: ServerCommand,
        /// Exit code, or `None` if the process was terminated by a signal.
        exit_code: Option<i32>,
        /// The likely cause and remedy, when one is known.
        hint: Option<InitFailureHint>,
        /// What the server wrote to stderr before exiting, if anything.
        stderr: Option<StderrExcerpt>,
    },

    /// A crashed server could not be automatically respawned.
    ///
    /// Distinct from [`Self::ServerTerminated`] so a caller (or a log
    /// reader) can tell "the connection just died" apart from "mcpls tried
    /// to bring it back and could not" -- it is crash-looping and is being
    /// backed off.
    #[error(
        "LSP server '{server_id}' is unavailable: crash-looping, retry in {:.1}s",
        .retry_in.as_secs_f64()
    )]
    ServerUnavailable {
        /// Routing identity of the server that could not be respawned.
        server_id: ServerId,
        /// Remaining backoff before the next respawn attempt.
        retry_in: Duration,
    },

    /// Invalid tool parameters provided.
    #[error("invalid tool parameters: {0}")]
    InvalidToolParams(String),

    /// A client-supplied file path is empty or contains a NUL byte.
    #[error(transparent)]
    InvalidClientPath(#[from] InvalidClientPath),

    /// A client-supplied file path is malformed for the filesystem: it runs
    /// through a regular file, or has an invalid or over-long name.
    ///
    /// Produced only while validating the client path
    /// (`WorkspaceRoots::validate`); the same IO kinds raised later, while
    /// reading or opening an already validated file, stay [`Error::FileIo`]
    /// because there they are environmental.
    #[error("malformed file path {}", BoundedDebugPath(.path))]
    MalformedPath {
        /// The path as supplied by the client.
        path: PathBuf,
        /// Underlying I/O error.
        #[source]
        source: std::io::Error,
    },

    /// File I/O error occurred.
    ///
    /// See [`Error::mcp_error_kind`] for the JSON-RPC classification: a
    /// `source.kind() == ErrorKind::NotFound` failure -- whether `path` was
    /// freshly supplied in this request or was tracked from an earlier one
    /// and has since been deleted/moved on disk -- is caller-fault; any
    /// other IO failure is not.
    #[error("file I/O error for {}", BoundedDebugPath(.path))]
    FileIo {
        /// Path to the file.
        path: PathBuf,
        /// Underlying I/O error.
        #[source]
        source: std::io::Error,
    },

    /// Path is outside allowed workspace boundaries.
    #[error("path outside workspace: {}", EchoedPath::new(.0))]
    PathOutsideWorkspace(PathBuf),

    /// No workspace roots are configured, so path-taking operations are
    /// rejected outright rather than allowed unrestricted (fail closed).
    #[error("no workspace roots configured: refusing access to {}", EchoedPath::new(.0))]
    NoWorkspaceRoots(PathBuf),

    /// Document limit exceeded.
    #[error(
        "document limit exceeded: {current}/{max} (raise workspace.max_documents in config to increase this)"
    )]
    DocumentLimitExceeded {
        /// Current number of documents.
        current: usize,
        /// Maximum allowed documents.
        max: std::num::NonZeroUsize,
    },

    /// Resource-subscription limit exceeded for the session.
    ///
    /// See [`Error::mcp_error_kind`] for the JSON-RPC classification: same
    /// shape as [`Self::DocumentLimitExceeded`] -- fires on aggregate
    /// per-session tracker state, not this request's params -- so it is
    /// classified the same way, not `InvalidParams`.
    #[error("subscription limit of {max} reached")]
    SubscriptionLimitReached {
        /// Maximum number of subscriptions allowed per session.
        max: usize,
    },

    /// Too many concurrent `subscriptions/listen` streams are open.
    ///
    /// Transient: a stream closing frees a slot, so it is classified as
    /// retryable (see [`Error::mcp_error_kind`]).
    #[error("listen stream limit of {max} reached; retry once another stream closes")]
    ListenStreamsExhausted {
        /// Maximum number of concurrent listen streams.
        max: usize,
    },

    /// A `subscriptions/listen` request asked for more resource URIs than a
    /// single stream may watch.
    #[error(
        "subscriptions/listen request exceeds the limit of {max} resource URIs or their total size budget"
    )]
    ListenFilterTooLarge {
        /// Maximum number of resource URIs per listen stream.
        max: usize,
    },

    /// File size limit exceeded.
    #[error(
        "file size limit exceeded: {} bytes, max {} bytes (raise workspace.max_file_size in config to increase this)",
        .0.size,
        .0.max
    )]
    FileSizeLimitExceeded(SizeExceeded),

    /// Path exists but does not refer to a regular file (e.g. a FIFO or a
    /// character/block device).
    ///
    /// mcpls refuses to read such paths: their reported size does not bound
    /// how much data reading them could produce, and opening some of them
    /// for reading can block indefinitely waiting for a peer. A Unix domain
    /// socket special file is not covered by this variant -- `open(2)` on
    /// one fails outright (`ENXIO`) before the file-type check that produces
    /// this error ever runs, so it surfaces as [`Self::FileIo`] from a
    /// document read and as [`Self::Io`] from the config loader.
    #[error("not a regular file: {}", EchoedPath::new(.0))]
    NotARegularFile(PathBuf),

    /// All configured LSP servers failed to initialize.
    #[error("all LSP servers failed to initialize: {}", FailureList(failures))]
    AllServersFailedToInit {
        /// Details of each failure.
        failures: Vec<ServerSpawnFailure>,
    },

    /// The server routed for this request does not advertise support for the
    /// requested LSP capability (e.g. no `renameProvider` in its
    /// `ServerCapabilities`).
    #[error("server '{server_id}' does not support capability '{capability}'")]
    CapabilityNotSupported {
        /// Routing identity of the server that lacks the capability.
        server_id: ServerId,
        /// The missing LSP capability, naming the `ServerCapabilities` field
        /// mcpls checked.
        capability: Capability,
    },

    /// The routed server has an active signal indicating its initial
    /// workspace-load/indexing phase is still in progress, and the bounded
    /// wait for it to finish elapsed before it completed. Returned instead
    /// of an unqualified empty/`null` result so a caller cannot mistake
    /// "index not ready yet" for "this position/symbol genuinely has
    /// nothing here".
    #[error(
        "LSP server '{server_id}' is still indexing the workspace after {elapsed_secs}s; wait and retry the request"
    )]
    WorkspaceIndexing {
        /// Routing identity of the server still indexing.
        server_id: ServerId,
        /// How long mcpls waited for readiness before giving up.
        elapsed_secs: u64,
    },
}

/// Bespoke JSON-RPC code for [`Error::WorkspaceIndexing`].
///
/// Picked clear of rmcp's `-32002`/`-32020..-32022`; the range is convention, not a registry.
///
/// # Examples
///
/// ```
/// use mcpls_core::error::WORKSPACE_INDEXING_ERROR_CODE;
///
/// assert_eq!(WORKSPACE_INDEXING_ERROR_CODE, -32050);
/// ```
pub const WORKSPACE_INDEXING_ERROR_CODE: i32 = -32050;

/// Bespoke JSON-RPC code for [`Error::ServerInitializing`].
///
/// Distinct from [`WORKSPACE_INDEXING_ERROR_CODE`] so a client can tell "the
/// server hasn't registered yet" apart from "the server registered but is
/// still indexing" -- both retryable, but for different reasons.
///
/// # Examples
///
/// ```
/// use mcpls_core::error::{SERVER_INITIALIZING_ERROR_CODE, WORKSPACE_INDEXING_ERROR_CODE};
///
/// assert_eq!(SERVER_INITIALIZING_ERROR_CODE, -32051);
/// assert_ne!(SERVER_INITIALIZING_ERROR_CODE, WORKSPACE_INDEXING_ERROR_CODE);
/// ```
pub const SERVER_INITIALIZING_ERROR_CODE: i32 = -32051;

/// Bespoke JSON-RPC code for a resource subscription request rejected
/// because it was served over rmcp's stateless per-request HTTP path (#482).
///
/// Same convention range as [`WORKSPACE_INDEXING_ERROR_CODE`]/
/// [`SERVER_INITIALIZING_ERROR_CODE`], next unused slot.
///
/// # Examples
///
/// ```
/// use mcpls_core::error::{
///     SERVER_INITIALIZING_ERROR_CODE, STATELESS_SUBSCRIPTION_ERROR_CODE,
///     WORKSPACE_INDEXING_ERROR_CODE,
/// };
///
/// assert_eq!(STATELESS_SUBSCRIPTION_ERROR_CODE, -32052);
/// assert_ne!(STATELESS_SUBSCRIPTION_ERROR_CODE, WORKSPACE_INDEXING_ERROR_CODE);
/// assert_ne!(STATELESS_SUBSCRIPTION_ERROR_CODE, SERVER_INITIALIZING_ERROR_CODE);
/// ```
pub const STATELESS_SUBSCRIPTION_ERROR_CODE: i32 = -32052;

/// Bespoke JSON-RPC code for [`Error::ListenStreamsExhausted`].
///
/// Same convention range as [`WORKSPACE_INDEXING_ERROR_CODE`], next unused
/// slot after [`STATELESS_SUBSCRIPTION_ERROR_CODE`].
///
/// # Examples
///
/// ```
/// use mcpls_core::error::{
///     LISTEN_STREAMS_EXHAUSTED_ERROR_CODE, STATELESS_SUBSCRIPTION_ERROR_CODE,
/// };
///
/// assert_eq!(LISTEN_STREAMS_EXHAUSTED_ERROR_CODE, -32053);
/// assert_ne!(LISTEN_STREAMS_EXHAUSTED_ERROR_CODE, STATELESS_SUBSCRIPTION_ERROR_CODE);
/// ```
pub const LISTEN_STREAMS_EXHAUSTED_ERROR_CODE: i32 = -32053;

/// Bespoke JSON-RPC code for [`Error::ServerRestarted`].
///
/// Same convention range as [`WORKSPACE_INDEXING_ERROR_CODE`], next unused
/// slot after [`LISTEN_STREAMS_EXHAUSTED_ERROR_CODE`].
///
/// # Examples
///
/// ```
/// use mcpls_core::error::{LISTEN_STREAMS_EXHAUSTED_ERROR_CODE, SERVER_RESTARTED_ERROR_CODE};
///
/// assert_eq!(SERVER_RESTARTED_ERROR_CODE, -32054);
/// assert_ne!(SERVER_RESTARTED_ERROR_CODE, LISTEN_STREAMS_EXHAUSTED_ERROR_CODE);
/// ```
pub const SERVER_RESTARTED_ERROR_CODE: i32 = -32054;

/// Structured `data` payload of a retryable JSON-RPC error.
///
/// Each variant pairs a bespoke error code ([`Self::code`]) with its own
/// payload, so a code can never be sent with another variant's data. Keys
/// are `snake_case`; the wire form is the variant's fields as a bare object.
///
/// # Examples
///
/// ```
/// use mcpls_core::config::ServerId;
/// use mcpls_core::error::{RetryableErrorData, WORKSPACE_INDEXING_ERROR_CODE};
///
/// let data = RetryableErrorData::WorkspaceIndexing {
///     server_id: ServerId::from_static("rust"),
///     elapsed_secs: 30,
/// };
/// assert_eq!(data.code(), WORKSPACE_INDEXING_ERROR_CODE);
/// assert_eq!(
///     serde_json::to_value(&data).unwrap(),
///     serde_json::json!({"server_id": "rust", "elapsed_secs": 30})
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(untagged)]
pub enum RetryableErrorData {
    /// The routed server is still indexing the workspace.
    WorkspaceIndexing {
        /// Server that is indexing.
        server_id: ServerId,
        /// Seconds spent waiting for indexing to finish before giving up.
        elapsed_secs: u64,
    },
    /// The routed server has not finished initializing.
    ServerInitializing {
        /// Server that is initializing.
        server_id: ServerId,
    },
    /// An expected server has not registered yet and no single candidate
    /// could be narrowed down, so there is no server to name. The braces
    /// keep the wire value an empty object rather than `null`.
    WorkspaceServersInitializing {},
    /// The concurrent `subscriptions/listen` stream limit is reached.
    ListenStreamsExhausted {
        /// Maximum number of concurrent listen streams.
        max_listen_streams: usize,
    },
    /// The routed server was restarted while the request was in flight.
    ServerRestarted {
        /// Server that was restarted.
        server_id: ServerId,
    },
}

impl RetryableErrorData {
    /// The bespoke JSON-RPC error code for this retryable condition.
    #[must_use]
    pub const fn code(&self) -> i32 {
        match self {
            Self::WorkspaceIndexing { .. } => WORKSPACE_INDEXING_ERROR_CODE,
            Self::ServerInitializing { .. } | Self::WorkspaceServersInitializing {} => {
                SERVER_INITIALIZING_ERROR_CODE
            }
            Self::ListenStreamsExhausted { .. } => LISTEN_STREAMS_EXHAUSTED_ERROR_CODE,
            Self::ServerRestarted { .. } => SERVER_RESTARTED_ERROR_CODE,
        }
    }
}

/// JSON-RPC error-code classification for an [`Error`], returned by
/// [`Error::mcp_error_kind`].
///
/// mcpls-core has no dependency on the MCP transport crate, so this carries
/// only plain data; `crate::mcp` is responsible for turning it into the
/// actual wire-level error type.
///
/// # Examples
///
/// ```
/// use mcpls_core::error::{Error, McpErrorKind};
///
/// let err = Error::InvalidToolParams("missing `file_path`".to_string());
/// assert_eq!(err.mcp_error_kind(), McpErrorKind::InvalidParams);
/// ```
///
/// This enum is `#[non_exhaustive]`: match it with a wildcard arm.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum McpErrorKind {
    /// Caller-fault: the request itself was invalid. Maps to JSON-RPC
    /// `-32602` (`INVALID_PARAMS`).
    InvalidParams,
    /// Caller-fault: the position fell outside the document and the server's
    /// raw error was rewritten for display. Maps to `-32602` with the
    /// original error as `data`.
    InvalidPosition(RewrittenServerError),
    /// Caller-fault: a symbol name did not resolve to exactly one position.
    /// Maps to `-32602` with the structured resolution outcome as `data`.
    SymbolResolution(SymbolResolutionData),
    /// A transient, retryable server-side condition, distinct from a crash.
    /// Maps to a bespoke JSON-RPC `code` with a structured `data` payload a
    /// caller can act on mechanically, rather than the generic
    /// `INTERNAL_ERROR`.
    Retryable(RetryableErrorData),
    /// An unexpected server-side failure. Maps to JSON-RPC `-32603`
    /// (`INTERNAL_ERROR`).
    Internal,
}

impl Error {
    /// Classify this error for JSON-RPC error-code mapping.
    ///
    /// Matched exhaustively with no wildcard arm: a newly added [`Error`]
    /// variant must be given an explicit classification here instead of
    /// silently defaulting to [`McpErrorKind::Internal`].
    ///
    /// # Examples
    ///
    /// ```
    /// use mcpls_core::config::ServerId;
    /// use mcpls_core::error::{Error, McpErrorKind};
    ///
    /// let err = Error::WorkspaceIndexing {
    ///     server_id: ServerId::from_static("rust"),
    ///     elapsed_secs: 30,
    /// };
    /// let McpErrorKind::Retryable(data) = err.mcp_error_kind() else {
    ///     panic!("expected a retryable classification");
    /// };
    /// assert_eq!(data.code(), mcpls_core::error::WORKSPACE_INDEXING_ERROR_CODE);
    /// ```
    #[must_use]
    pub fn mcp_error_kind(&self) -> McpErrorKind {
        match self {
            Self::InvalidToolParams(_)
            | Self::UnknownServers { .. }
            | Self::InvalidClientPath(_)
            | Self::MalformedPath { .. }
            | Self::PathOutsideWorkspace(_)
            | Self::NotARegularFile(_)
            | Self::NoResolvableListenUris
            | Self::ResourceUri(_)
            | Self::InvalidPositionInput(_)
            | Self::InvalidRangeInput(_)
            | Self::InvalidHierarchyItemInput(_)
            | Self::PositionBeyondDocument { .. }
            | Self::ListenFilterTooLarge { .. }
            | Self::DocumentNotFound(_)
            | Self::FileSizeLimitExceeded { .. } => McpErrorKind::InvalidParams,

            // Frees up as soon as another listen stream closes.
            Self::ListenStreamsExhausted { max } => {
                McpErrorKind::Retryable(RetryableErrorData::ListenStreamsExhausted {
                    max_listen_streams: *max,
                })
            }

            // A path that doesn't exist -- whether freshly supplied in this
            // request or tracked from an earlier request and then
            // deleted/moved on disk since -- is caller-fault, same as
            // `DocumentNotFound`, and matches the MCP spec's expectation
            // that resource-not-found map to INVALID_PARAMS, not
            // INTERNAL_ERROR (rmcp's `read_resource` handling, SEP-2164).
            // Any other IO failure (permission denied, an invalid-input error
            // while reading an already validated file, etc.) reaching here is
            // a genuine server-side problem the caller cannot fix by changing
            // their request. A malformed client path is `MalformedPath`.
            Self::FileIo { source, .. } => {
                if source.kind() == std::io::ErrorKind::NotFound {
                    McpErrorKind::InvalidParams
                } else {
                    McpErrorKind::Internal
                }
            }

            Self::WorkspaceIndexing {
                server_id,
                elapsed_secs,
            } => McpErrorKind::Retryable(RetryableErrorData::WorkspaceIndexing {
                server_id: server_id.clone(),
                elapsed_secs: *elapsed_secs,
            }),
            Self::ServerInitializing { server_id } => {
                McpErrorKind::Retryable(RetryableErrorData::ServerInitializing {
                    server_id: server_id.clone(),
                })
            }
            Self::SymbolResolution(data) => McpErrorKind::SymbolResolution((**data).clone()),
            Self::ServerRestarted { server_id } => {
                McpErrorKind::Retryable(RetryableErrorData::ServerRestarted {
                    server_id: server_id.clone(),
                })
            }
            // Same condition as `ServerInitializing` -- an expected LSP
            // server hasn't registered yet, retry -- just without a single
            // candidate server narrowed down (see the variant's doc), so
            // there's no `server_id` to report.
            Self::WorkspaceServersInitializing => {
                McpErrorKind::Retryable(RetryableErrorData::WorkspaceServersInitializing {})
            }

            // Same recognized shape `sanitize_lsp_server_message` rewrites
            // for display: rust-analyzer reports this when a position-based
            // request's line/character falls outside the target document --
            // caller-fault. Every other `LspServerError` shape is a genuine
            // server-side problem and stays `Internal`.
            Self::LspServerError(response) if is_invalid_offset(response) => {
                McpErrorKind::InvalidPosition(RewrittenServerError::new(
                    response.code,
                    &response.message,
                ))
            }

            Self::LspInitFailed { .. }
            | Self::LspServerError(..)
            | Self::McpServerStart(_)
            | Self::TaskFailed { .. }
            | Self::StdioCapture(_)
            | Self::PathToUri(_)
            | Self::HttpBind { .. }
            | Self::NoServerForLanguage { .. }
            | Self::NoServerForTool { .. }
            | Self::NoServerConfigured
            | Self::NoServerForWorkspaceTool { .. }
            | Self::ConfigNotFound(_)
            | Self::ConfigInsideWorkspace { .. }
            | Self::Config(_)
            | Self::Io(_)
            | Self::Json(_)
            | Self::TomlDe(_)
            | Self::TomlSer(_)
            | Self::Timeout(_)
            | Self::ServerSpawnFailed { .. }
            | Self::ServerNotFound { .. }
            | Self::LspProtocolError(_)
            | Self::ServerTerminated
            | Self::ShutdownTimeout
            | Self::ServerUnavailable { .. }
            | Self::ServerFailedToStart(_)
            | Self::ServerExitedDuringInit { .. }
            | Self::NoWorkspaceRoots(_)
            // Unlike `FileSizeLimitExceeded`, this fires on aggregate tracker
            // state, not this request's params -- it can succeed unchanged
            // once other documents close, so `InvalidParams` is wrong; not
            // `Retryable` either, since nothing evicts documents on a timer.
            | Self::DocumentLimitExceeded { .. }
            // Same shape as `DocumentLimitExceeded` above -- see this
            // variant's doc comment.
            | Self::SubscriptionLimitReached { .. }
            | Self::AllServersFailedToInit { .. }
            | Self::CapabilityNotSupported { .. } => McpErrorKind::Internal,
        }
    }

    /// A well-formed resource URI whose path cannot be resolved (deleted, outside
    /// the workspace): unsubscribing falls back to the recorded alias (#499).
    /// Every other failure is a malformed URI or an internal fault.
    pub(crate) const fn is_unresolvable_resource(&self) -> bool {
        match self {
            Self::MalformedPath { .. }
            | Self::FileIo { .. }
            | Self::PathOutsideWorkspace(..)
            | Self::NoWorkspaceRoots(..) => true,
            Self::LspInitFailed { .. }
            | Self::LspServerError(..)
            | Self::McpServerStart(..)
            | Self::TaskFailed { .. }
            | Self::StdioCapture(..)
            | Self::HttpBind { .. }
            | Self::DocumentNotFound(..)
            | Self::NoServerForLanguage { .. }
            | Self::NoServerForTool { .. }
            | Self::ServerFailedToStart(..)
            | Self::ServerInitializing { .. }
            | Self::ServerRestarted { .. }
            | Self::SymbolResolution(..)
            | Self::UnknownServers { .. }
            | Self::WorkspaceServersInitializing
            | Self::NoServerConfigured
            | Self::NoServerForWorkspaceTool { .. }
            | Self::ConfigNotFound(..)
            | Self::ConfigInsideWorkspace { .. }
            | Self::Config(..)
            | Self::Io(..)
            | Self::Json(..)
            | Self::TomlDe(..)
            | Self::TomlSer(..)
            | Self::Timeout(..)
            | Self::ServerSpawnFailed { .. }
            | Self::ServerNotFound { .. }
            | Self::LspProtocolError(..)
            | Self::NoResolvableListenUris
            | Self::InvalidPositionInput(..)
            | Self::InvalidRangeInput(..)
            | Self::InvalidHierarchyItemInput(..)
            | Self::PositionBeyondDocument { .. }
            | Self::ResourceUri(..)
            | Self::PathToUri(..)
            | Self::ServerTerminated
            | Self::ShutdownTimeout
            | Self::ServerExitedDuringInit { .. }
            | Self::ServerUnavailable { .. }
            | Self::InvalidToolParams(..)
            | Self::InvalidClientPath(..)
            | Self::DocumentLimitExceeded { .. }
            | Self::SubscriptionLimitReached { .. }
            | Self::ListenStreamsExhausted { .. }
            | Self::ListenFilterTooLarge { .. }
            | Self::FileSizeLimitExceeded { .. }
            | Self::NotARegularFile(..)
            | Self::AllServersFailedToInit { .. }
            | Self::CapabilityNotSupported { .. }
            | Self::WorkspaceIndexing { .. } => false,
        }
    }
}

/// A TOML parse error that names where it happened without quoting the source.
///
/// The parser's own `Display` quotes the offending source line, which can hold
/// a secret from an `env` table. This type shows the parser's message and the
/// line and column of the error, or its byte span when the source is not at
/// hand.
#[derive(Debug, Clone)]
pub struct TomlParseError {
    error: toml::de::Error,
    line_column: Option<(usize, usize)>,
}

impl TomlParseError {
    /// Wraps `error`, locating it in the `source` text that was parsed.
    ///
    /// # Examples
    ///
    /// ```
    /// use mcpls_core::error::TomlParseError;
    ///
    /// let src = "a = = 1";
    /// let err = toml::from_str::<toml::Table>(src).unwrap_err();
    /// let shown = TomlParseError::new(err, src).to_string();
    /// assert!(shown.contains("line 1"));
    /// assert!(!shown.contains(src));
    /// ```
    #[must_use]
    pub fn new(error: toml::de::Error, source: &str) -> Self {
        let line_column = error
            .span()
            .and_then(|span| source.get(..span.start))
            .map(|before| {
                let line = before.matches('\n').count().saturating_add(1);
                let column = before
                    .rsplit('\n')
                    .next()
                    .map_or_default(|last| last.chars().count())
                    .saturating_add(1);
                (line, column)
            });
        Self { error, line_column }
    }

    /// The parser's message, without the source line.
    #[must_use]
    pub fn message(&self) -> &str {
        self.error.message()
    }
}

impl fmt::Display for TomlParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.message())?;
        if let Some((line, column)) = self.line_column {
            write!(f, " (line {line}, column {column})")
        } else if let Some(span) = self.error.span() {
            write!(f, " (at bytes {}..{})", span.start, span.end)
        } else {
            Ok(())
        }
    }
}

/// A specialized Result type for mcpls-core operations.
pub type Result<T> = std::result::Result<T, Error>;

/// Renders an error followed by every cause in its
/// [`source`](std::error::Error::source) chain, `outer: cause: root`.
///
/// An error type's own message names what failed and leaves the cause to
/// [`std::error::Error::source`]; this is where a reader that wants the whole
/// story (an MCP client, a log line) joins them once. No cause is skipped, so
/// a type must not also print its source in its own message.
///
/// # Examples
///
/// ```
/// use std::path::PathBuf;
///
/// use mcpls_core::error::{Error, ErrorChain};
///
/// let error = Error::FileIo {
///     path: PathBuf::from("a.rs"),
///     source: std::io::Error::new(std::io::ErrorKind::NotFound, "gone"),
/// };
///
/// assert_eq!(ErrorChain(&error).to_string(), "file I/O error for \"a.rs\": gone");
/// ```
#[derive(Debug, Clone, Copy)]
pub struct ErrorChain<'a>(pub &'a (dyn std::error::Error + 'static));

impl fmt::Display for ErrorChain<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)?;
        let mut cause = self.0.source();
        while let Some(error) = cause {
            write!(f, ": {error}")?;
            cause = error.source();
        }
        Ok(())
    }
}

/// An error that renders its whole [`ErrorChain`] from `Display`, for a
/// consumer that prints only the outermost error (serde's `try_from` turns the
/// conversion error into a message with `Display`).
#[derive(Debug)]
pub(crate) struct ChainedError<E>(pub(crate) E);

impl<E> From<E> for ChainedError<E> {
    fn from(error: E) -> Self {
        Self(error)
    }
}

impl<E: std::error::Error + 'static> fmt::Display for ChainedError<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        ErrorChain(&self.0).fmt(f)
    }
}

#[cfg(test)]
mod tests {
    use std::assert_matches;

    use super::*;
    use crate::config::{FileExtension, FileName};
    use crate::util::TRUNCATION_MARKER;

    #[test]
    fn test_all_servers_failed_to_init_error() {
        let failures = vec![
            ServerSpawnFailure {
                server_id: ServerId::from_static("rust"),
                language_id: LanguageId::from_static("rust"),
                command: ServerCommand::from_static("rust-analyzer"),
                reason: StartupFailure::InitTaskPanicked,
            },
            ServerSpawnFailure {
                server_id: ServerId::from_static("python"),
                language_id: LanguageId::from_static("python"),
                command: ServerCommand::from_static("pyright"),
                reason: StartupFailure::InitTaskPanicked,
            },
        ];

        let err = Error::AllServersFailedToInit { failures };

        assert!(err.to_string().contains("all LSP servers failed"));

        // Verify failures are preserved
        if let Error::AllServersFailedToInit { failures: f } = err {
            assert_eq!(f.len(), 2);
            assert_eq!(f[0].language_id, "rust");
            assert_eq!(f[1].language_id, "python");
        } else {
            panic!("Expected AllServersFailedToInit error");
        }
    }

    #[test]
    fn test_server_spawn_failure_display_names_init_panic() {
        let failure = ServerSpawnFailure {
            server_id: ServerId::from_static("typescript"),
            language_id: LanguageId::from_static("typescript"),
            command: ServerCommand::from_static("tsserver"),
            reason: StartupFailure::InitTaskPanicked,
        };

        let display = failure.to_string();
        assert!(display.contains("typescript"));
        assert!(display.contains("tsserver"));
        assert!(display.contains("panicked"));
    }

    #[test]
    fn test_ambiguity_display_lists_at_most_ten_candidates_and_the_hint() {
        let candidates: Vec<SymbolCandidate> = (1..=12)
            .map(|line| SymbolCandidate {
                name: "new".to_string(),
                kind: 6,
                kind_name: "Method".to_string(),
                container: Some("Foo".to_string()),
                line,
                character: 1,
            })
            .collect();
        let text = SymbolResolutionData::Ambiguous {
            name: "new".to_string(),
            candidates,
            truncated: false,
        }
        .to_string();

        assert!(text.contains("12 candidates"), "{text}");
        assert!(
            text.contains("at 10:1") && !text.contains("at 11:1"),
            "{text}"
        );
        assert!(text.contains("; ..."), "{text}");
        assert!(text.contains("`symbol_kind` or `container`"), "{text}");
    }

    #[test]
    fn test_error_display_lsp_init_failed() {
        let err = Error::LspInitFailed {
            phase: InitPhase::Initialize,
            cause: Box::new(Error::Io(std::io::Error::other("server not found"))),
            hint: None,
            stderr: None,
        };
        assert_eq!(
            err.to_string(),
            "LSP server initialization failed: Initialize request failed: server not found"
        );
    }

    #[test]
    fn test_stderr_excerpt_none_when_nothing_visible() {
        assert_eq!(
            StderrExcerpt::complete(b"  \n\x1b\r\n ", &Redactions::default()),
            None
        );
        assert_eq!(StderrExcerpt::complete(b"", &Redactions::default()), None);
    }

    #[test]
    fn test_stderr_excerpt_strips_control_characters_but_keeps_newline_and_tab() {
        let excerpt =
            StderrExcerpt::complete(b"a\x1b[31mb\x00\r\nc\td", &Redactions::default()).unwrap();
        assert_eq!(excerpt.head(), "a[31mb\nc\td");
    }

    #[test]
    fn test_stderr_excerpt_display_is_single_line() {
        let excerpt =
            StderrExcerpt::complete(b"first\n\n  second  \nthird\n", &Redactions::default())
                .unwrap();
        assert_eq!(excerpt.to_string(), "first | second | third");
    }

    #[test]
    fn test_stderr_excerpt_elided_display_marks_the_gap() {
        let excerpt =
            StderrExcerpt::elided(b"start\nbanner", b"last\nerror", &Redactions::default())
                .unwrap();
        assert!(excerpt.is_elided());
        assert_eq!(excerpt.tail(), Some("last\nerror"));
        assert_eq!(excerpt.to_string(), "start | banner | ... | last | error");
    }

    #[test]
    fn test_stderr_excerpt_elided_drops_utf8_sequences_cut_by_the_split() {
        let text = "é".as_bytes();
        let head = [b"ok ".as_slice(), &text[..1]].concat();
        let tail = [&text[1..], b" end".as_slice()].concat();

        let excerpt = StderrExcerpt::elided(&head, &tail, &Redactions::default()).unwrap();

        assert_eq!(excerpt.head(), "ok");
        assert_eq!(excerpt.tail(), Some("end"));
    }

    fn secrets(pairs: &[(&str, &str)]) -> Redactions {
        Redactions::new(
            pairs
                .iter()
                .map(|(label, value)| ((*label).to_owned(), (*value).to_owned())),
        )
    }

    #[test]
    fn test_stderr_excerpt_redacts_secrets_with_their_label() {
        let excerpt = StderrExcerpt::complete(
            b"token=hunter2hunter2 id=abc",
            &secrets(&[("API_TOKEN", "hunter2hunter2"), ("SHORT_KEY", "abc")]),
        )
        .unwrap();
        assert_eq!(excerpt.head(), "token=[redacted:API_TOKEN] id=abc");
    }

    #[test]
    fn test_stderr_excerpt_redacts_longest_overlapping_secret_whole() {
        let excerpt = StderrExcerpt::complete(
            b"v=abcdefghXYZ12345",
            &secrets(&[("A_KEY", "abcdefgh"), ("B_KEY", "abcdefghXYZ12345")]),
        )
        .unwrap();
        assert_eq!(excerpt.head(), "v=[redacted:B_KEY]");
    }

    #[test]
    fn test_stderr_excerpt_keeps_non_secret_values_visible() {
        let excerpt = StderrExcerpt::complete(
            b"toolchain 'nightly-2024-01-01' is not installed",
            &secrets(&[("API_TOKEN", "hunter2hunter2")]),
        )
        .unwrap();
        assert_eq!(
            excerpt.head(),
            "toolchain 'nightly-2024-01-01' is not installed"
        );
    }

    #[test]
    fn test_stderr_excerpt_redacts_a_secret_split_by_a_control_character() {
        let excerpt = StderrExcerpt::complete(
            "tok=hunter2\u{200B}hunter2".as_bytes(),
            &secrets(&[("API_TOKEN", "hunter2hunter2")]),
        )
        .unwrap();
        assert_eq!(excerpt.head(), "tok=[redacted:API_TOKEN]");
    }

    /// A secret cut in two by the elision boundary: the fragments of at least
    /// four bytes on each side are masked.
    #[test]
    fn test_stderr_excerpt_masks_a_secret_split_across_the_elision_boundary() {
        let redactions = secrets(&[("API_TOKEN", "supersecretvalue")]);

        let excerpt =
            StderrExcerpt::elided(b"token=supersec", b"retvalue done", &redactions).unwrap();

        let shown = excerpt.to_string();
        assert!(!shown.contains("supersec"), "{shown}");
        assert!(!shown.contains("retvalue"), "{shown}");
        assert!(shown.contains("[redacted:API_TOKEN]"), "{shown}");
    }

    #[test]
    fn test_stderr_excerpt_strips_separators_bidi_and_zero_width_characters() {
        let text = "a\u{2028}b\u{2029}c\u{202E}d\u{2066}e\u{200B}f\u{FEFF}g\u{200F}h";

        let excerpt = StderrExcerpt::complete(text.as_bytes(), &Redactions::default()).unwrap();

        assert_eq!(excerpt.head(), "abcdefgh");
    }

    #[test]
    fn test_escape_control_and_stderr_agree_on_deceptive_characters() {
        let deceptive = [
            '\u{061C}',
            '\u{200B}',
            '\u{200C}',
            '\u{200D}',
            '\u{200E}',
            '\u{200F}',
            '\u{2028}',
            '\u{2029}',
            '\u{202A}',
            '\u{202B}',
            '\u{202C}',
            '\u{202D}',
            '\u{202E}',
            '\u{2060}',
            '\u{2066}',
            '\u{2067}',
            '\u{2068}',
            '\u{2069}',
            '\u{FEFF}',
            '\u{00AD}',
            '\u{180E}',
            '\u{2061}',
            '\u{2064}',
            '\u{206A}',
            '\u{206F}',
            '\u{FFF9}',
            '\u{FFFB}',
            '\u{E0000}',
            '\u{E0041}',
            '\u{E007F}',
        ];
        for c in deceptive {
            let text = format!("a{c}b");
            let escaped = crate::util::escape_control(&text);
            assert!(
                !escaped.contains(c),
                "escape_control kept U+{:04X}",
                c as u32
            );
            let excerpt = StderrExcerpt::complete(text.as_bytes(), &Redactions::default()).unwrap();
            assert_eq!(excerpt.head(), "ab", "stderr kept U+{:04X}", c as u32);
        }
    }

    #[test]
    fn test_init_errors_append_stderr_to_display() {
        let stderr = StderrExcerpt::complete(b"fatal: bad config", &Redactions::default());
        let failed = Error::LspInitFailed {
            phase: InitPhase::Initialize,
            cause: Box::new(Error::Io(std::io::Error::other("boom"))),
            hint: None,
            stderr: stderr.clone(),
        };
        assert_eq!(
            failed.to_string(),
            "LSP server initialization failed: Initialize request failed: boom; stderr: fatal: bad config"
        );
        let exited = Error::ServerExitedDuringInit {
            command: crate::config::ServerCommand::from_static("gopls"),
            exit_code: Some(2),
            hint: None,
            stderr,
        };
        assert_eq!(
            exited.to_string(),
            "LSP server 'gopls' exited during initialization with exit code 2; stderr: fatal: bad config"
        );
    }

    #[test]
    fn test_error_display_lsp_server_error() {
        let err = Error::LspServerError(JsonRpcError {
            code: -32600,
            message: "Invalid request".to_string(),
            data: None,
        });
        assert_eq!(
            err.to_string(),
            "LSP server error: -32600 - Invalid request"
        );
    }

    #[test]
    fn test_error_display_lsp_server_error_sanitizes_invalid_offset() {
        let err = Error::LspServerError(JsonRpcError {
            code: -32603,
            message: "Invalid offset LineCol { line: 2291, col: 0 } (line index length: 100417)"
                .to_string(),
            data: None,
        });
        assert_eq!(
            err.to_string(),
            "LSP server error: -32603 - position out of range for this document"
        );
    }

    #[test]
    fn test_error_display_lsp_server_error_sanitizes_wrapped_invalid_offset() {
        // Guards the `contains` (not `starts_with`) match: an upstream
        // wrapper (e.g. an `anyhow::Context`) or a future mcpls-side prefix
        // could prepend text ahead of rust-analyzer's raw message.
        let err = Error::LspServerError(JsonRpcError {
            code: -32803,
            message: "request handler panicked: Invalid offset LineCol { line: 5, col: 0 } \
                      (line index length: 3)"
                .to_string(),
            data: None,
        });
        assert_eq!(
            err.to_string(),
            "LSP server error: -32803 - position out of range for this document"
        );
    }

    #[test]
    fn test_error_display_lsp_server_error_passes_through_unrelated_message() {
        let err = Error::LspServerError(JsonRpcError {
            code: -32602,
            message: "Invalid params: expected object".to_string(),
            data: None,
        });
        assert_eq!(
            err.to_string(),
            "LSP server error: -32602 - Invalid params: expected object"
        );
    }

    #[test]
    fn test_error_display_document_not_found() {
        let err = Error::DocumentNotFound(PathBuf::from("/path/to/file.rs"));
        assert!(err.to_string().contains("document not found"));
        assert!(err.to_string().contains("file.rs"));
    }

    #[test]
    fn test_error_display_no_server_for_language() {
        let err = no_server_for_language("rust");
        assert_eq!(
            err.to_string(),
            "no LSP server configured for language: rust"
        );
    }

    #[test]
    fn test_error_display_workspace_servers_initializing() {
        let err = Error::WorkspaceServersInitializing;
        assert!(err.to_string().contains("still initializing"));
    }

    #[test]
    fn test_error_display_no_server_for_workspace_tool() {
        let err = Error::NoServerForWorkspaceTool {
            tool: crate::config::ToolKind::WorkspaceSymbols,
        };
        assert!(err.to_string().contains("workspace_symbols"));
        assert!(err.to_string().contains("no server's `handles` list"));
    }

    #[test]
    fn test_error_display_timeout() {
        assert_eq!(
            Error::Timeout(Duration::from_secs(30)).to_string(),
            "request timed out after 30s"
        );
        assert_eq!(
            Error::Timeout(Duration::from_millis(500)).to_string(),
            "request timed out after 500ms"
        );
    }

    #[test]
    fn test_error_display_document_limit() {
        let err = Error::DocumentLimitExceeded {
            current: 150,
            max: std::num::NonZeroUsize::new(100).unwrap(),
        };
        assert_eq!(
            err.to_string(),
            "document limit exceeded: 150/100 (raise workspace.max_documents in config to increase this)"
        );
    }

    #[test]
    fn test_error_display_file_size_limit() {
        let err = Error::FileSizeLimitExceeded(SizeExceeded {
            size: 20_000_000,
            max: std::num::NonZeroU64::new(10_000_000).unwrap(),
        });
        assert_eq!(
            err.to_string(),
            "file size limit exceeded: 20000000 bytes, max 10000000 bytes (raise workspace.max_file_size in config to increase this)"
        );
    }

    #[test]
    fn test_error_display_not_a_regular_file() {
        let err = Error::NotARegularFile(PathBuf::from("/tmp/some.fifo"));
        assert_eq!(err.to_string(), "not a regular file: /tmp/some.fifo");
    }

    #[test]
    fn test_error_from_io() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
        let err: Error = io_err.into();
        assert_matches!(err, Error::Io(_));
    }

    #[test]
    fn test_error_from_json() {
        let json_str = "{invalid json}";
        let json_err = serde_json::from_str::<serde_json::Value>(json_str).unwrap_err();
        let err: Error = json_err.into();
        assert_matches!(err, Error::Json(_));
    }

    fn assert_rendered_once(err: &(dyn std::error::Error + 'static), marker: &str) {
        let text = ErrorChain(err).to_string();
        assert_eq!(text.matches(marker).count(), 1, "{text}");
        let segments: Vec<&str> = text.split(": ").collect();
        let distinct: std::collections::HashSet<&str> = segments.iter().copied().collect();
        assert_eq!(distinct.len(), segments.len(), "repeated segment in {text}");
    }

    fn io_sourced_cases() -> Vec<(Error, String)> {
        let io = |marker: &str| std::io::Error::other(marker.to_owned());
        let command = ServerCommand::from_static("rust-analyzer");
        vec![
            (
                Error::HttpBind {
                    addr: std::net::SocketAddr::from(([127, 0, 0, 1], 1)),
                    source: io("bind-marker"),
                },
                "bind-marker".to_owned(),
            ),
            (
                Error::ServerSpawnFailed {
                    command: command.clone(),
                    source: io("spawn-marker"),
                },
                "spawn-marker".to_owned(),
            ),
            (
                Error::ServerNotFound {
                    command: command.clone(),
                    io: io("missing-marker"),
                },
                "missing-marker".to_owned(),
            ),
            (
                Error::LspInitFailed {
                    phase: InitPhase::Initialize,
                    cause: Box::new(Error::ServerSpawnFailed {
                        command,
                        source: io("init-marker"),
                    }),
                    hint: None,
                    stderr: None,
                },
                "init-marker".to_owned(),
            ),
            (
                Error::from(ConfigError::UnresolvableWorkspaceRoot {
                    written: PathBuf::from("root"),
                    base_dir: PathBuf::from("base"),
                    probe: PathBuf::from("base/root"),
                    source: io("root-marker"),
                }),
                "root-marker".to_owned(),
            ),
            (Error::from(io("io-marker")), "io-marker".to_owned()),
            (
                Error::FileIo {
                    path: PathBuf::from("a.rs"),
                    source: io("file-marker"),
                },
                "file-marker".to_owned(),
            ),
            (
                Error::MalformedPath {
                    path: PathBuf::from("b.rs"),
                    source: io("path-marker"),
                },
                "path-marker".to_owned(),
            ),
        ]
    }

    /// #735: every variant that carries a cause renders it exactly once.
    #[tokio::test]
    async fn test_error_chain_renders_each_cause_exactly_once() {
        let toml_text = "[invalid toml";
        let toml_err = toml::from_str::<toml::Value>(toml_text).unwrap_err();
        let json_err = serde_json::from_str::<serde_json::Value>("{bad").unwrap_err();
        let json_text = json_err.to_string();
        let join_error = tokio::spawn(async { panic!("task-marker") })
            .await
            .unwrap_err();
        let url_err = url::Url::parse("http://[").unwrap_err();
        let non_utf8 = String::from_utf8(vec![0xff]).unwrap_err();

        let mut cases = io_sourced_cases();
        cases.extend([
            (
                Error::TomlDe(TomlParseError::new(toml_err.clone(), toml_text)),
                toml_err.message().to_owned(),
            ),
            (Error::from(json_err), json_text),
            (
                Error::McpServerStart("mcp-marker".into()),
                "mcp-marker".to_owned(),
            ),
            (
                Error::TaskFailed {
                    task: BackgroundTask::McpService,
                    source: join_error,
                },
                "task-marker".to_owned(),
            ),
            (
                Error::from(ConfigError::UnsupportedFilePattern {
                    server: ServerId::from_static("rust"),
                    pattern: FilePattern::parse("zz/yy").unwrap_err(),
                }),
                "'zz/yy'".to_owned(),
            ),
            (
                Error::from(ConfigError::NotUtf8(non_utf8.clone())),
                non_utf8.to_string(),
            ),
            (
                Error::from(ResourceUriError::UrlParse(url_err)),
                url_err.to_string(),
            ),
            (
                Error::from(ResourceUriError::ClientPath(InvalidClientPath::Empty)),
                InvalidClientPath::Empty.to_string(),
            ),
        ]);
        for (err, marker) in &cases {
            assert_rendered_once(err, marker);
        }
    }

    #[test]
    fn test_startup_failure_spawn_renders_the_cause_once() {
        let failure = StartupFailure::Spawn(Arc::new(Error::ServerSpawnFailed {
            command: ServerCommand::from_static("rust-analyzer"),
            source: std::io::Error::other("spawn-marker"),
        }));
        let text = failure.to_string();
        assert_eq!(text.matches("spawn-marker").count(), 1, "{text}");
    }

    /// The docs of the echo types state the bounds as numbers (the constants
    /// live in a private module and cannot be linked); this keeps them in step.
    #[test]
    fn test_echo_bound_docs_state_the_constants() {
        let source = include_str!("error.rs");
        for (bytes, doc_marker) in [
            (MAX_ECHOED_NAME_BYTES, "pub struct EchoedArgument"),
            (MAX_ECHOED_PATH_BYTES, "pub struct EchoedPath"),
        ] {
            let before = source.split(doc_marker).next().unwrap();
            let doc = before.rsplit("\n\n").next().unwrap();
            assert!(
                doc.contains(&format!("{bytes} bytes")),
                "{doc_marker}: {doc}"
            );
        }
        let debug_doc = source
            .split("struct BoundedDebugPath")
            .next()
            .and_then(|before| before.rsplit("\n\n").next())
            .unwrap();
        assert!(
            debug_doc.contains(&format!("{MAX_ECHOED_PATH_BYTES} bytes")),
            "{debug_doc}"
        );
    }

    fn debug_of(path: &str) -> String {
        BoundedDebugPath(Path::new(path)).to_string()
    }

    /// #749 FR-013: the debug-quoted path is cut at the bound, on a character
    /// boundary, and within the bound it is the plain `{:?}` text.
    #[test]
    fn test_bounded_debug_path_cuts_at_the_bound() {
        let at_bound = "a".repeat(MAX_ECHOED_PATH_BYTES - 2);
        assert_eq!(debug_of(&at_bound), format!("{:?}", Path::new(&at_bound)));
        assert!(!debug_of(&at_bound).ends_with(TRUNCATION_MARKER));

        let over = "a".repeat(MAX_ECHOED_PATH_BYTES - 1);
        let cut = debug_of(&over);
        assert!(cut.ends_with(TRUNCATION_MARKER), "{cut}");
        assert_eq!(cut.len(), MAX_ECHOED_PATH_BYTES + TRUNCATION_MARKER.len());

        let straddling = "é".repeat(MAX_ECHOED_PATH_BYTES);
        let cut = debug_of(&straddling);
        assert!(cut.ends_with(TRUNCATION_MARKER), "{cut}");
        assert!(cut.len() <= MAX_ECHOED_PATH_BYTES + TRUNCATION_MARKER.len());

        let honest = debug_of("/ws/quote\"d\\ name.rs");
        assert_eq!(honest, format!("{:?}", Path::new("/ws/quote\"d\\ name.rs")));
    }

    /// #749 FR-013: a cut never leaves half an escape sequence before the marker.
    #[test]
    fn test_bounded_debug_path_never_splits_an_escape() {
        for prefix in 0..8 {
            let text = format!(
                "{}{}",
                "a".repeat(prefix),
                "\u{1b}".repeat(MAX_ECHOED_PATH_BYTES)
            );
            let cut = debug_of(&text);
            let body = cut.strip_suffix(TRUNCATION_MARKER).expect("cut");
            let tail = body.rsplit('\\').next().unwrap_or_default();
            assert!(
                tail.is_empty() || (tail.starts_with("u{1b}") && tail == "u{1b}"),
                "prefix {prefix}: ends with {tail:?}"
            );
            assert!(body.len() <= MAX_ECHOED_PATH_BYTES, "{}", body.len());
        }
    }

    /// #749 FR-014: every error that echoes client text renders a bounded
    /// message for a 1 MiB value, and keeps the whole stored value.
    #[test]
    fn test_client_text_echoes_stay_bounded() {
        let huge = "Z".repeat(1 << 20);
        let path = PathBuf::from(format!("/{huge}"));
        let io = || std::io::Error::other("cause");
        let errors = [
            Error::PathOutsideWorkspace(path.clone()),
            Error::NoWorkspaceRoots(path.clone()),
            Error::NotARegularFile(path.clone()),
            Error::DocumentNotFound(path.clone()),
            Error::PathToUri(path.clone()),
            Error::FileIo {
                path: path.clone(),
                source: io(),
            },
            Error::MalformedPath {
                path: path.clone(),
                source: io(),
            },
            Error::from(ResourceUriError::InvalidPath(huge.clone())),
            Error::from(ResourceUriError::InvalidScheme(huge.clone())),
            Error::from(ResourceUriError::NotAFilePath(huge)),
        ];
        for error in &errors {
            let text = ErrorChain(error).to_string();
            let len = text.len();
            assert!(len <= 2 * MAX_ECHOED_PATH_BYTES, "{len} bytes: {text:.80}");
            assert!(text.contains(TRUNCATION_MARKER), "{text:.80}");
        }
        assert_matches!(&errors[0], Error::PathOutsideWorkspace(stored) if *stored == path);
    }

    /// #749 FR-013: a path at the bound is echoed whole, one byte over is cut.
    #[test]
    fn test_path_echo_variants_cut_one_byte_over_the_bound() {
        let at_bound = PathBuf::from("a".repeat(MAX_ECHOED_PATH_BYTES));
        let text = Error::PathOutsideWorkspace(at_bound).to_string();
        assert!(!text.contains(TRUNCATION_MARKER), "{text:.80}");

        let over = PathBuf::from("a".repeat(MAX_ECHOED_PATH_BYTES + 1));
        let text = Error::NotARegularFile(over).to_string();
        assert!(text.ends_with(TRUNCATION_MARKER), "{text:.80}");

        let controls = PathBuf::from("\u{1b}".repeat(MAX_ECHOED_PATH_BYTES));
        let text = Error::NoWorkspaceRoots(controls).to_string();
        assert!(text.len() <= 2 * MAX_ECHOED_PATH_BYTES, "{}", text.len());
    }

    #[test]
    fn test_document_not_found_and_path_to_uri_escape_control_characters() {
        let path = || PathBuf::from("/a\nERROR forged\u{1b}[31m");

        for error in [Error::DocumentNotFound(path()), Error::PathToUri(path())] {
            let text = error.to_string();
            assert!(!text.contains('\n') && !text.contains('\u{1b}'), "{text}");
        }
    }

    #[test]
    fn test_error_chain_joins_causes_once() {
        let not_found = || std::io::Error::new(std::io::ErrorKind::NotFound, "gone");
        let file_io = Error::FileIo {
            path: PathBuf::from("a.rs"),
            source: not_found(),
        };
        let spawn = Error::ServerSpawnFailed {
            command: crate::config::ServerCommand::new("x").unwrap(),
            source: not_found(),
        };

        assert_eq!(
            ErrorChain(&file_io).to_string(),
            "file I/O error for \"a.rs\": gone"
        );
        assert_eq!(
            ErrorChain(&spawn).to_string(),
            "failed to spawn LSP server 'x': gone"
        );
    }

    #[test]
    fn test_toml_parse_error_reports_line_and_column_without_the_line() {
        let text = "a = 1\nsecret = \"sk-SECRET\" bad\n";
        let error = toml::from_str::<toml::Value>(text).unwrap_err();

        let rendered = TomlParseError::new(error, text).to_string();

        assert!(rendered.contains("(line 2, column "), "{rendered}");
        assert!(!rendered.contains("sk-SECRET"), "{rendered}");
    }

    /// #751: the parser quotes the source line of a failed entry; an `env`
    /// secret on it must not reach the error text or its chain.
    #[test]
    fn test_toml_error_never_quotes_an_env_secret() {
        let text = "lsp_servers = [{ language_id = \"rust\", command = \"ra\", \
                    env = { API_TOKEN = \"sk-SECRET\\u0000\" } }]";
        let parse_error = toml::from_str::<crate::config::ServerConfig>(text).unwrap_err();
        let err = Error::TomlDe(TomlParseError::new(parse_error, text));

        let rendered = ErrorChain(&err).to_string();
        assert!(!rendered.contains("sk-SECRET"), "{rendered}");
        assert!(
            rendered.contains("environment variable 'API_TOKEN'"),
            "{rendered}"
        );
        assert!(rendered.contains("cannot contain NUL"), "{rendered}");
    }

    #[test]
    fn test_result_type_alias() {
        fn _returns_error() -> Result<i32> {
            Err(Error::Config(ConfigError::NoParentDirectory {
                path: PathBuf::new(),
            }))
        }

        let result: Result<i32> = Ok(42);
        assert!(result.is_ok());
        if let Ok(value) = result {
            assert_eq!(value, 42);
        }
    }

    fn not_found(command: &str) -> Error {
        Error::ServerNotFound {
            command: crate::config::ServerCommand::new(command).unwrap(),
            io: std::io::Error::from(std::io::ErrorKind::NotFound),
        }
    }

    #[test]
    fn test_server_not_found_bare_builtin_has_path_and_install_hint() {
        let msg = not_found("rust-analyzer").to_string();
        assert!(msg.contains("not on the PATH"), "{msg}");
        assert!(msg.contains("rustup component add rust-analyzer"), "{msg}");
    }

    #[test]
    fn test_server_not_found_bare_unknown_has_no_install_hint() {
        let msg = not_found("my-custom-lsp").to_string();
        assert!(msg.contains("not on the PATH"), "{msg}");
        assert!(!msg.contains("install it"), "{msg}");
        assert!(!msg.contains(".cmd"), "{msg}");
    }

    #[test]
    fn test_server_not_found_path_command_has_no_path_text() {
        let msg = not_found("/nonexistent/rust-analyzer").to_string();
        assert!(msg.contains("configured path exists"), "{msg}");
        assert!(!msg.contains("PATH"), "{msg}");
        assert!(!msg.contains("install it"), "{msg}");
    }

    #[test]
    fn test_lifecycle_errors_map_to_internal() {
        for err in [Error::ShutdownTimeout, not_found("x")] {
            assert_eq!(err.mcp_error_kind(), McpErrorKind::Internal, "{err:?}");
        }
    }

    #[test]
    fn test_not_found_guidance_cmd_note_only_for_npm_builtins_on_windows() {
        let cases = [
            ("pyright-langserver", Platform::Windows, true),
            ("typescript-language-server", Platform::Windows, true),
            ("pyright-langserver", Platform::Other, false),
            ("rust-analyzer", Platform::Windows, false),
            ("gopls", Platform::Windows, false),
            ("my-custom-lsp", Platform::Windows, false),
        ];
        for (command, platform, expects_cmd_note) in cases {
            let msg = NotFoundGuidance(command, platform).to_string();
            assert_eq!(
                msg.contains(".cmd"),
                expects_cmd_note,
                "{command} {platform:?}: {msg}"
            );
        }
    }

    #[test]
    fn test_error_source_chain() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
        let err = Error::ServerSpawnFailed {
            command: crate::config::ServerCommand::from_static("rust-analyzer"),
            source: io_err,
        };

        let source = std::error::Error::source(&err);
        assert!(source.is_some());
    }

    fn spawn_failure(id: &str, command: &str, error: Error) -> ServerSpawnFailure {
        ServerSpawnFailure {
            server_id: ServerId::new(id).unwrap(),
            language_id: LanguageId::new(id).unwrap(),
            command: ServerCommand::new(command).unwrap(),
            reason: StartupFailure::Spawn(Arc::new(error)),
        }
    }

    #[test]
    fn test_server_spawn_failure_display() {
        let failure = spawn_failure(
            "rust",
            "rust-analyzer",
            Error::LspInitFailed {
                phase: InitPhase::Initialize,
                cause: Box::new(Error::Io(std::io::Error::other("boom"))),
                hint: None,
                stderr: None,
            },
        );
        assert_eq!(
            failure.to_string(),
            "rust [rust] (rust-analyzer): LSP server initialization failed: Initialize request failed: boom"
        );
    }

    #[test]
    fn test_server_spawn_failure_clone_shares_reason() {
        let failure = spawn_failure("python", "pyright", not_found("pyright"));
        let cloned = failure.clone();
        assert_eq!(failure.language_id, cloned.language_id);
        assert_eq!(failure.to_string(), cloned.to_string());
    }

    #[test]
    fn test_server_failed_to_start_display_carries_not_found_guidance() {
        let err = Error::ServerFailedToStart(Box::new(spawn_failure(
            "rust",
            "rust-analyzer",
            not_found("rust-analyzer"),
        )));
        let msg = err.to_string();
        assert!(
            msg.contains("'rust' for language 'rust' failed to start"),
            "{msg}"
        );
        assert!(msg.contains("not on the PATH"), "{msg}");
        assert!(msg.contains("rustup component add rust-analyzer"), "{msg}");
        assert!(msg.contains("restart mcpls"), "{msg}");
    }

    #[test]
    fn test_server_failed_to_start_init_task_panicked_display() {
        let err = Error::ServerFailedToStart(Box::new(ServerSpawnFailure {
            server_id: ServerId::from_static("rust"),
            language_id: LanguageId::from_static("rust"),
            command: ServerCommand::from_static("rust-analyzer"),
            reason: StartupFailure::InitTaskPanicked,
        }));
        assert!(err.to_string().contains("initialization task panicked"));
    }

    #[test]
    fn test_startup_errors_map_to_internal() {
        let failure = spawn_failure("rust", "rust-analyzer", not_found("rust-analyzer"));
        for err in [
            Error::ServerFailedToStart(Box::new(failure.clone())),
            Error::AllServersFailedToInit {
                failures: vec![failure],
            },
            Error::ServerExitedDuringInit {
                command: crate::config::ServerCommand::from_static("x"),
                exit_code: Some(1),
                hint: None,
                stderr: None,
            },
            Error::ServerUnavailable {
                server_id: ServerId::from_static("rust"),
                retry_in: Duration::from_secs(1),
            },
        ] {
            assert_eq!(err.mcp_error_kind(), McpErrorKind::Internal, "{err:?}");
        }
    }

    #[test]
    fn test_init_failure_hint_renders_between_detail_and_stderr() {
        let stderr = StderrExcerpt::complete(b"boom", &Redactions::default());
        let hint = Some(InitFailureHint::NativeTypescriptOnly);
        let failed = Error::LspInitFailed {
            phase: InitPhase::Initialize,
            cause: Box::new(Error::Io(std::io::Error::other("x"))),
            hint,
            stderr: stderr.clone(),
        }
        .to_string();
        let exited = Error::ServerExitedDuringInit {
            command: crate::config::ServerCommand::from_static("typescript-language-server"),
            exit_code: Some(1),
            hint,
            stderr,
        }
        .to_string();
        for text in [failed, exited] {
            let hint_at = text.find("TypeScript 7").unwrap();
            assert!(hint_at < text.find("; stderr: boom").unwrap(), "{text}");
            assert!(
                text.contains(BuiltinServer::TypescriptLanguageServer.install_hint()),
                "{text}"
            );
        }
    }

    #[test]
    fn test_server_exited_during_init_display_hints_only_for_rust_analyzer() {
        let hinted = Error::ServerExitedDuringInit {
            command: crate::config::ServerCommand::from_static("rust-analyzer"),
            exit_code: Some(1),
            hint: None,
            stderr: None,
        }
        .to_string();
        assert!(hinted.contains("exit code 1"), "{hinted}");
        assert!(
            hinted.contains("rustup component add rust-analyzer"),
            "{hinted}"
        );

        let plain = Error::ServerExitedDuringInit {
            command: crate::config::ServerCommand::from_static("gopls"),
            exit_code: None,
            hint: None,
            stderr: None,
        }
        .to_string();
        assert!(plain.contains("terminated by a signal"), "{plain}");
        assert!(!plain.contains("rustup"), "{plain}");
    }

    #[test]
    fn test_server_unavailable_display_names_retry_delay() {
        let err = Error::ServerUnavailable {
            server_id: ServerId::from_static("rust"),
            retry_in: Duration::from_secs(2),
        };
        assert_eq!(
            err.to_string(),
            "LSP server 'rust' is unavailable: crash-looping, retry in 2.0s"
        );
    }

    #[test]
    fn test_error_display_all_servers_failed_lists_each_failure() {
        let err = Error::AllServersFailedToInit {
            failures: vec![
                spawn_failure("rust", "rust-analyzer", not_found("rust-analyzer")),
                spawn_failure(
                    "python",
                    "pyright",
                    Error::LspInitFailed {
                        phase: InitPhase::Initialize,
                        cause: Box::new(Error::Io(std::io::Error::other("denied"))),
                        hint: None,
                        stderr: None,
                    },
                ),
            ],
        };
        let msg = err.to_string();
        assert!(
            msg.starts_with("all LSP servers failed to initialize: "),
            "{msg}"
        );
        assert!(msg.contains("rust [rust] (rust-analyzer)"), "{msg}");
        assert!(msg.contains("python [python] (pyright)"), "{msg}");
    }

    #[test]
    fn test_untrusted_refusal_paths_are_escaped_and_bounded() {
        let hostile = PathBuf::from(format!("/ws/evil{}", "\n\u{202e}".repeat(3000)));
        for refusal in [
            UntrustedRefusal::WorkspaceExecutable {
                executable: hostile.clone(),
            },
            UntrustedRefusal::WorkspaceTsserver {
                tsserver: hostile.clone(),
            },
            UntrustedRefusal::WorkspaceHome {
                variable: HomeVariable::Home,
                home: hostile.clone(),
            },
            UntrustedRefusal::NonUtf8Path {
                what: ResolvedItem::Executable,
                path: hostile,
            },
        ] {
            let text = refusal.to_string();
            assert!(!text.contains('\n'), "{text}");
            assert!(!text.contains('\u{202e}'), "{text}");
            assert!(text.len() < MAX_ECHOED_PATH_BYTES + 512, "{}", text.len());
        }
        let name = EchoedArgument::name(&"\u{202e}".repeat(5000));
        assert!(name.as_str().len() < MAX_ECHOED_NAME_BYTES + 64);
    }

    #[test]
    fn test_untrusted_refusal_new_variants_name_their_cause() {
        let launcher = UntrustedRefusal::ProjectLauncher {
            command: ServerCommand::from_static("npx"),
            cause: LauncherRefusal::SelectsWorkspaceCode {
                program: EchoedPath::program("npx"),
                trigger: LaunchTrigger::Always,
            },
        };
        assert!(launcher.to_string().contains("'npx'"), "{launcher}");
        let unpinned = UntrustedRefusal::UnpinnedTypescriptLauncher {
            command: ServerCommand::from_static("pnpm"),
        };
        assert!(unpinned.to_string().contains("'pnpm'"), "{unpinned}");
        let non_utf8 = UntrustedRefusal::NonUtf8Path {
            what: ResolvedItem::SearchPath,
            path: PathBuf::from("/odd"),
        };
        assert_eq!(
            non_utf8.to_string(),
            "its PATH, /odd, is not valid UTF-8, so untrusted mode cannot pass it on"
        );
        assert!(
            UntrustedRefusal::NoSafeWorkingDirectory
                .to_string()
                .contains("outside the workspace")
        );
    }

    fn no_server_for_language(language: &'static str) -> Error {
        Error::NoServerForLanguage {
            language: LanguageId::from_static(language),
            file: FileKey::Unmappable,
            patterns: Arc::default(),
        }
    }

    #[test]
    fn test_no_server_for_plaintext_names_extension_and_patterns() {
        let err = Error::NoServerForLanguage {
            language: LanguageId::PLAINTEXT,
            file: FileKey::Extension(FileExtension::from_static("cpp")),
            patterns: Arc::from([
                FilePattern::from_static("**/*.rs"),
                FilePattern::from_static("**/*.h"),
            ]),
        };
        let message = err.to_string();
        assert!(message.starts_with("no LSP server configured for language: plaintext ("));
        assert!(
            message.contains("file extension 'cpp' is not mapped"),
            "{message}"
        );
        assert!(
            message.contains("configured file_patterns: **/*.rs, **/*.h"),
            "{message}"
        );
    }

    #[test]
    fn test_no_server_for_plaintext_without_patterns_or_extension() {
        let err = Error::NoServerForLanguage {
            language: LanguageId::PLAINTEXT,
            file: FileKey::Unmappable,
            patterns: Arc::default(),
        };
        let message = err.to_string();
        assert!(
            message.contains("the file has no usable extension or name"),
            "{message}"
        );
        assert!(
            message.contains("no file_patterns are configured"),
            "{message}"
        );
    }

    #[test]
    fn test_no_server_for_other_language_text_is_unchanged() {
        let err = Error::NoServerForLanguage {
            language: LanguageId::from_static("nushell"),
            file: FileKey::Extension(FileExtension::from_static("nu")),
            patterns: Arc::from([FilePattern::from_static("**/*.rs")]),
        };
        assert_eq!(
            err.to_string(),
            "no LSP server configured for language: nushell"
        );
    }

    #[test]
    fn test_no_server_for_plaintext_name_suggests_a_name_pattern() {
        let err = Error::NoServerForLanguage {
            language: LanguageId::PLAINTEXT,
            file: FileKey::Name(FileName::from_static("Makefile")),
            patterns: Arc::from([FilePattern::from_static("**/*.rs")]),
        };
        let message = err.to_string();
        assert!(
            message.contains("file name 'Makefile' is not mapped"),
            "{message}"
        );
        assert!(
            message.contains("a `**/Makefile` file_patterns entry"),
            "{message}"
        );
        assert!(!message.contains("*.EXT"), "{message}");
    }

    #[test]
    fn test_error_display_capability_not_supported() {
        let err = Error::CapabilityNotSupported {
            server_id: ServerId::from_static("rust"),
            capability: Capability::Rename,
        };
        assert_eq!(
            err.to_string(),
            "server 'rust' does not support capability 'renameProvider'"
        );
    }

    #[test]
    fn test_error_display_workspace_indexing() {
        let err = Error::WorkspaceIndexing {
            server_id: ServerId::from_static("rust"),
            elapsed_secs: 30,
        };
        assert_eq!(
            err.to_string(),
            "LSP server 'rust' is still indexing the workspace after 30s; wait and retry the request"
        );
    }

    /// #479: caller-fault variants must classify as `InvalidParams`, not fall
    /// through to the generic `Internal` bucket.
    #[test]
    fn test_mcp_error_kind_caller_fault_variants_are_invalid_params() {
        let caller_fault_errors = vec![
            Error::InvalidToolParams("bad params".to_string()),
            Error::PathOutsideWorkspace(PathBuf::from("/etc/passwd")),
            Error::NotARegularFile(PathBuf::from("/dev/null")),
            Error::NoResolvableListenUris,
            Error::ResourceUri(ResourceUriError::InvalidScheme("x".to_string())),
            Error::DocumentNotFound(PathBuf::from("/missing.rs")),
            Error::FileSizeLimitExceeded(SizeExceeded {
                size: 100,
                max: std::num::NonZeroU64::new(10).unwrap(),
            }),
            Error::ListenFilterTooLarge { max: 1000 },
            Error::InvalidClientPath(InvalidClientPath::ContainsNul),
        ];

        for err in caller_fault_errors {
            assert_eq!(
                err.mcp_error_kind(),
                McpErrorKind::InvalidParams,
                "expected {err:?} to classify as InvalidParams"
            );
        }
    }

    #[tokio::test]
    async fn test_mcp_error_kind_internal_failures_are_internal() {
        let join_error = tokio::spawn(async { panic!("boom") }).await.unwrap_err();
        let internal_errors = vec![
            Error::TaskFailed {
                task: BackgroundTask::McpService,
                source: join_error,
            },
            Error::StdioCapture(StdioStream::Stdin),
            Error::PathToUri(PathBuf::from("/x")),
            Error::McpServerStart("handshake".into()),
        ];

        for err in internal_errors {
            assert_eq!(
                err.mcp_error_kind(),
                McpErrorKind::Internal,
                "expected {err:?} to classify as Internal"
            );
        }
    }

    #[tokio::test]
    async fn test_task_failed_keeps_the_panic_payload_as_source() {
        let join_error = tokio::spawn(async { panic!("secret boom") })
            .await
            .unwrap_err();
        let err = Error::TaskFailed {
            task: BackgroundTask::LspReceiver,
            source: join_error,
        };
        let source = std::error::Error::source(&err).unwrap();
        assert!(source.to_string().contains("secret boom"), "{source}");
        assert!(err.to_string().starts_with("LSP receiver task failed"));
    }

    #[test]
    fn test_mcp_error_kind_workspace_indexing_is_retryable_with_dedicated_code() {
        let err = Error::WorkspaceIndexing {
            server_id: ServerId::from_static("rust"),
            elapsed_secs: 30,
        };
        let McpErrorKind::Retryable(data) = err.mcp_error_kind() else {
            panic!("expected WorkspaceIndexing to classify as Retryable");
        };
        assert_eq!(data.code(), WORKSPACE_INDEXING_ERROR_CODE);
        assert_eq!(
            serde_json::to_value(&data).unwrap(),
            serde_json::json!({"server_id": "rust", "elapsed_secs": 30})
        );
    }

    #[test]
    fn test_mcp_error_kind_server_initializing_is_retryable_with_dedicated_code() {
        let err = Error::ServerInitializing {
            server_id: ServerId::from_static("python"),
        };
        let McpErrorKind::Retryable(data) = err.mcp_error_kind() else {
            panic!("expected ServerInitializing to classify as Retryable");
        };
        assert_eq!(data.code(), SERVER_INITIALIZING_ERROR_CODE);
        assert_eq!(
            serde_json::to_value(&data).unwrap(),
            serde_json::json!({"server_id": "python"})
        );
        assert_ne!(
            data.code(),
            WORKSPACE_INDEXING_ERROR_CODE,
            "ServerInitializing must be distinguishable on the wire from WorkspaceIndexing"
        );
    }

    /// `WorkspaceServersInitializing` is `ServerInitializing`'s counterpart
    /// for a resolution that never narrowed down to a single server (see the
    /// variant's doc comment), so it must be retryable too -- a client that
    /// auto-retries on the bespoke retryable code must not treat this as a
    /// hard failure just because no `server_id` was available.
    #[test]
    fn test_mcp_error_kind_workspace_servers_initializing_is_retryable() {
        let err = Error::WorkspaceServersInitializing;
        let McpErrorKind::Retryable(data) = err.mcp_error_kind() else {
            panic!("expected WorkspaceServersInitializing to classify as Retryable");
        };
        assert_eq!(data.code(), SERVER_INITIALIZING_ERROR_CODE);
        assert_eq!(
            serde_json::to_value(&data).unwrap(),
            serde_json::json!({}),
            "the empty struct variant must serialize as `{{}}`, not `null`"
        );
    }

    #[test]
    fn test_retryable_error_data_codes_and_snake_case_keys() {
        let cases = [
            (
                RetryableErrorData::WorkspaceIndexing {
                    server_id: ServerId::from_static("rust"),
                    elapsed_secs: 7,
                },
                WORKSPACE_INDEXING_ERROR_CODE,
                serde_json::json!({"server_id": "rust", "elapsed_secs": 7}),
            ),
            (
                RetryableErrorData::ServerInitializing {
                    server_id: ServerId::from_static("python"),
                },
                SERVER_INITIALIZING_ERROR_CODE,
                serde_json::json!({"server_id": "python"}),
            ),
            (
                RetryableErrorData::WorkspaceServersInitializing {},
                SERVER_INITIALIZING_ERROR_CODE,
                serde_json::json!({}),
            ),
            (
                RetryableErrorData::ListenStreamsExhausted {
                    max_listen_streams: 100,
                },
                LISTEN_STREAMS_EXHAUSTED_ERROR_CODE,
                serde_json::json!({"max_listen_streams": 100}),
            ),
        ];
        for (data, code, wire) in cases {
            assert_eq!(data.code(), code);
            assert_eq!(serde_json::to_value(&data).unwrap(), wire);
        }
    }

    #[test]
    fn test_mcp_error_kind_listen_streams_exhausted_is_retryable() {
        let err = Error::ListenStreamsExhausted { max: 100 };
        let McpErrorKind::Retryable(data) = err.mcp_error_kind() else {
            panic!("expected ListenStreamsExhausted to classify as Retryable");
        };
        assert_eq!(data.code(), LISTEN_STREAMS_EXHAUSTED_ERROR_CODE);
        assert_eq!(
            data,
            RetryableErrorData::ListenStreamsExhausted {
                max_listen_streams: 100
            }
        );
    }

    #[test]
    fn test_mcp_error_kind_unretained_variants_stay_internal() {
        let internal_errors = vec![
            no_server_for_language("python"),
            Error::NoServerForTool {
                language_id: LanguageId::from_static("rust"),
                tool: crate::config::ToolKind::Hover,
            },
            Error::CapabilityNotSupported {
                server_id: ServerId::from_static("rust"),
                capability: Capability::Rename,
            },
            Error::NoWorkspaceRoots(PathBuf::from("/tmp")),
            Error::DocumentLimitExceeded {
                current: 150,
                max: std::num::NonZeroUsize::new(100).unwrap(),
            },
            Error::SubscriptionLimitReached { max: 1000 },
        ];

        for err in internal_errors {
            assert_eq!(
                err.mcp_error_kind(),
                McpErrorKind::Internal,
                "expected {err:?} to classify as Internal"
            );
        }
    }

    /// #479 regression: a client-supplied path that doesn't exist (the
    /// common case behind `WorkspaceRoots::validate`'s `canonicalize()`
    /// failure) must classify as caller-fault, matching `DocumentNotFound`.
    #[test]
    fn test_mcp_error_kind_file_io_not_found_is_invalid_params() {
        let err = Error::FileIo {
            path: PathBuf::from("/no/such/file.rs"),
            source: std::io::Error::new(std::io::ErrorKind::NotFound, "no such file or directory"),
        };
        assert_eq!(err.mcp_error_kind(), McpErrorKind::InvalidParams);
    }

    #[test]
    fn test_position_beyond_document_is_invalid_params_naming_the_line() {
        let err = Error::PositionBeyondDocument {
            line: std::num::NonZeroU32::new(7).unwrap(),
            last_line: std::num::NonZeroU32::new(3).unwrap(),
        };
        assert_eq!(err.mcp_error_kind(), McpErrorKind::InvalidParams);
        assert_eq!(
            err.to_string(),
            "line 7 is beyond the end of the document (the document ends at line 3)"
        );
    }

    /// #575: a malformed client path is caller-fault, whatever IO kind the
    /// validation hit.
    #[test]
    fn test_mcp_error_kind_malformed_path_is_invalid_params() {
        use std::io::ErrorKind;

        for kind in [
            ErrorKind::NotADirectory,
            ErrorKind::InvalidFilename,
            ErrorKind::InvalidInput,
        ] {
            let err = Error::MalformedPath {
                path: PathBuf::from("/ws/main.rs/x"),
                source: std::io::Error::new(kind, "bad path"),
            };
            assert_eq!(
                err.mcp_error_kind(),
                McpErrorKind::InvalidParams,
                "{kind:?}"
            );
        }
    }

    /// The same IO kinds from a post-validation read or open are
    /// environmental, not caller-fault.
    #[test]
    fn test_mcp_error_kind_post_validation_file_io_invalid_input_stays_internal() {
        let err = Error::FileIo {
            path: PathBuf::from("/ws/main.rs"),
            source: std::io::Error::new(std::io::ErrorKind::InvalidInput, "bad input"),
        };
        assert_eq!(err.mcp_error_kind(), McpErrorKind::Internal);
    }

    /// Counterpart: a non-not-found IO failure (permission denied, etc.) is
    /// a genuine server-side problem, not something the caller can fix by
    /// changing their request.
    #[test]
    fn test_mcp_error_kind_file_io_other_kind_stays_internal() {
        let err = Error::FileIo {
            path: PathBuf::from("/root/secret.rs"),
            source: std::io::Error::new(std::io::ErrorKind::PermissionDenied, "permission denied"),
        };
        assert_eq!(err.mcp_error_kind(), McpErrorKind::Internal);
    }

    /// #496: an `LspServerError` carrying the recognized "position out of
    /// range" shape (same substring `sanitize_lsp_server_message` rewrites
    /// for display) is caller-fault, not a generic internal failure.
    #[test]
    fn test_mcp_error_kind_lsp_server_error_invalid_offset_is_invalid_params() {
        let err = Error::LspServerError(JsonRpcError {
            code: -32603,
            message: "Invalid offset LineCol { line: 2291, col: 0 } (line index length: 100417)"
                .to_string(),
            data: None,
        });
        assert_eq!(
            err.mcp_error_kind(),
            McpErrorKind::InvalidPosition(RewrittenServerError::new(
                -32603,
                "Invalid offset LineCol { line: 2291, col: 0 } (line index length: 100417)"
            ))
        );
    }

    /// #465: server-supplied control characters never reach an error `Display`
    /// raw, so a logged or echoed error cannot forge log lines.
    #[test]
    fn test_display_escapes_control_characters_from_the_server() {
        let server_error = Error::LspServerError(JsonRpcError {
            code: -32603,
            message: "boom\nERROR forged\x1b[31m".to_string(),
            data: None,
        });
        assert_eq!(
            server_error.to_string(),
            "LSP server error: -32603 - boom\\nERROR forged\\u{1b}[31m"
        );

        let protocol_error = Error::LspProtocolError(RedactedText::fixed("bad\nline"));
        assert_eq!(protocol_error.to_string(), "LSP protocol error: bad\\nline");
    }

    /// The raw message carried as `data` is bounded at construction.
    #[test]
    fn test_rewritten_server_error_bounds_raw_message() {
        let raw =
            RewrittenServerError::new(-32603, &"x".repeat(MAX_ERROR_MESSAGE_CALLER_BYTES * 2));
        assert!(raw.raw_message().len() < MAX_ERROR_MESSAGE_CALLER_BYTES * 2);
        assert!(raw.raw_message().ends_with("(truncated)"));
    }

    /// Counterpart: an `LspServerError` whose message doesn't match the
    /// recognized position-out-of-range shape is a genuine server-side
    /// problem and must stay `Internal`.
    #[test]
    fn test_mcp_error_kind_lsp_server_error_other_message_stays_internal() {
        let err = Error::LspServerError(JsonRpcError {
            code: -32603,
            message: "internal error".to_string(),
            data: None,
        });
        assert_eq!(err.mcp_error_kind(), McpErrorKind::Internal);
    }

    /// #496: `SubscriptionLimitReached` fires on aggregate per-session
    /// tracker state, not this request's params, so it must classify the
    /// same way as `DocumentLimitExceeded` -- not `InvalidParams`.
    #[test]
    fn test_mcp_error_kind_subscription_limit_reached_stays_internal() {
        let err = Error::SubscriptionLimitReached { max: 1000 };
        assert_eq!(err.mcp_error_kind(), McpErrorKind::Internal);
    }

    fn refusal_failure(refusal: UntrustedRefusal) -> ServerSpawnFailure {
        ServerSpawnFailure {
            server_id: ServerId::from_static("rust"),
            language_id: LanguageId::new("rust").unwrap(),
            command: ServerCommand::from_static("rust-analyzer"),
            reason: StartupFailure::RefusedUntrustedWorkspace(refusal),
        }
    }

    #[test]
    fn test_not_allowed_refusal_names_the_server_class_and_the_remedy() {
        let err =
            Error::ServerFailedToStart(Box::new(refusal_failure(UntrustedRefusal::NotAllowed {
                builtin: Some(BuiltinServer::RustAnalyzer),
            })));
        assert_eq!(
            err.to_string(),
            "LSP server 'rust' for language 'rust' was not started: the workspace is untrusted \
             and it may run workspace code (Cargo build scripts and procedural macros); restart \
             mcpls with `--allow-server rust` to start it"
        );
        assert_eq!(err.mcp_error_kind(), McpErrorKind::Internal);
    }

    #[test]
    fn test_workspace_executable_refusal_offers_no_allow_remedy() {
        let err = Error::ServerFailedToStart(Box::new(refusal_failure(
            UntrustedRefusal::WorkspaceExecutable {
                executable: PathBuf::from("/ws/bin/rust-analyzer"),
            },
        )));
        let text = err.to_string();
        assert!(
            text.contains("its executable /ws/bin/rust-analyzer lies inside the workspace"),
            "{text}"
        );
        assert!(!text.contains("--allow-server"), "{text}");
        assert!(!text.contains("not retried"), "{text}");
    }

    #[test]
    fn test_custom_server_refusal_says_its_workspace_code_is_unknown() {
        let text = UntrustedRefusal::NotAllowed { builtin: None }.to_string();
        assert!(text.contains("not a built-in server"), "{text}");
    }

    #[test]
    fn test_config_inside_workspace_is_a_startup_error_of_kind_internal() {
        let err = Error::ConfigInsideWorkspace {
            path: PathBuf::from("/ws/mcpls.toml"),
        };
        assert!(err.to_string().contains("/ws/mcpls.toml"));
        assert_eq!(err.mcp_error_kind(), McpErrorKind::Internal);
    }

    #[test]
    fn echoed_path_keeps_spaces_and_equals() {
        let path = EchoedPath::new(Path::new("/tmp/out/no such dir/a=b/srv"));
        assert_eq!(path.as_str(), "/tmp/out/no such dir/a=b/srv");
    }

    #[test]
    fn echoed_path_never_cuts_an_escape_in_half() {
        let escape = "\\u{202e}";
        let hostile = "\u{202e}".repeat(MAX_ECHOED_PATH_BYTES);
        let echoed = EchoedPath::new(Path::new(&hostile));
        let kept = echoed
            .as_str()
            .strip_suffix(TRUNCATION_MARKER)
            .expect("an over-long path is marked as truncated");
        assert!(kept.len() <= MAX_ECHOED_PATH_BYTES);
        assert!(
            !kept.is_empty() && kept.len().is_multiple_of(escape.len()),
            "{kept}"
        );
        assert_eq!(kept, escape.repeat(kept.len() / escape.len()));
    }

    #[test]
    fn echoed_program_cuts_an_assignment_but_keeps_a_path() {
        assert_eq!(EchoedPath::program("API_TOKEN=abc").as_str(), "API_TOKEN");
        assert_eq!(EchoedPath::program("X=/tmp/secret").as_str(), "X");
        assert_eq!(
            EchoedPath::program("/tmp/out/a=b/srv").as_str(),
            "/tmp/out/a=b/srv"
        );
        assert_eq!(EchoedPath::program("no such dir").as_str(), "no such dir");
    }

    #[test]
    fn shell_flags_display_the_prefix_they_are_spelled_with() {
        assert_eq!(ShellFlag::PlusC.short_spelling(), Some(('+', 'c')));
        assert_eq!(ShellFlag::PlusC.to_string(), "+c");
        assert_eq!(ShellFlag::DashC.to_string(), "-c");
        assert_eq!(ShellFlag::DashCapitalC.short_spelling(), Some(('-', 'C')));
        let long = ShellFlag::LongCommand(LongCommandName::Command);
        assert_eq!(long.short_spelling(), None);
        assert_eq!(long.to_string(), "--command");
    }

    #[test]
    fn echoed_path_within_the_bound_is_not_marked() {
        let path = "a".repeat(MAX_ECHOED_PATH_BYTES);
        assert_eq!(EchoedPath::new(Path::new(&path)).as_str(), path);
    }

    #[test]
    fn wrapped_program_refusals_name_the_program_its_launcher_starts() {
        let program = EchoedPath::new(Path::new("/tmp/out/a=b"));
        let text = UntrustedRefusal::WrappedProgramPathContainsEquals { program }.to_string();
        assert!(text.contains("'/tmp/out/a=b'"), "{text}");
        assert!(text.contains("the program '"), "{text}");
        assert!(!text.contains("its launcher '/tmp"), "{text}");
    }
}